Rename objc_lifetime -> objc_ownership, and modify diagnostics to talk about 'ownersh...
[clang/stm8.git] / lib / Sema / SemaExpr.cpp
blob3fdfb63c10b9df625707386ede7139a15980a318
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/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Designator.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/ParsedTemplate.h"
39 #include "clang/Sema/Template.h"
40 using namespace clang;
41 using namespace sema;
44 /// \brief Determine whether the use of this declaration is valid, and
45 /// emit any corresponding diagnostics.
46 ///
47 /// This routine diagnoses various problems with referencing
48 /// declarations that can occur when using a declaration. For example,
49 /// it might warn if a deprecated or unavailable declaration is being
50 /// used, or produce an error (and return true) if a C++0x deleted
51 /// function is being used.
52 ///
53 /// If IgnoreDeprecated is set to true, this should not warn about deprecated
54 /// decls.
55 ///
56 /// \returns true if there was an error (this declaration cannot be
57 /// referenced), false otherwise.
58 ///
59 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
60 const ObjCInterfaceDecl *UnknownObjCClass) {
61 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
62 // If there were any diagnostics suppressed by template argument deduction,
63 // emit them now.
64 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
65 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66 if (Pos != SuppressedDiagnostics.end()) {
67 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
68 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69 Diag(Suppressed[I].first, Suppressed[I].second);
71 // Clear out the list of suppressed diagnostics, so that we don't emit
72 // them again for this specialization. However, we don't obsolete this
73 // entry from the table, because we want to avoid ever emitting these
74 // diagnostics again.
75 Suppressed.clear();
79 // See if this is an auto-typed variable whose initializer we are parsing.
80 if (ParsingInitForAutoVars.count(D)) {
81 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82 << D->getDeclName();
83 return true;
86 // See if this is a deleted function.
87 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
88 if (FD->isDeleted()) {
89 Diag(Loc, diag::err_deleted_function_use);
90 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
91 return true;
95 // See if this declaration is unavailable or deprecated.
96 std::string Message;
97 switch (D->getAvailability(&Message)) {
98 case AR_Available:
99 case AR_NotYetIntroduced:
100 break;
102 case AR_Deprecated:
103 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
104 break;
106 case AR_Unavailable:
107 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
108 if (Message.empty()) {
109 if (!UnknownObjCClass)
110 Diag(Loc, diag::err_unavailable) << D->getDeclName();
111 else
112 Diag(Loc, diag::warn_unavailable_fwdclass_message)
113 << D->getDeclName();
115 else
116 Diag(Loc, diag::err_unavailable_message)
117 << D->getDeclName() << Message;
118 Diag(D->getLocation(), diag::note_unavailable_here)
119 << isa<FunctionDecl>(D) << false;
121 break;
124 // Warn if this is used but marked unused.
125 if (D->hasAttr<UnusedAttr>())
126 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
128 return false;
131 /// \brief Retrieve the message suffix that should be added to a
132 /// diagnostic complaining about the given function being deleted or
133 /// unavailable.
134 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
135 // FIXME: C++0x implicitly-deleted special member functions could be
136 // detected here so that we could improve diagnostics to say, e.g.,
137 // "base class 'A' had a deleted copy constructor".
138 if (FD->isDeleted())
139 return std::string();
141 std::string Message;
142 if (FD->getAvailability(&Message))
143 return ": " + Message;
145 return std::string();
148 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
149 /// (and other functions in future), which have been declared with sentinel
150 /// attribute. It warns if call does not have the sentinel argument.
152 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
153 Expr **Args, unsigned NumArgs) {
154 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
155 if (!attr)
156 return;
158 // FIXME: In C++0x, if any of the arguments are parameter pack
159 // expansions, we can't check for the sentinel now.
160 int sentinelPos = attr->getSentinel();
161 int nullPos = attr->getNullPos();
163 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
164 // base class. Then we won't be needing two versions of the same code.
165 unsigned int i = 0;
166 bool warnNotEnoughArgs = false;
167 int isMethod = 0;
168 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
169 // skip over named parameters.
170 ObjCMethodDecl::param_iterator P, E = MD->param_end();
171 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
172 if (nullPos)
173 --nullPos;
174 else
175 ++i;
177 warnNotEnoughArgs = (P != E || i >= NumArgs);
178 isMethod = 1;
179 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
180 // skip over named parameters.
181 ObjCMethodDecl::param_iterator P, E = FD->param_end();
182 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
183 if (nullPos)
184 --nullPos;
185 else
186 ++i;
188 warnNotEnoughArgs = (P != E || i >= NumArgs);
189 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
190 // block or function pointer call.
191 QualType Ty = V->getType();
192 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
193 const FunctionType *FT = Ty->isFunctionPointerType()
194 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
195 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
196 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
197 unsigned NumArgsInProto = Proto->getNumArgs();
198 unsigned k;
199 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
200 if (nullPos)
201 --nullPos;
202 else
203 ++i;
205 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
207 if (Ty->isBlockPointerType())
208 isMethod = 2;
209 } else
210 return;
211 } else
212 return;
214 if (warnNotEnoughArgs) {
215 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
216 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
217 return;
219 int sentinel = i;
220 while (sentinelPos > 0 && i < NumArgs-1) {
221 --sentinelPos;
222 ++i;
224 if (sentinelPos > 0) {
225 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
226 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
227 return;
229 while (i < NumArgs-1) {
230 ++i;
231 ++sentinel;
233 Expr *sentinelExpr = Args[sentinel];
234 if (!sentinelExpr) return;
235 if (sentinelExpr->isTypeDependent()) return;
236 if (sentinelExpr->isValueDependent()) return;
238 // nullptr_t is always treated as null.
239 if (sentinelExpr->getType()->isNullPtrType()) return;
241 if (sentinelExpr->getType()->isAnyPointerType() &&
242 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
243 Expr::NPC_ValueDependentIsNull))
244 return;
246 // Unfortunately, __null has type 'int'.
247 if (isa<GNUNullExpr>(sentinelExpr)) return;
249 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
250 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
253 SourceRange Sema::getExprRange(ExprTy *E) const {
254 Expr *Ex = (Expr *)E;
255 return Ex? Ex->getSourceRange() : SourceRange();
258 //===----------------------------------------------------------------------===//
259 // Standard Promotions and Conversions
260 //===----------------------------------------------------------------------===//
262 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
263 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
264 QualType Ty = E->getType();
265 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
267 if (Ty->isFunctionType())
268 E = ImpCastExprToType(E, Context.getPointerType(Ty),
269 CK_FunctionToPointerDecay).take();
270 else if (Ty->isArrayType()) {
271 // In C90 mode, arrays only promote to pointers if the array expression is
272 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
273 // type 'array of type' is converted to an expression that has type 'pointer
274 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
275 // that has type 'array of type' ...". The relevant change is "an lvalue"
276 // (C90) to "an expression" (C99).
278 // C++ 4.2p1:
279 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
280 // T" can be converted to an rvalue of type "pointer to T".
282 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
283 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
284 CK_ArrayToPointerDecay).take();
286 return Owned(E);
289 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
290 // Check to see if we are dereferencing a null pointer. If so,
291 // and if not volatile-qualified, this is undefined behavior that the
292 // optimizer will delete, so warn about it. People sometimes try to use this
293 // to get a deterministic trap and are surprised by clang's behavior. This
294 // only handles the pattern "*null", which is a very syntactic check.
295 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
296 if (UO->getOpcode() == UO_Deref &&
297 UO->getSubExpr()->IgnoreParenCasts()->
298 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
299 !UO->getType().isVolatileQualified()) {
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::warn_indirection_through_null)
302 << UO->getSubExpr()->getSourceRange());
303 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
304 S.PDiag(diag::note_indirection_through_null));
308 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
309 // C++ [conv.lval]p1:
310 // A glvalue of a non-function, non-array type T can be
311 // converted to a prvalue.
312 if (!E->isGLValue()) return Owned(E);
314 QualType T = E->getType();
315 assert(!T.isNull() && "r-value conversion on typeless expression?");
317 // Create a load out of an ObjCProperty l-value, if necessary.
318 if (E->getObjectKind() == OK_ObjCProperty) {
319 ExprResult Res = ConvertPropertyForRValue(E);
320 if (Res.isInvalid())
321 return Owned(E);
322 E = Res.take();
323 if (!E->isGLValue())
324 return Owned(E);
327 // We don't want to throw lvalue-to-rvalue casts on top of
328 // expressions of certain types in C++.
329 if (getLangOptions().CPlusPlus &&
330 (E->getType() == Context.OverloadTy ||
331 T->isDependentType() ||
332 T->isRecordType()))
333 return Owned(E);
335 // The C standard is actually really unclear on this point, and
336 // DR106 tells us what the result should be but not why. It's
337 // generally best to say that void types just doesn't undergo
338 // lvalue-to-rvalue at all. Note that expressions of unqualified
339 // 'void' type are never l-values, but qualified void can be.
340 if (T->isVoidType())
341 return Owned(E);
343 CheckForNullPointerDereference(*this, E);
345 // C++ [conv.lval]p1:
346 // [...] If T is a non-class type, the type of the prvalue is the
347 // cv-unqualified version of T. Otherwise, the type of the
348 // rvalue is T.
350 // C99 6.3.2.1p2:
351 // If the lvalue has qualified type, the value has the unqualified
352 // version of the type of the lvalue; otherwise, the value has the
353 // type of the lvalue.
354 if (T.hasQualifiers())
355 T = T.getUnqualifiedType();
357 CheckArrayAccess(E);
359 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
360 E, 0, VK_RValue));
363 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
364 ExprResult Res = DefaultFunctionArrayConversion(E);
365 if (Res.isInvalid())
366 return ExprError();
367 Res = DefaultLvalueConversion(Res.take());
368 if (Res.isInvalid())
369 return ExprError();
370 return move(Res);
374 /// UsualUnaryConversions - Performs various conversions that are common to most
375 /// operators (C99 6.3). The conversions of array and function types are
376 /// sometimes suppressed. For example, the array->pointer conversion doesn't
377 /// apply if the array is an argument to the sizeof or address (&) operators.
378 /// In these instances, this routine should *not* be called.
379 ExprResult Sema::UsualUnaryConversions(Expr *E) {
380 // First, convert to an r-value.
381 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
382 if (Res.isInvalid())
383 return Owned(E);
384 E = Res.take();
386 QualType Ty = E->getType();
387 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
389 // Try to perform integral promotions if the object has a theoretically
390 // promotable type.
391 if (Ty->isIntegralOrUnscopedEnumerationType()) {
392 // C99 6.3.1.1p2:
394 // The following may be used in an expression wherever an int or
395 // unsigned int may be used:
396 // - an object or expression with an integer type whose integer
397 // conversion rank is less than or equal to the rank of int
398 // and unsigned int.
399 // - A bit-field of type _Bool, int, signed int, or unsigned int.
401 // If an int can represent all values of the original type, the
402 // value is converted to an int; otherwise, it is converted to an
403 // unsigned int. These are called the integer promotions. All
404 // other types are unchanged by the integer promotions.
406 QualType PTy = Context.isPromotableBitField(E);
407 if (!PTy.isNull()) {
408 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
409 return Owned(E);
411 if (Ty->isPromotableIntegerType()) {
412 QualType PT = Context.getPromotedIntegerType(Ty);
413 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
414 return Owned(E);
417 return Owned(E);
420 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
421 /// do not have a prototype. Arguments that have type float are promoted to
422 /// double. All other argument types are converted by UsualUnaryConversions().
423 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
424 QualType Ty = E->getType();
425 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
427 ExprResult Res = UsualUnaryConversions(E);
428 if (Res.isInvalid())
429 return Owned(E);
430 E = Res.take();
432 // If this is a 'float' (CVR qualified or typedef) promote to double.
433 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
434 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
436 return Owned(E);
439 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
440 /// will warn if the resulting type is not a POD type, and rejects ObjC
441 /// interfaces passed by value.
442 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
443 FunctionDecl *FDecl) {
444 ExprResult ExprRes = CheckPlaceholderExpr(E);
445 if (ExprRes.isInvalid())
446 return ExprError();
448 ExprRes = DefaultArgumentPromotion(E);
449 if (ExprRes.isInvalid())
450 return ExprError();
451 E = ExprRes.take();
453 // __builtin_va_start takes the second argument as a "varargs" argument, but
454 // it doesn't actually do anything with it. It doesn't need to be non-pod
455 // etc.
456 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
457 return Owned(E);
459 // Don't allow one to pass an Objective-C interface to a vararg.
460 if (E->getType()->isObjCObjectType() &&
461 DiagRuntimeBehavior(E->getLocStart(), 0,
462 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
463 << E->getType() << CT))
464 return ExprError();
466 if (!E->getType().isPODType(Context)) {
467 // C++0x [expr.call]p7:
468 // Passing a potentially-evaluated argument of class type (Clause 9)
469 // having a non-trivial copy constructor, a non-trivial move constructor,
470 // or a non-trivial destructor, with no corresponding parameter,
471 // is conditionally-supported with implementation-defined semantics.
472 bool TrivialEnough = false;
473 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
474 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
475 if (Record->hasTrivialCopyConstructor() &&
476 Record->hasTrivialMoveConstructor() &&
477 Record->hasTrivialDestructor())
478 TrivialEnough = true;
482 if (!TrivialEnough &&
483 getLangOptions().ObjCAutoRefCount &&
484 E->getType()->isObjCLifetimeType())
485 TrivialEnough = true;
487 if (TrivialEnough) {
488 // Nothing to diagnose. This is okay.
489 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
490 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
491 << getLangOptions().CPlusPlus0x << E->getType()
492 << CT)) {
493 // Turn this into a trap.
494 CXXScopeSpec SS;
495 UnqualifiedId Name;
496 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
497 E->getLocStart());
498 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
499 if (TrapFn.isInvalid())
500 return ExprError();
502 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
503 MultiExprArg(), E->getLocEnd());
504 if (Call.isInvalid())
505 return ExprError();
507 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
508 Call.get(), E);
509 if (Comma.isInvalid())
510 return ExprError();
512 E = Comma.get();
516 return Owned(E);
519 /// UsualArithmeticConversions - Performs various conversions that are common to
520 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
521 /// routine returns the first non-arithmetic type found. The client is
522 /// responsible for emitting appropriate error diagnostics.
523 /// FIXME: verify the conversion rules for "complex int" are consistent with
524 /// GCC.
525 QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
526 bool isCompAssign) {
527 if (!isCompAssign) {
528 lhsExpr = UsualUnaryConversions(lhsExpr.take());
529 if (lhsExpr.isInvalid())
530 return QualType();
533 rhsExpr = UsualUnaryConversions(rhsExpr.take());
534 if (rhsExpr.isInvalid())
535 return QualType();
537 // For conversion purposes, we ignore any qualifiers.
538 // For example, "const float" and "float" are equivalent.
539 QualType lhs =
540 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
541 QualType rhs =
542 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
544 // If both types are identical, no conversion is needed.
545 if (lhs == rhs)
546 return lhs;
548 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
549 // The caller can deal with this (e.g. pointer + int).
550 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
551 return lhs;
553 // Apply unary and bitfield promotions to the LHS's type.
554 QualType lhs_unpromoted = lhs;
555 if (lhs->isPromotableIntegerType())
556 lhs = Context.getPromotedIntegerType(lhs);
557 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
558 if (!LHSBitfieldPromoteTy.isNull())
559 lhs = LHSBitfieldPromoteTy;
560 if (lhs != lhs_unpromoted && !isCompAssign)
561 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
563 // If both types are identical, no conversion is needed.
564 if (lhs == rhs)
565 return lhs;
567 // At this point, we have two different arithmetic types.
569 // Handle complex types first (C99 6.3.1.8p1).
570 bool LHSComplexFloat = lhs->isComplexType();
571 bool RHSComplexFloat = rhs->isComplexType();
572 if (LHSComplexFloat || RHSComplexFloat) {
573 // if we have an integer operand, the result is the complex type.
575 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
576 if (rhs->isIntegerType()) {
577 QualType fp = cast<ComplexType>(lhs)->getElementType();
578 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
579 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
580 } else {
581 assert(rhs->isComplexIntegerType());
582 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
584 return lhs;
587 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
588 if (!isCompAssign) {
589 // int -> float -> _Complex float
590 if (lhs->isIntegerType()) {
591 QualType fp = cast<ComplexType>(rhs)->getElementType();
592 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
593 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
594 } else {
595 assert(lhs->isComplexIntegerType());
596 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
599 return rhs;
602 // This handles complex/complex, complex/float, or float/complex.
603 // When both operands are complex, the shorter operand is converted to the
604 // type of the longer, and that is the type of the result. This corresponds
605 // to what is done when combining two real floating-point operands.
606 // The fun begins when size promotion occur across type domains.
607 // From H&S 6.3.4: When one operand is complex and the other is a real
608 // floating-point type, the less precise type is converted, within it's
609 // real or complex domain, to the precision of the other type. For example,
610 // when combining a "long double" with a "double _Complex", the
611 // "double _Complex" is promoted to "long double _Complex".
612 int order = Context.getFloatingTypeOrder(lhs, rhs);
614 // If both are complex, just cast to the more precise type.
615 if (LHSComplexFloat && RHSComplexFloat) {
616 if (order > 0) {
617 // _Complex float -> _Complex double
618 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
619 return lhs;
621 } else if (order < 0) {
622 // _Complex float -> _Complex double
623 if (!isCompAssign)
624 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
625 return rhs;
627 return lhs;
630 // If just the LHS is complex, the RHS needs to be converted,
631 // and the LHS might need to be promoted.
632 if (LHSComplexFloat) {
633 if (order > 0) { // LHS is wider
634 // float -> _Complex double
635 QualType fp = cast<ComplexType>(lhs)->getElementType();
636 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
637 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
638 return lhs;
641 // RHS is at least as wide. Find its corresponding complex type.
642 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
644 // double -> _Complex double
645 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
647 // _Complex float -> _Complex double
648 if (!isCompAssign && order < 0)
649 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
651 return result;
654 // Just the RHS is complex, so the LHS needs to be converted
655 // and the RHS might need to be promoted.
656 assert(RHSComplexFloat);
658 if (order < 0) { // RHS is wider
659 // float -> _Complex double
660 if (!isCompAssign) {
661 QualType fp = cast<ComplexType>(rhs)->getElementType();
662 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
663 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
665 return rhs;
668 // LHS is at least as wide. Find its corresponding complex type.
669 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
671 // double -> _Complex double
672 if (!isCompAssign)
673 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
675 // _Complex float -> _Complex double
676 if (order > 0)
677 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
679 return result;
682 // Now handle "real" floating types (i.e. float, double, long double).
683 bool LHSFloat = lhs->isRealFloatingType();
684 bool RHSFloat = rhs->isRealFloatingType();
685 if (LHSFloat || RHSFloat) {
686 // If we have two real floating types, convert the smaller operand
687 // to the bigger result.
688 if (LHSFloat && RHSFloat) {
689 int order = Context.getFloatingTypeOrder(lhs, rhs);
690 if (order > 0) {
691 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
692 return lhs;
695 assert(order < 0 && "illegal float comparison");
696 if (!isCompAssign)
697 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
698 return rhs;
701 // If we have an integer operand, the result is the real floating type.
702 if (LHSFloat) {
703 if (rhs->isIntegerType()) {
704 // Convert rhs to the lhs floating point type.
705 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
706 return lhs;
709 // Convert both sides to the appropriate complex float.
710 assert(rhs->isComplexIntegerType());
711 QualType result = Context.getComplexType(lhs);
713 // _Complex int -> _Complex float
714 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
716 // float -> _Complex float
717 if (!isCompAssign)
718 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
720 return result;
723 assert(RHSFloat);
724 if (lhs->isIntegerType()) {
725 // Convert lhs to the rhs floating point type.
726 if (!isCompAssign)
727 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
728 return rhs;
731 // Convert both sides to the appropriate complex float.
732 assert(lhs->isComplexIntegerType());
733 QualType result = Context.getComplexType(rhs);
735 // _Complex int -> _Complex float
736 if (!isCompAssign)
737 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
739 // float -> _Complex float
740 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
742 return result;
745 // Handle GCC complex int extension.
746 // FIXME: if the operands are (int, _Complex long), we currently
747 // don't promote the complex. Also, signedness?
748 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
749 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
750 if (lhsComplexInt && rhsComplexInt) {
751 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
752 rhsComplexInt->getElementType());
753 assert(order && "inequal types with equal element ordering");
754 if (order > 0) {
755 // _Complex int -> _Complex long
756 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
757 return lhs;
760 if (!isCompAssign)
761 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
762 return rhs;
763 } else if (lhsComplexInt) {
764 // int -> _Complex int
765 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
766 return lhs;
767 } else if (rhsComplexInt) {
768 // int -> _Complex int
769 if (!isCompAssign)
770 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
771 return rhs;
774 // Finally, we have two differing integer types.
775 // The rules for this case are in C99 6.3.1.8
776 int compare = Context.getIntegerTypeOrder(lhs, rhs);
777 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
778 rhsSigned = rhs->hasSignedIntegerRepresentation();
779 if (lhsSigned == rhsSigned) {
780 // Same signedness; use the higher-ranked type
781 if (compare >= 0) {
782 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
783 return lhs;
784 } else if (!isCompAssign)
785 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
786 return rhs;
787 } else if (compare != (lhsSigned ? 1 : -1)) {
788 // The unsigned type has greater than or equal rank to the
789 // signed type, so use the unsigned type
790 if (rhsSigned) {
791 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
792 return lhs;
793 } else if (!isCompAssign)
794 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
795 return rhs;
796 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
797 // The two types are different widths; if we are here, that
798 // means the signed type is larger than the unsigned type, so
799 // use the signed type.
800 if (lhsSigned) {
801 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
802 return lhs;
803 } else if (!isCompAssign)
804 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
805 return rhs;
806 } else {
807 // The signed type is higher-ranked than the unsigned type,
808 // but isn't actually any bigger (like unsigned int and long
809 // on most 32-bit systems). Use the unsigned type corresponding
810 // to the signed type.
811 QualType result =
812 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
813 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
814 if (!isCompAssign)
815 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
816 return result;
820 //===----------------------------------------------------------------------===//
821 // Semantic Analysis for various Expression Types
822 //===----------------------------------------------------------------------===//
825 ExprResult
826 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
827 SourceLocation DefaultLoc,
828 SourceLocation RParenLoc,
829 Expr *ControllingExpr,
830 MultiTypeArg types,
831 MultiExprArg exprs) {
832 unsigned NumAssocs = types.size();
833 assert(NumAssocs == exprs.size());
835 ParsedType *ParsedTypes = types.release();
836 Expr **Exprs = exprs.release();
838 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
839 for (unsigned i = 0; i < NumAssocs; ++i) {
840 if (ParsedTypes[i])
841 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
842 else
843 Types[i] = 0;
846 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
847 ControllingExpr, Types, Exprs,
848 NumAssocs);
849 delete [] Types;
850 return ER;
853 ExprResult
854 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
855 SourceLocation DefaultLoc,
856 SourceLocation RParenLoc,
857 Expr *ControllingExpr,
858 TypeSourceInfo **Types,
859 Expr **Exprs,
860 unsigned NumAssocs) {
861 bool TypeErrorFound = false,
862 IsResultDependent = ControllingExpr->isTypeDependent(),
863 ContainsUnexpandedParameterPack
864 = ControllingExpr->containsUnexpandedParameterPack();
866 for (unsigned i = 0; i < NumAssocs; ++i) {
867 if (Exprs[i]->containsUnexpandedParameterPack())
868 ContainsUnexpandedParameterPack = true;
870 if (Types[i]) {
871 if (Types[i]->getType()->containsUnexpandedParameterPack())
872 ContainsUnexpandedParameterPack = true;
874 if (Types[i]->getType()->isDependentType()) {
875 IsResultDependent = true;
876 } else {
877 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
878 // complete object type other than a variably modified type."
879 unsigned D = 0;
880 if (Types[i]->getType()->isIncompleteType())
881 D = diag::err_assoc_type_incomplete;
882 else if (!Types[i]->getType()->isObjectType())
883 D = diag::err_assoc_type_nonobject;
884 else if (Types[i]->getType()->isVariablyModifiedType())
885 D = diag::err_assoc_type_variably_modified;
887 if (D != 0) {
888 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
889 << Types[i]->getTypeLoc().getSourceRange()
890 << Types[i]->getType();
891 TypeErrorFound = true;
894 // C1X 6.5.1.1p2 "No two generic associations in the same generic
895 // selection shall specify compatible types."
896 for (unsigned j = i+1; j < NumAssocs; ++j)
897 if (Types[j] && !Types[j]->getType()->isDependentType() &&
898 Context.typesAreCompatible(Types[i]->getType(),
899 Types[j]->getType())) {
900 Diag(Types[j]->getTypeLoc().getBeginLoc(),
901 diag::err_assoc_compatible_types)
902 << Types[j]->getTypeLoc().getSourceRange()
903 << Types[j]->getType()
904 << Types[i]->getType();
905 Diag(Types[i]->getTypeLoc().getBeginLoc(),
906 diag::note_compat_assoc)
907 << Types[i]->getTypeLoc().getSourceRange()
908 << Types[i]->getType();
909 TypeErrorFound = true;
914 if (TypeErrorFound)
915 return ExprError();
917 // If we determined that the generic selection is result-dependent, don't
918 // try to compute the result expression.
919 if (IsResultDependent)
920 return Owned(new (Context) GenericSelectionExpr(
921 Context, KeyLoc, ControllingExpr,
922 Types, Exprs, NumAssocs, DefaultLoc,
923 RParenLoc, ContainsUnexpandedParameterPack));
925 llvm::SmallVector<unsigned, 1> CompatIndices;
926 unsigned DefaultIndex = -1U;
927 for (unsigned i = 0; i < NumAssocs; ++i) {
928 if (!Types[i])
929 DefaultIndex = i;
930 else if (Context.typesAreCompatible(ControllingExpr->getType(),
931 Types[i]->getType()))
932 CompatIndices.push_back(i);
935 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
936 // type compatible with at most one of the types named in its generic
937 // association list."
938 if (CompatIndices.size() > 1) {
939 // We strip parens here because the controlling expression is typically
940 // parenthesized in macro definitions.
941 ControllingExpr = ControllingExpr->IgnoreParens();
942 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
943 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
944 << (unsigned) CompatIndices.size();
945 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
946 E = CompatIndices.end(); I != E; ++I) {
947 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
948 diag::note_compat_assoc)
949 << Types[*I]->getTypeLoc().getSourceRange()
950 << Types[*I]->getType();
952 return ExprError();
955 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
956 // its controlling expression shall have type compatible with exactly one of
957 // the types named in its generic association list."
958 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
959 // We strip parens here because the controlling expression is typically
960 // parenthesized in macro definitions.
961 ControllingExpr = ControllingExpr->IgnoreParens();
962 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
963 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
964 return ExprError();
967 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
968 // type name that is compatible with the type of the controlling expression,
969 // then the result expression of the generic selection is the expression
970 // in that generic association. Otherwise, the result expression of the
971 // generic selection is the expression in the default generic association."
972 unsigned ResultIndex =
973 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
975 return Owned(new (Context) GenericSelectionExpr(
976 Context, KeyLoc, ControllingExpr,
977 Types, Exprs, NumAssocs, DefaultLoc,
978 RParenLoc, ContainsUnexpandedParameterPack,
979 ResultIndex));
982 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
983 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
984 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
985 /// multiple tokens. However, the common case is that StringToks points to one
986 /// string.
988 ExprResult
989 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
990 assert(NumStringToks && "Must have at least one string!");
992 StringLiteralParser Literal(StringToks, NumStringToks, PP);
993 if (Literal.hadError)
994 return ExprError();
996 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
997 for (unsigned i = 0; i != NumStringToks; ++i)
998 StringTokLocs.push_back(StringToks[i].getLocation());
1000 QualType StrTy = Context.CharTy;
1001 if (Literal.AnyWide)
1002 StrTy = Context.getWCharType();
1003 else if (Literal.Pascal)
1004 StrTy = Context.UnsignedCharTy;
1006 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1007 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
1008 StrTy.addConst();
1010 // Get an array type for the string, according to C99 6.4.5. This includes
1011 // the nul terminator character as well as the string length for pascal
1012 // strings.
1013 StrTy = Context.getConstantArrayType(StrTy,
1014 llvm::APInt(32, Literal.GetNumStringChars()+1),
1015 ArrayType::Normal, 0);
1017 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1018 return Owned(StringLiteral::Create(Context, Literal.GetString(),
1019 Literal.AnyWide, Literal.Pascal, StrTy,
1020 &StringTokLocs[0],
1021 StringTokLocs.size()));
1024 enum CaptureResult {
1025 /// No capture is required.
1026 CR_NoCapture,
1028 /// A capture is required.
1029 CR_Capture,
1031 /// A by-ref capture is required.
1032 CR_CaptureByRef,
1034 /// An error occurred when trying to capture the given variable.
1035 CR_Error
1038 /// Diagnose an uncapturable value reference.
1040 /// \param var - the variable referenced
1041 /// \param DC - the context which we couldn't capture through
1042 static CaptureResult
1043 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
1044 VarDecl *var, DeclContext *DC) {
1045 switch (S.ExprEvalContexts.back().Context) {
1046 case Sema::Unevaluated:
1047 // The argument will never be evaluated, so don't complain.
1048 return CR_NoCapture;
1050 case Sema::PotentiallyEvaluated:
1051 case Sema::PotentiallyEvaluatedIfUsed:
1052 break;
1054 case Sema::PotentiallyPotentiallyEvaluated:
1055 // FIXME: delay these!
1056 break;
1059 // Don't diagnose about capture if we're not actually in code right
1060 // now; in general, there are more appropriate places that will
1061 // diagnose this.
1062 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1064 // Certain madnesses can happen with parameter declarations, which
1065 // we want to ignore.
1066 if (isa<ParmVarDecl>(var)) {
1067 // - If the parameter still belongs to the translation unit, then
1068 // we're actually just using one parameter in the declaration of
1069 // the next. This is useful in e.g. VLAs.
1070 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1071 return CR_NoCapture;
1073 // - This particular madness can happen in ill-formed default
1074 // arguments; claim it's okay and let downstream code handle it.
1075 if (S.CurContext == var->getDeclContext()->getParent())
1076 return CR_NoCapture;
1079 DeclarationName functionName;
1080 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1081 functionName = fn->getDeclName();
1082 // FIXME: variable from enclosing block that we couldn't capture from!
1084 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1085 << var->getIdentifier() << functionName;
1086 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1087 << var->getIdentifier();
1089 return CR_Error;
1092 /// There is a well-formed capture at a particular scope level;
1093 /// propagate it through all the nested blocks.
1094 static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1095 const BlockDecl::Capture &capture) {
1096 VarDecl *var = capture.getVariable();
1098 // Update all the inner blocks with the capture information.
1099 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1100 i != e; ++i) {
1101 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1102 innerBlock->Captures.push_back(
1103 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1104 /*nested*/ true, capture.getCopyExpr()));
1105 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1108 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1111 /// shouldCaptureValueReference - Determine if a reference to the
1112 /// given value in the current context requires a variable capture.
1114 /// This also keeps the captures set in the BlockScopeInfo records
1115 /// up-to-date.
1116 static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
1117 ValueDecl *value) {
1118 // Only variables ever require capture.
1119 VarDecl *var = dyn_cast<VarDecl>(value);
1120 if (!var) return CR_NoCapture;
1122 // Fast path: variables from the current context never require capture.
1123 DeclContext *DC = S.CurContext;
1124 if (var->getDeclContext() == DC) return CR_NoCapture;
1126 // Only variables with local storage require capture.
1127 // FIXME: What about 'const' variables in C++?
1128 if (!var->hasLocalStorage()) return CR_NoCapture;
1130 // Otherwise, we need to capture.
1132 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
1133 do {
1134 // Only blocks (and eventually C++0x closures) can capture; other
1135 // scopes don't work.
1136 if (!isa<BlockDecl>(DC))
1137 return diagnoseUncapturableValueReference(S, loc, var, DC);
1139 BlockScopeInfo *blockScope =
1140 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1141 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1143 // Check whether we've already captured it in this block. If so,
1144 // we're done.
1145 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1146 return propagateCapture(S, functionScopesIndex,
1147 blockScope->Captures[indexPlus1 - 1]);
1149 functionScopesIndex--;
1150 DC = cast<BlockDecl>(DC)->getDeclContext();
1151 } while (var->getDeclContext() != DC);
1153 // Okay, we descended all the way to the block that defines the variable.
1154 // Actually try to capture it.
1155 QualType type = var->getType();
1157 // Prohibit variably-modified types.
1158 if (type->isVariablyModifiedType()) {
1159 S.Diag(loc, diag::err_ref_vm_type);
1160 S.Diag(var->getLocation(), diag::note_declared_at);
1161 return CR_Error;
1164 // Prohibit arrays, even in __block variables, but not references to
1165 // them.
1166 if (type->isArrayType()) {
1167 S.Diag(loc, diag::err_ref_array_type);
1168 S.Diag(var->getLocation(), diag::note_declared_at);
1169 return CR_Error;
1172 S.MarkDeclarationReferenced(loc, var);
1174 // The BlocksAttr indicates the variable is bound by-reference.
1175 bool byRef = var->hasAttr<BlocksAttr>();
1177 // Build a copy expression.
1178 Expr *copyExpr = 0;
1179 const RecordType *rtype;
1180 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1181 (rtype = type->getAs<RecordType>())) {
1183 // The capture logic needs the destructor, so make sure we mark it.
1184 // Usually this is unnecessary because most local variables have
1185 // their destructors marked at declaration time, but parameters are
1186 // an exception because it's technically only the call site that
1187 // actually requires the destructor.
1188 if (isa<ParmVarDecl>(var))
1189 S.FinalizeVarWithDestructor(var, rtype);
1191 // According to the blocks spec, the capture of a variable from
1192 // the stack requires a const copy constructor. This is not true
1193 // of the copy/move done to move a __block variable to the heap.
1194 type.addConst();
1196 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1197 ExprResult result =
1198 S.PerformCopyInitialization(
1199 InitializedEntity::InitializeBlock(var->getLocation(),
1200 type, false),
1201 loc, S.Owned(declRef));
1203 // Build a full-expression copy expression if initialization
1204 // succeeded and used a non-trivial constructor. Recover from
1205 // errors by pretending that the copy isn't necessary.
1206 if (!result.isInvalid() &&
1207 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1208 result = S.MaybeCreateExprWithCleanups(result);
1209 copyExpr = result.take();
1213 // We're currently at the declarer; go back to the closure.
1214 functionScopesIndex++;
1215 BlockScopeInfo *blockScope =
1216 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1218 // Build a valid capture in this scope.
1219 blockScope->Captures.push_back(
1220 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1221 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1223 // Propagate that to inner captures if necessary.
1224 return propagateCapture(S, functionScopesIndex,
1225 blockScope->Captures.back());
1228 static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1229 const DeclarationNameInfo &NameInfo,
1230 bool byRef) {
1231 assert(isa<VarDecl>(vd) && "capturing non-variable");
1233 VarDecl *var = cast<VarDecl>(vd);
1234 assert(var->hasLocalStorage() && "capturing non-local");
1235 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1237 QualType exprType = var->getType().getNonReferenceType();
1239 BlockDeclRefExpr *BDRE;
1240 if (!byRef) {
1241 // The variable will be bound by copy; make it const within the
1242 // closure, but record that this was done in the expression.
1243 bool constAdded = !exprType.isConstQualified();
1244 exprType.addConst();
1246 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1247 NameInfo.getLoc(), false,
1248 constAdded);
1249 } else {
1250 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1251 NameInfo.getLoc(), true);
1254 return S.Owned(BDRE);
1257 ExprResult
1258 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1259 SourceLocation Loc,
1260 const CXXScopeSpec *SS) {
1261 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1262 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1265 /// BuildDeclRefExpr - Build an expression that references a
1266 /// declaration that does not require a closure capture.
1267 ExprResult
1268 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1269 const DeclarationNameInfo &NameInfo,
1270 const CXXScopeSpec *SS) {
1271 MarkDeclarationReferenced(NameInfo.getLoc(), D);
1273 Expr *E = DeclRefExpr::Create(Context,
1274 SS? SS->getWithLocInContext(Context)
1275 : NestedNameSpecifierLoc(),
1276 D, NameInfo, Ty, VK);
1278 // Just in case we're building an illegal pointer-to-member.
1279 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1280 E->setObjectKind(OK_BitField);
1282 return Owned(E);
1285 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1286 /// possibly a list of template arguments.
1288 /// If this produces template arguments, it is permitted to call
1289 /// DecomposeTemplateName.
1291 /// This actually loses a lot of source location information for
1292 /// non-standard name kinds; we should consider preserving that in
1293 /// some way.
1294 void Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1295 TemplateArgumentListInfo &Buffer,
1296 DeclarationNameInfo &NameInfo,
1297 const TemplateArgumentListInfo *&TemplateArgs) {
1298 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1299 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1300 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1302 ASTTemplateArgsPtr TemplateArgsPtr(*this,
1303 Id.TemplateId->getTemplateArgs(),
1304 Id.TemplateId->NumArgs);
1305 translateTemplateArguments(TemplateArgsPtr, Buffer);
1306 TemplateArgsPtr.release();
1308 TemplateName TName = Id.TemplateId->Template.get();
1309 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1310 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1311 TemplateArgs = &Buffer;
1312 } else {
1313 NameInfo = GetNameFromUnqualifiedId(Id);
1314 TemplateArgs = 0;
1318 /// Diagnose an empty lookup.
1320 /// \return false if new lookup candidates were found
1321 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1322 CorrectTypoContext CTC) {
1323 DeclarationName Name = R.getLookupName();
1325 unsigned diagnostic = diag::err_undeclared_var_use;
1326 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1327 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1328 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1329 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1330 diagnostic = diag::err_undeclared_use;
1331 diagnostic_suggest = diag::err_undeclared_use_suggest;
1334 // If the original lookup was an unqualified lookup, fake an
1335 // unqualified lookup. This is useful when (for example) the
1336 // original lookup would not have found something because it was a
1337 // dependent name.
1338 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1339 DC; DC = DC->getParent()) {
1340 if (isa<CXXRecordDecl>(DC)) {
1341 LookupQualifiedName(R, DC);
1343 if (!R.empty()) {
1344 // Don't give errors about ambiguities in this lookup.
1345 R.suppressDiagnostics();
1347 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1348 bool isInstance = CurMethod &&
1349 CurMethod->isInstance() &&
1350 DC == CurMethod->getParent();
1352 // Give a code modification hint to insert 'this->'.
1353 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1354 // Actually quite difficult!
1355 if (isInstance) {
1356 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1357 CallsUndergoingInstantiation.back()->getCallee());
1358 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1359 CurMethod->getInstantiatedFromMemberFunction());
1360 if (DepMethod) {
1361 Diag(R.getNameLoc(), diagnostic) << Name
1362 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1363 QualType DepThisType = DepMethod->getThisType(Context);
1364 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1365 R.getNameLoc(), DepThisType, false);
1366 TemplateArgumentListInfo TList;
1367 if (ULE->hasExplicitTemplateArgs())
1368 ULE->copyTemplateArgumentsInto(TList);
1370 CXXScopeSpec SS;
1371 SS.Adopt(ULE->getQualifierLoc());
1372 CXXDependentScopeMemberExpr *DepExpr =
1373 CXXDependentScopeMemberExpr::Create(
1374 Context, DepThis, DepThisType, true, SourceLocation(),
1375 SS.getWithLocInContext(Context), NULL,
1376 R.getLookupNameInfo(), &TList);
1377 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1378 } else {
1379 // FIXME: we should be able to handle this case too. It is correct
1380 // to add this-> here. This is a workaround for PR7947.
1381 Diag(R.getNameLoc(), diagnostic) << Name;
1383 } else {
1384 Diag(R.getNameLoc(), diagnostic) << Name;
1387 // Do we really want to note all of these?
1388 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1389 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1391 // Tell the callee to try to recover.
1392 return false;
1395 R.clear();
1399 // We didn't find anything, so try to correct for a typo.
1400 DeclarationName Corrected;
1401 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
1402 if (!R.empty()) {
1403 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1404 if (SS.isEmpty())
1405 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1406 << FixItHint::CreateReplacement(R.getNameLoc(),
1407 R.getLookupName().getAsString());
1408 else
1409 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1410 << Name << computeDeclContext(SS, false) << R.getLookupName()
1411 << SS.getRange()
1412 << FixItHint::CreateReplacement(R.getNameLoc(),
1413 R.getLookupName().getAsString());
1414 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1415 Diag(ND->getLocation(), diag::note_previous_decl)
1416 << ND->getDeclName();
1418 // Tell the callee to try to recover.
1419 return false;
1422 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1423 // FIXME: If we ended up with a typo for a type name or
1424 // Objective-C class name, we're in trouble because the parser
1425 // is in the wrong place to recover. Suggest the typo
1426 // correction, but don't make it a fix-it since we're not going
1427 // to recover well anyway.
1428 if (SS.isEmpty())
1429 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1430 else
1431 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1432 << Name << computeDeclContext(SS, false) << R.getLookupName()
1433 << SS.getRange();
1435 // Don't try to recover; it won't work.
1436 return true;
1438 } else {
1439 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1440 // because we aren't able to recover.
1441 if (SS.isEmpty())
1442 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
1443 else
1444 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1445 << Name << computeDeclContext(SS, false) << Corrected
1446 << SS.getRange();
1447 return true;
1449 R.clear();
1452 // Emit a special diagnostic for failed member lookups.
1453 // FIXME: computing the declaration context might fail here (?)
1454 if (!SS.isEmpty()) {
1455 Diag(R.getNameLoc(), diag::err_no_member)
1456 << Name << computeDeclContext(SS, false)
1457 << SS.getRange();
1458 return true;
1461 // Give up, we can't recover.
1462 Diag(R.getNameLoc(), diagnostic) << Name;
1463 return true;
1466 ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1467 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1468 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1469 if (!IDecl)
1470 return 0;
1471 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1472 if (!ClassImpDecl)
1473 return 0;
1474 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
1475 if (!property)
1476 return 0;
1477 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1478 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1479 PIDecl->getPropertyIvarDecl())
1480 return 0;
1481 return property;
1484 bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1485 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1486 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1487 if (!IDecl)
1488 return false;
1489 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1490 if (!ClassImpDecl)
1491 return false;
1492 if (ObjCPropertyImplDecl *PIDecl
1493 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1494 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1495 PIDecl->getPropertyIvarDecl())
1496 return false;
1498 return true;
1501 ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1502 IdentifierInfo *II,
1503 SourceLocation NameLoc) {
1504 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1505 bool LookForIvars;
1506 if (Lookup.empty())
1507 LookForIvars = true;
1508 else if (CurMeth->isClassMethod())
1509 LookForIvars = false;
1510 else
1511 LookForIvars = (Lookup.isSingleResult() &&
1512 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1513 (Lookup.getAsSingle<VarDecl>() != 0));
1514 if (!LookForIvars)
1515 return 0;
1517 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1518 if (!IDecl)
1519 return 0;
1520 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1521 if (!ClassImpDecl)
1522 return 0;
1523 bool DynamicImplSeen = false;
1524 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
1525 if (!property)
1526 return 0;
1527 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
1528 DynamicImplSeen =
1529 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1530 // property implementation has a designated ivar. No need to assume a new
1531 // one.
1532 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1533 return 0;
1535 if (!DynamicImplSeen) {
1536 QualType PropType = Context.getCanonicalType(property->getType());
1537 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
1538 NameLoc, NameLoc,
1539 II, PropType, /*Dinfo=*/0,
1540 ObjCIvarDecl::Private,
1541 (Expr *)0, true);
1542 ClassImpDecl->addDecl(Ivar);
1543 IDecl->makeDeclVisibleInContext(Ivar, false);
1544 property->setPropertyIvarDecl(Ivar);
1545 return Ivar;
1547 return 0;
1550 ExprResult Sema::ActOnIdExpression(Scope *S,
1551 CXXScopeSpec &SS,
1552 UnqualifiedId &Id,
1553 bool HasTrailingLParen,
1554 bool isAddressOfOperand) {
1555 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1556 "cannot be direct & operand and have a trailing lparen");
1558 if (SS.isInvalid())
1559 return ExprError();
1561 TemplateArgumentListInfo TemplateArgsBuffer;
1563 // Decompose the UnqualifiedId into the following data.
1564 DeclarationNameInfo NameInfo;
1565 const TemplateArgumentListInfo *TemplateArgs;
1566 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1568 DeclarationName Name = NameInfo.getName();
1569 IdentifierInfo *II = Name.getAsIdentifierInfo();
1570 SourceLocation NameLoc = NameInfo.getLoc();
1572 // C++ [temp.dep.expr]p3:
1573 // An id-expression is type-dependent if it contains:
1574 // -- an identifier that was declared with a dependent type,
1575 // (note: handled after lookup)
1576 // -- a template-id that is dependent,
1577 // (note: handled in BuildTemplateIdExpr)
1578 // -- a conversion-function-id that specifies a dependent type,
1579 // -- a nested-name-specifier that contains a class-name that
1580 // names a dependent type.
1581 // Determine whether this is a member of an unknown specialization;
1582 // we need to handle these differently.
1583 bool DependentID = false;
1584 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1585 Name.getCXXNameType()->isDependentType()) {
1586 DependentID = true;
1587 } else if (SS.isSet()) {
1588 if (DeclContext *DC = computeDeclContext(SS, false)) {
1589 if (RequireCompleteDeclContext(SS, DC))
1590 return ExprError();
1591 } else {
1592 DependentID = true;
1596 if (DependentID)
1597 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1598 TemplateArgs);
1600 bool IvarLookupFollowUp = false;
1601 // Perform the required lookup.
1602 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1603 if (TemplateArgs) {
1604 // Lookup the template name again to correctly establish the context in
1605 // which it was found. This is really unfortunate as we already did the
1606 // lookup to determine that it was a template name in the first place. If
1607 // this becomes a performance hit, we can work harder to preserve those
1608 // results until we get here but it's likely not worth it.
1609 bool MemberOfUnknownSpecialization;
1610 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1611 MemberOfUnknownSpecialization);
1613 if (MemberOfUnknownSpecialization ||
1614 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1615 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1616 TemplateArgs);
1617 } else {
1618 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1619 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1621 // If the result might be in a dependent base class, this is a dependent
1622 // id-expression.
1623 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1624 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1625 TemplateArgs);
1627 // If this reference is in an Objective-C method, then we need to do
1628 // some special Objective-C lookup, too.
1629 if (IvarLookupFollowUp) {
1630 ExprResult E(LookupInObjCMethod(R, S, II, true));
1631 if (E.isInvalid())
1632 return ExprError();
1634 if (Expr *Ex = E.takeAs<Expr>())
1635 return Owned(Ex);
1637 // Synthesize ivars lazily.
1638 if (getLangOptions().ObjCDefaultSynthProperties &&
1639 getLangOptions().ObjCNonFragileABI2) {
1640 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
1641 if (const ObjCPropertyDecl *Property =
1642 canSynthesizeProvisionalIvar(II)) {
1643 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1644 Diag(Property->getLocation(), diag::note_property_declare);
1646 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1647 isAddressOfOperand);
1650 // for further use, this must be set to false if in class method.
1651 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1655 if (R.isAmbiguous())
1656 return ExprError();
1658 // Determine whether this name might be a candidate for
1659 // argument-dependent lookup.
1660 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1662 if (R.empty() && !ADL) {
1663 // Otherwise, this could be an implicitly declared function reference (legal
1664 // in C90, extension in C99, forbidden in C++).
1665 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1666 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1667 if (D) R.addDecl(D);
1670 // If this name wasn't predeclared and if this is not a function
1671 // call, diagnose the problem.
1672 if (R.empty()) {
1673 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1674 return ExprError();
1676 assert(!R.empty() &&
1677 "DiagnoseEmptyLookup returned false but added no results");
1679 // If we found an Objective-C instance variable, let
1680 // LookupInObjCMethod build the appropriate expression to
1681 // reference the ivar.
1682 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1683 R.clear();
1684 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1685 assert(E.isInvalid() || E.get());
1686 return move(E);
1691 // This is guaranteed from this point on.
1692 assert(!R.empty() || ADL);
1694 // Check whether this might be a C++ implicit instance member access.
1695 // C++ [class.mfct.non-static]p3:
1696 // When an id-expression that is not part of a class member access
1697 // syntax and not used to form a pointer to member is used in the
1698 // body of a non-static member function of class X, if name lookup
1699 // resolves the name in the id-expression to a non-static non-type
1700 // member of some class C, the id-expression is transformed into a
1701 // class member access expression using (*this) as the
1702 // postfix-expression to the left of the . operator.
1704 // But we don't actually need to do this for '&' operands if R
1705 // resolved to a function or overloaded function set, because the
1706 // expression is ill-formed if it actually works out to be a
1707 // non-static member function:
1709 // C++ [expr.ref]p4:
1710 // Otherwise, if E1.E2 refers to a non-static member function. . .
1711 // [t]he expression can be used only as the left-hand operand of a
1712 // member function call.
1714 // There are other safeguards against such uses, but it's important
1715 // to get this right here so that we don't end up making a
1716 // spuriously dependent expression if we're inside a dependent
1717 // instance method.
1718 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1719 bool MightBeImplicitMember;
1720 if (!isAddressOfOperand)
1721 MightBeImplicitMember = true;
1722 else if (!SS.isEmpty())
1723 MightBeImplicitMember = false;
1724 else if (R.isOverloadedResult())
1725 MightBeImplicitMember = false;
1726 else if (R.isUnresolvableResult())
1727 MightBeImplicitMember = true;
1728 else
1729 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1730 isa<IndirectFieldDecl>(R.getFoundDecl());
1732 if (MightBeImplicitMember)
1733 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1736 if (TemplateArgs)
1737 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1739 return BuildDeclarationNameExpr(SS, R, ADL);
1742 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1743 /// declaration name, generally during template instantiation.
1744 /// There's a large number of things which don't need to be done along
1745 /// this path.
1746 ExprResult
1747 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1748 const DeclarationNameInfo &NameInfo) {
1749 DeclContext *DC;
1750 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1751 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
1753 if (RequireCompleteDeclContext(SS, DC))
1754 return ExprError();
1756 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1757 LookupQualifiedName(R, DC);
1759 if (R.isAmbiguous())
1760 return ExprError();
1762 if (R.empty()) {
1763 Diag(NameInfo.getLoc(), diag::err_no_member)
1764 << NameInfo.getName() << DC << SS.getRange();
1765 return ExprError();
1768 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1771 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1772 /// detected that we're currently inside an ObjC method. Perform some
1773 /// additional lookup.
1775 /// Ideally, most of this would be done by lookup, but there's
1776 /// actually quite a lot of extra work involved.
1778 /// Returns a null sentinel to indicate trivial success.
1779 ExprResult
1780 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1781 IdentifierInfo *II, bool AllowBuiltinCreation) {
1782 SourceLocation Loc = Lookup.getNameLoc();
1783 ObjCMethodDecl *CurMethod = getCurMethodDecl();
1785 // There are two cases to handle here. 1) scoped lookup could have failed,
1786 // in which case we should look for an ivar. 2) scoped lookup could have
1787 // found a decl, but that decl is outside the current instance method (i.e.
1788 // a global variable). In these two cases, we do a lookup for an ivar with
1789 // this name, if the lookup sucedes, we replace it our current decl.
1791 // If we're in a class method, we don't normally want to look for
1792 // ivars. But if we don't find anything else, and there's an
1793 // ivar, that's an error.
1794 bool IsClassMethod = CurMethod->isClassMethod();
1796 bool LookForIvars;
1797 if (Lookup.empty())
1798 LookForIvars = true;
1799 else if (IsClassMethod)
1800 LookForIvars = false;
1801 else
1802 LookForIvars = (Lookup.isSingleResult() &&
1803 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1804 ObjCInterfaceDecl *IFace = 0;
1805 if (LookForIvars) {
1806 IFace = CurMethod->getClassInterface();
1807 ObjCInterfaceDecl *ClassDeclared;
1808 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1809 // Diagnose using an ivar in a class method.
1810 if (IsClassMethod)
1811 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1812 << IV->getDeclName());
1814 // If we're referencing an invalid decl, just return this as a silent
1815 // error node. The error diagnostic was already emitted on the decl.
1816 if (IV->isInvalidDecl())
1817 return ExprError();
1819 // Check if referencing a field with __attribute__((deprecated)).
1820 if (DiagnoseUseOfDecl(IV, Loc))
1821 return ExprError();
1823 // Diagnose the use of an ivar outside of the declaring class.
1824 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1825 ClassDeclared != IFace)
1826 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1828 // FIXME: This should use a new expr for a direct reference, don't
1829 // turn this into Self->ivar, just return a BareIVarExpr or something.
1830 IdentifierInfo &II = Context.Idents.get("self");
1831 UnqualifiedId SelfName;
1832 SelfName.setIdentifier(&II, SourceLocation());
1833 CXXScopeSpec SelfScopeSpec;
1834 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1835 SelfName, false, false);
1836 if (SelfExpr.isInvalid())
1837 return ExprError();
1839 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1840 if (SelfExpr.isInvalid())
1841 return ExprError();
1843 MarkDeclarationReferenced(Loc, IV);
1844 Expr *base = SelfExpr.take();
1845 base = base->IgnoreParenImpCasts();
1846 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
1847 const NamedDecl *ND = DE->getDecl();
1848 if (!isa<ImplicitParamDecl>(ND)) {
1849 // relax the rule such that it is allowed to have a shadow 'self'
1850 // where stand-alone ivar can be found in this 'self' object.
1851 // This is to match gcc's behavior.
1852 ObjCInterfaceDecl *selfIFace = 0;
1853 if (const ObjCObjectPointerType *OPT =
1854 base->getType()->getAsObjCInterfacePointerType())
1855 selfIFace = OPT->getInterfaceDecl();
1856 if (!selfIFace ||
1857 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
1858 Diag(Loc, diag::error_implicit_ivar_access)
1859 << IV->getDeclName();
1860 Diag(ND->getLocation(), diag::note_declared_at);
1861 return ExprError();
1865 return Owned(new (Context)
1866 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1867 SelfExpr.take(), true, true));
1869 } else if (CurMethod->isInstanceMethod()) {
1870 // We should warn if a local variable hides an ivar.
1871 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
1872 ObjCInterfaceDecl *ClassDeclared;
1873 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1874 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1875 IFace == ClassDeclared)
1876 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1880 if (Lookup.empty() && II && AllowBuiltinCreation) {
1881 // FIXME. Consolidate this with similar code in LookupName.
1882 if (unsigned BuiltinID = II->getBuiltinID()) {
1883 if (!(getLangOptions().CPlusPlus &&
1884 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1885 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1886 S, Lookup.isForRedeclaration(),
1887 Lookup.getNameLoc());
1888 if (D) Lookup.addDecl(D);
1892 // Sentinel value saying that we didn't do anything special.
1893 return Owned((Expr*) 0);
1896 /// \brief Cast a base object to a member's actual type.
1898 /// Logically this happens in three phases:
1900 /// * First we cast from the base type to the naming class.
1901 /// The naming class is the class into which we were looking
1902 /// when we found the member; it's the qualifier type if a
1903 /// qualifier was provided, and otherwise it's the base type.
1905 /// * Next we cast from the naming class to the declaring class.
1906 /// If the member we found was brought into a class's scope by
1907 /// a using declaration, this is that class; otherwise it's
1908 /// the class declaring the member.
1910 /// * Finally we cast from the declaring class to the "true"
1911 /// declaring class of the member. This conversion does not
1912 /// obey access control.
1913 ExprResult
1914 Sema::PerformObjectMemberConversion(Expr *From,
1915 NestedNameSpecifier *Qualifier,
1916 NamedDecl *FoundDecl,
1917 NamedDecl *Member) {
1918 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1919 if (!RD)
1920 return Owned(From);
1922 QualType DestRecordType;
1923 QualType DestType;
1924 QualType FromRecordType;
1925 QualType FromType = From->getType();
1926 bool PointerConversions = false;
1927 if (isa<FieldDecl>(Member)) {
1928 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
1930 if (FromType->getAs<PointerType>()) {
1931 DestType = Context.getPointerType(DestRecordType);
1932 FromRecordType = FromType->getPointeeType();
1933 PointerConversions = true;
1934 } else {
1935 DestType = DestRecordType;
1936 FromRecordType = FromType;
1938 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1939 if (Method->isStatic())
1940 return Owned(From);
1942 DestType = Method->getThisType(Context);
1943 DestRecordType = DestType->getPointeeType();
1945 if (FromType->getAs<PointerType>()) {
1946 FromRecordType = FromType->getPointeeType();
1947 PointerConversions = true;
1948 } else {
1949 FromRecordType = FromType;
1950 DestType = DestRecordType;
1952 } else {
1953 // No conversion necessary.
1954 return Owned(From);
1957 if (DestType->isDependentType() || FromType->isDependentType())
1958 return Owned(From);
1960 // If the unqualified types are the same, no conversion is necessary.
1961 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1962 return Owned(From);
1964 SourceRange FromRange = From->getSourceRange();
1965 SourceLocation FromLoc = FromRange.getBegin();
1967 ExprValueKind VK = CastCategory(From);
1969 // C++ [class.member.lookup]p8:
1970 // [...] Ambiguities can often be resolved by qualifying a name with its
1971 // class name.
1973 // If the member was a qualified name and the qualified referred to a
1974 // specific base subobject type, we'll cast to that intermediate type
1975 // first and then to the object in which the member is declared. That allows
1976 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1978 // class Base { public: int x; };
1979 // class Derived1 : public Base { };
1980 // class Derived2 : public Base { };
1981 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1983 // void VeryDerived::f() {
1984 // x = 17; // error: ambiguous base subobjects
1985 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1986 // }
1987 if (Qualifier) {
1988 QualType QType = QualType(Qualifier->getAsType(), 0);
1989 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1990 assert(QType->isRecordType() && "lookup done with non-record type");
1992 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1994 // In C++98, the qualifier type doesn't actually have to be a base
1995 // type of the object type, in which case we just ignore it.
1996 // Otherwise build the appropriate casts.
1997 if (IsDerivedFrom(FromRecordType, QRecordType)) {
1998 CXXCastPath BasePath;
1999 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2000 FromLoc, FromRange, &BasePath))
2001 return ExprError();
2003 if (PointerConversions)
2004 QType = Context.getPointerType(QType);
2005 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2006 VK, &BasePath).take();
2008 FromType = QType;
2009 FromRecordType = QRecordType;
2011 // If the qualifier type was the same as the destination type,
2012 // we're done.
2013 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2014 return Owned(From);
2018 bool IgnoreAccess = false;
2020 // If we actually found the member through a using declaration, cast
2021 // down to the using declaration's type.
2023 // Pointer equality is fine here because only one declaration of a
2024 // class ever has member declarations.
2025 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2026 assert(isa<UsingShadowDecl>(FoundDecl));
2027 QualType URecordType = Context.getTypeDeclType(
2028 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2030 // We only need to do this if the naming-class to declaring-class
2031 // conversion is non-trivial.
2032 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2033 assert(IsDerivedFrom(FromRecordType, URecordType));
2034 CXXCastPath BasePath;
2035 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2036 FromLoc, FromRange, &BasePath))
2037 return ExprError();
2039 QualType UType = URecordType;
2040 if (PointerConversions)
2041 UType = Context.getPointerType(UType);
2042 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2043 VK, &BasePath).take();
2044 FromType = UType;
2045 FromRecordType = URecordType;
2048 // We don't do access control for the conversion from the
2049 // declaring class to the true declaring class.
2050 IgnoreAccess = true;
2053 CXXCastPath BasePath;
2054 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2055 FromLoc, FromRange, &BasePath,
2056 IgnoreAccess))
2057 return ExprError();
2059 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2060 VK, &BasePath);
2063 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2064 const LookupResult &R,
2065 bool HasTrailingLParen) {
2066 // Only when used directly as the postfix-expression of a call.
2067 if (!HasTrailingLParen)
2068 return false;
2070 // Never if a scope specifier was provided.
2071 if (SS.isSet())
2072 return false;
2074 // Only in C++ or ObjC++.
2075 if (!getLangOptions().CPlusPlus)
2076 return false;
2078 // Turn off ADL when we find certain kinds of declarations during
2079 // normal lookup:
2080 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2081 NamedDecl *D = *I;
2083 // C++0x [basic.lookup.argdep]p3:
2084 // -- a declaration of a class member
2085 // Since using decls preserve this property, we check this on the
2086 // original decl.
2087 if (D->isCXXClassMember())
2088 return false;
2090 // C++0x [basic.lookup.argdep]p3:
2091 // -- a block-scope function declaration that is not a
2092 // using-declaration
2093 // NOTE: we also trigger this for function templates (in fact, we
2094 // don't check the decl type at all, since all other decl types
2095 // turn off ADL anyway).
2096 if (isa<UsingShadowDecl>(D))
2097 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2098 else if (D->getDeclContext()->isFunctionOrMethod())
2099 return false;
2101 // C++0x [basic.lookup.argdep]p3:
2102 // -- a declaration that is neither a function or a function
2103 // template
2104 // And also for builtin functions.
2105 if (isa<FunctionDecl>(D)) {
2106 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2108 // But also builtin functions.
2109 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2110 return false;
2111 } else if (!isa<FunctionTemplateDecl>(D))
2112 return false;
2115 return true;
2119 /// Diagnoses obvious problems with the use of the given declaration
2120 /// as an expression. This is only actually called for lookups that
2121 /// were not overloaded, and it doesn't promise that the declaration
2122 /// will in fact be used.
2123 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2124 if (isa<TypedefNameDecl>(D)) {
2125 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2126 return true;
2129 if (isa<ObjCInterfaceDecl>(D)) {
2130 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2131 return true;
2134 if (isa<NamespaceDecl>(D)) {
2135 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2136 return true;
2139 return false;
2142 ExprResult
2143 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2144 LookupResult &R,
2145 bool NeedsADL) {
2146 // If this is a single, fully-resolved result and we don't need ADL,
2147 // just build an ordinary singleton decl ref.
2148 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2149 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2150 R.getFoundDecl());
2152 // We only need to check the declaration if there's exactly one
2153 // result, because in the overloaded case the results can only be
2154 // functions and function templates.
2155 if (R.isSingleResult() &&
2156 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2157 return ExprError();
2159 // Otherwise, just build an unresolved lookup expression. Suppress
2160 // any lookup-related diagnostics; we'll hash these out later, when
2161 // we've picked a target.
2162 R.suppressDiagnostics();
2164 UnresolvedLookupExpr *ULE
2165 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2166 SS.getWithLocInContext(Context),
2167 R.getLookupNameInfo(),
2168 NeedsADL, R.isOverloadedResult(),
2169 R.begin(), R.end());
2171 return Owned(ULE);
2174 /// \brief Complete semantic analysis for a reference to the given declaration.
2175 ExprResult
2176 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2177 const DeclarationNameInfo &NameInfo,
2178 NamedDecl *D) {
2179 assert(D && "Cannot refer to a NULL declaration");
2180 assert(!isa<FunctionTemplateDecl>(D) &&
2181 "Cannot refer unambiguously to a function template");
2183 SourceLocation Loc = NameInfo.getLoc();
2184 if (CheckDeclInExpr(*this, Loc, D))
2185 return ExprError();
2187 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2188 // Specifically diagnose references to class templates that are missing
2189 // a template argument list.
2190 Diag(Loc, diag::err_template_decl_ref)
2191 << Template << SS.getRange();
2192 Diag(Template->getLocation(), diag::note_template_decl_here);
2193 return ExprError();
2196 // Make sure that we're referring to a value.
2197 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2198 if (!VD) {
2199 Diag(Loc, diag::err_ref_non_value)
2200 << D << SS.getRange();
2201 Diag(D->getLocation(), diag::note_declared_at);
2202 return ExprError();
2205 // Check whether this declaration can be used. Note that we suppress
2206 // this check when we're going to perform argument-dependent lookup
2207 // on this function name, because this might not be the function
2208 // that overload resolution actually selects.
2209 if (DiagnoseUseOfDecl(VD, Loc))
2210 return ExprError();
2212 // Only create DeclRefExpr's for valid Decl's.
2213 if (VD->isInvalidDecl())
2214 return ExprError();
2216 // Handle members of anonymous structs and unions. If we got here,
2217 // and the reference is to a class member indirect field, then this
2218 // must be the subject of a pointer-to-member expression.
2219 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2220 if (!indirectField->isCXXClassMember())
2221 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2222 indirectField);
2224 // If the identifier reference is inside a block, and it refers to a value
2225 // that is outside the block, create a BlockDeclRefExpr instead of a
2226 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2227 // the block is formed.
2229 // We do not do this for things like enum constants, global variables, etc,
2230 // as they do not get snapshotted.
2232 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
2233 case CR_Error:
2234 return ExprError();
2236 case CR_Capture:
2237 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2238 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2240 case CR_CaptureByRef:
2241 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2242 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
2244 case CR_NoCapture: {
2245 // If this reference is not in a block or if the referenced
2246 // variable is within the block, create a normal DeclRefExpr.
2248 QualType type = VD->getType();
2249 ExprValueKind valueKind = VK_RValue;
2251 switch (D->getKind()) {
2252 // Ignore all the non-ValueDecl kinds.
2253 #define ABSTRACT_DECL(kind)
2254 #define VALUE(type, base)
2255 #define DECL(type, base) \
2256 case Decl::type:
2257 #include "clang/AST/DeclNodes.inc"
2258 llvm_unreachable("invalid value decl kind");
2259 return ExprError();
2261 // These shouldn't make it here.
2262 case Decl::ObjCAtDefsField:
2263 case Decl::ObjCIvar:
2264 llvm_unreachable("forming non-member reference to ivar?");
2265 return ExprError();
2267 // Enum constants are always r-values and never references.
2268 // Unresolved using declarations are dependent.
2269 case Decl::EnumConstant:
2270 case Decl::UnresolvedUsingValue:
2271 valueKind = VK_RValue;
2272 break;
2274 // Fields and indirect fields that got here must be for
2275 // pointer-to-member expressions; we just call them l-values for
2276 // internal consistency, because this subexpression doesn't really
2277 // exist in the high-level semantics.
2278 case Decl::Field:
2279 case Decl::IndirectField:
2280 assert(getLangOptions().CPlusPlus &&
2281 "building reference to field in C?");
2283 // These can't have reference type in well-formed programs, but
2284 // for internal consistency we do this anyway.
2285 type = type.getNonReferenceType();
2286 valueKind = VK_LValue;
2287 break;
2289 // Non-type template parameters are either l-values or r-values
2290 // depending on the type.
2291 case Decl::NonTypeTemplateParm: {
2292 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2293 type = reftype->getPointeeType();
2294 valueKind = VK_LValue; // even if the parameter is an r-value reference
2295 break;
2298 // For non-references, we need to strip qualifiers just in case
2299 // the template parameter was declared as 'const int' or whatever.
2300 valueKind = VK_RValue;
2301 type = type.getUnqualifiedType();
2302 break;
2305 case Decl::Var:
2306 // In C, "extern void blah;" is valid and is an r-value.
2307 if (!getLangOptions().CPlusPlus &&
2308 !type.hasQualifiers() &&
2309 type->isVoidType()) {
2310 valueKind = VK_RValue;
2311 break;
2313 // fallthrough
2315 case Decl::ImplicitParam:
2316 case Decl::ParmVar:
2317 // These are always l-values.
2318 valueKind = VK_LValue;
2319 type = type.getNonReferenceType();
2320 break;
2322 case Decl::Function: {
2323 const FunctionType *fty = type->castAs<FunctionType>();
2325 // If we're referring to a function with an __unknown_anytype
2326 // result type, make the entire expression __unknown_anytype.
2327 if (fty->getResultType() == Context.UnknownAnyTy) {
2328 type = Context.UnknownAnyTy;
2329 valueKind = VK_RValue;
2330 break;
2333 // Functions are l-values in C++.
2334 if (getLangOptions().CPlusPlus) {
2335 valueKind = VK_LValue;
2336 break;
2339 // C99 DR 316 says that, if a function type comes from a
2340 // function definition (without a prototype), that type is only
2341 // used for checking compatibility. Therefore, when referencing
2342 // the function, we pretend that we don't have the full function
2343 // type.
2344 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2345 isa<FunctionProtoType>(fty))
2346 type = Context.getFunctionNoProtoType(fty->getResultType(),
2347 fty->getExtInfo());
2349 // Functions are r-values in C.
2350 valueKind = VK_RValue;
2351 break;
2354 case Decl::CXXMethod:
2355 // If we're referring to a method with an __unknown_anytype
2356 // result type, make the entire expression __unknown_anytype.
2357 // This should only be possible with a type written directly.
2358 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2359 if (proto->getResultType() == Context.UnknownAnyTy) {
2360 type = Context.UnknownAnyTy;
2361 valueKind = VK_RValue;
2362 break;
2365 // C++ methods are l-values if static, r-values if non-static.
2366 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2367 valueKind = VK_LValue;
2368 break;
2370 // fallthrough
2372 case Decl::CXXConversion:
2373 case Decl::CXXDestructor:
2374 case Decl::CXXConstructor:
2375 valueKind = VK_RValue;
2376 break;
2379 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2384 llvm_unreachable("unknown capture result");
2385 return ExprError();
2388 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2389 PredefinedExpr::IdentType IT;
2391 switch (Kind) {
2392 default: assert(0 && "Unknown simple primary expr!");
2393 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2394 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2395 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2398 // Pre-defined identifiers are of type char[x], where x is the length of the
2399 // string.
2401 Decl *currentDecl = getCurFunctionOrMethodDecl();
2402 if (!currentDecl && getCurBlock())
2403 currentDecl = getCurBlock()->TheDecl;
2404 if (!currentDecl) {
2405 Diag(Loc, diag::ext_predef_outside_function);
2406 currentDecl = Context.getTranslationUnitDecl();
2409 QualType ResTy;
2410 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2411 ResTy = Context.DependentTy;
2412 } else {
2413 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2415 llvm::APInt LengthI(32, Length + 1);
2416 ResTy = Context.CharTy.withConst();
2417 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2419 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2422 ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2423 llvm::SmallString<16> CharBuffer;
2424 bool Invalid = false;
2425 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2426 if (Invalid)
2427 return ExprError();
2429 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2430 PP);
2431 if (Literal.hadError())
2432 return ExprError();
2434 QualType Ty;
2435 if (!getLangOptions().CPlusPlus)
2436 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2437 else if (Literal.isWide())
2438 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2439 else if (Literal.isMultiChar())
2440 Ty = Context.IntTy; // 'wxyz' -> int in C++.
2441 else
2442 Ty = Context.CharTy; // 'x' -> char in C++
2444 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2445 Literal.isWide(),
2446 Ty, Tok.getLocation()));
2449 ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2450 // Fast path for a single digit (which is quite common). A single digit
2451 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2452 if (Tok.getLength() == 1) {
2453 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2454 unsigned IntSize = Context.Target.getIntWidth();
2455 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2456 Context.IntTy, Tok.getLocation()));
2459 llvm::SmallString<512> IntegerBuffer;
2460 // Add padding so that NumericLiteralParser can overread by one character.
2461 IntegerBuffer.resize(Tok.getLength()+1);
2462 const char *ThisTokBegin = &IntegerBuffer[0];
2464 // Get the spelling of the token, which eliminates trigraphs, etc.
2465 bool Invalid = false;
2466 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2467 if (Invalid)
2468 return ExprError();
2470 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2471 Tok.getLocation(), PP);
2472 if (Literal.hadError)
2473 return ExprError();
2475 Expr *Res;
2477 if (Literal.isFloatingLiteral()) {
2478 QualType Ty;
2479 if (Literal.isFloat)
2480 Ty = Context.FloatTy;
2481 else if (!Literal.isLong)
2482 Ty = Context.DoubleTy;
2483 else
2484 Ty = Context.LongDoubleTy;
2486 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2488 using llvm::APFloat;
2489 APFloat Val(Format);
2491 APFloat::opStatus result = Literal.GetFloatValue(Val);
2493 // Overflow is always an error, but underflow is only an error if
2494 // we underflowed to zero (APFloat reports denormals as underflow).
2495 if ((result & APFloat::opOverflow) ||
2496 ((result & APFloat::opUnderflow) && Val.isZero())) {
2497 unsigned diagnostic;
2498 llvm::SmallString<20> buffer;
2499 if (result & APFloat::opOverflow) {
2500 diagnostic = diag::warn_float_overflow;
2501 APFloat::getLargest(Format).toString(buffer);
2502 } else {
2503 diagnostic = diag::warn_float_underflow;
2504 APFloat::getSmallest(Format).toString(buffer);
2507 Diag(Tok.getLocation(), diagnostic)
2508 << Ty
2509 << llvm::StringRef(buffer.data(), buffer.size());
2512 bool isExact = (result == APFloat::opOK);
2513 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2515 if (Ty == Context.DoubleTy) {
2516 if (getLangOptions().SinglePrecisionConstants) {
2517 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2518 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2519 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2520 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2523 } else if (!Literal.isIntegerLiteral()) {
2524 return ExprError();
2525 } else {
2526 QualType Ty;
2528 // long long is a C99 feature.
2529 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
2530 Literal.isLongLong)
2531 Diag(Tok.getLocation(), diag::ext_longlong);
2533 // Get the value in the widest-possible width.
2534 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
2536 if (Literal.GetIntegerValue(ResultVal)) {
2537 // If this value didn't fit into uintmax_t, warn and force to ull.
2538 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2539 Ty = Context.UnsignedLongLongTy;
2540 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2541 "long long is not intmax_t?");
2542 } else {
2543 // If this value fits into a ULL, try to figure out what else it fits into
2544 // according to the rules of C99 6.4.4.1p5.
2546 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2547 // be an unsigned int.
2548 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2550 // Check from smallest to largest, picking the smallest type we can.
2551 unsigned Width = 0;
2552 if (!Literal.isLong && !Literal.isLongLong) {
2553 // Are int/unsigned possibilities?
2554 unsigned IntSize = Context.Target.getIntWidth();
2556 // Does it fit in a unsigned int?
2557 if (ResultVal.isIntN(IntSize)) {
2558 // Does it fit in a signed int?
2559 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2560 Ty = Context.IntTy;
2561 else if (AllowUnsigned)
2562 Ty = Context.UnsignedIntTy;
2563 Width = IntSize;
2567 // Are long/unsigned long possibilities?
2568 if (Ty.isNull() && !Literal.isLongLong) {
2569 unsigned LongSize = Context.Target.getLongWidth();
2571 // Does it fit in a unsigned long?
2572 if (ResultVal.isIntN(LongSize)) {
2573 // Does it fit in a signed long?
2574 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2575 Ty = Context.LongTy;
2576 else if (AllowUnsigned)
2577 Ty = Context.UnsignedLongTy;
2578 Width = LongSize;
2582 // Finally, check long long if needed.
2583 if (Ty.isNull()) {
2584 unsigned LongLongSize = Context.Target.getLongLongWidth();
2586 // Does it fit in a unsigned long long?
2587 if (ResultVal.isIntN(LongLongSize)) {
2588 // Does it fit in a signed long long?
2589 // To be compatible with MSVC, hex integer literals ending with the
2590 // LL or i64 suffix are always signed in Microsoft mode.
2591 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2592 (getLangOptions().Microsoft && Literal.isLongLong)))
2593 Ty = Context.LongLongTy;
2594 else if (AllowUnsigned)
2595 Ty = Context.UnsignedLongLongTy;
2596 Width = LongLongSize;
2600 // If we still couldn't decide a type, we probably have something that
2601 // does not fit in a signed long long, but has no U suffix.
2602 if (Ty.isNull()) {
2603 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2604 Ty = Context.UnsignedLongLongTy;
2605 Width = Context.Target.getLongLongWidth();
2608 if (ResultVal.getBitWidth() != Width)
2609 ResultVal = ResultVal.trunc(Width);
2611 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2614 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2615 if (Literal.isImaginary)
2616 Res = new (Context) ImaginaryLiteral(Res,
2617 Context.getComplexType(Res->getType()));
2619 return Owned(Res);
2622 ExprResult Sema::ActOnParenExpr(SourceLocation L,
2623 SourceLocation R, Expr *E) {
2624 assert((E != 0) && "ActOnParenExpr() missing expr");
2625 return Owned(new (Context) ParenExpr(L, R, E));
2628 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2629 SourceLocation Loc,
2630 SourceRange ArgRange) {
2631 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2632 // scalar or vector data type argument..."
2633 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2634 // type (C99 6.2.5p18) or void.
2635 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2636 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2637 << T << ArgRange;
2638 return true;
2641 assert((T->isVoidType() || !T->isIncompleteType()) &&
2642 "Scalar types should always be complete");
2643 return false;
2646 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2647 SourceLocation Loc,
2648 SourceRange ArgRange,
2649 UnaryExprOrTypeTrait TraitKind) {
2650 // C99 6.5.3.4p1:
2651 if (T->isFunctionType()) {
2652 // alignof(function) is allowed as an extension.
2653 if (TraitKind == UETT_SizeOf)
2654 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2655 return false;
2658 // Allow sizeof(void)/alignof(void) as an extension.
2659 if (T->isVoidType()) {
2660 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2661 return false;
2664 return true;
2667 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2668 SourceLocation Loc,
2669 SourceRange ArgRange,
2670 UnaryExprOrTypeTrait TraitKind) {
2671 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2672 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2673 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2674 << T << (TraitKind == UETT_SizeOf)
2675 << ArgRange;
2676 return true;
2679 return false;
2682 /// \brief Check the constrains on expression operands to unary type expression
2683 /// and type traits.
2685 /// Completes any types necessary and validates the constraints on the operand
2686 /// expression. The logic mostly mirrors the type-based overload, but may modify
2687 /// the expression as it completes the type for that expression through template
2688 /// instantiation, etc.
2689 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2690 UnaryExprOrTypeTrait ExprKind) {
2691 QualType ExprTy = Op->getType();
2693 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2694 // the result is the size of the referenced type."
2695 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2696 // result shall be the alignment of the referenced type."
2697 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2698 ExprTy = Ref->getPointeeType();
2700 if (ExprKind == UETT_VecStep)
2701 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2702 Op->getSourceRange());
2704 // Whitelist some types as extensions
2705 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2706 Op->getSourceRange(), ExprKind))
2707 return false;
2709 if (RequireCompleteExprType(Op,
2710 PDiag(diag::err_sizeof_alignof_incomplete_type)
2711 << ExprKind << Op->getSourceRange(),
2712 std::make_pair(SourceLocation(), PDiag(0))))
2713 return true;
2715 // Completeing the expression's type may have changed it.
2716 ExprTy = Op->getType();
2717 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2718 ExprTy = Ref->getPointeeType();
2720 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2721 Op->getSourceRange(), ExprKind))
2722 return true;
2724 if (ExprKind == UETT_SizeOf) {
2725 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2726 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2727 QualType OType = PVD->getOriginalType();
2728 QualType Type = PVD->getType();
2729 if (Type->isPointerType() && OType->isArrayType()) {
2730 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2731 << Type << OType;
2732 Diag(PVD->getLocation(), diag::note_declared_at);
2738 return false;
2741 /// \brief Check the constraints on operands to unary expression and type
2742 /// traits.
2744 /// This will complete any types necessary, and validate the various constraints
2745 /// on those operands.
2747 /// The UsualUnaryConversions() function is *not* called by this routine.
2748 /// C99 6.3.2.1p[2-4] all state:
2749 /// Except when it is the operand of the sizeof operator ...
2751 /// C++ [expr.sizeof]p4
2752 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2753 /// standard conversions are not applied to the operand of sizeof.
2755 /// This policy is followed for all of the unary trait expressions.
2756 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2757 SourceLocation OpLoc,
2758 SourceRange ExprRange,
2759 UnaryExprOrTypeTrait ExprKind) {
2760 if (exprType->isDependentType())
2761 return false;
2763 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2764 // the result is the size of the referenced type."
2765 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2766 // result shall be the alignment of the referenced type."
2767 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2768 exprType = Ref->getPointeeType();
2770 if (ExprKind == UETT_VecStep)
2771 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
2773 // Whitelist some types as extensions
2774 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2775 ExprKind))
2776 return false;
2778 if (RequireCompleteType(OpLoc, exprType,
2779 PDiag(diag::err_sizeof_alignof_incomplete_type)
2780 << ExprKind << ExprRange))
2781 return true;
2783 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2784 ExprKind))
2785 return true;
2787 return false;
2790 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
2791 E = E->IgnoreParens();
2793 // alignof decl is always ok.
2794 if (isa<DeclRefExpr>(E))
2795 return false;
2797 // Cannot know anything else if the expression is dependent.
2798 if (E->isTypeDependent())
2799 return false;
2801 if (E->getBitField()) {
2802 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2803 << 1 << E->getSourceRange();
2804 return true;
2807 // Alignment of a field access is always okay, so long as it isn't a
2808 // bit-field.
2809 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2810 if (isa<FieldDecl>(ME->getMemberDecl()))
2811 return false;
2813 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
2816 bool Sema::CheckVecStepExpr(Expr *E) {
2817 E = E->IgnoreParens();
2819 // Cannot know anything else if the expression is dependent.
2820 if (E->isTypeDependent())
2821 return false;
2823 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
2826 /// \brief Build a sizeof or alignof expression given a type operand.
2827 ExprResult
2828 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2829 SourceLocation OpLoc,
2830 UnaryExprOrTypeTrait ExprKind,
2831 SourceRange R) {
2832 if (!TInfo)
2833 return ExprError();
2835 QualType T = TInfo->getType();
2837 if (!T->isDependentType() &&
2838 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
2839 return ExprError();
2841 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2842 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2843 Context.getSizeType(),
2844 OpLoc, R.getEnd()));
2847 /// \brief Build a sizeof or alignof expression given an expression
2848 /// operand.
2849 ExprResult
2850 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2851 UnaryExprOrTypeTrait ExprKind) {
2852 ExprResult PE = CheckPlaceholderExpr(E);
2853 if (PE.isInvalid())
2854 return ExprError();
2856 E = PE.get();
2858 // Verify that the operand is valid.
2859 bool isInvalid = false;
2860 if (E->isTypeDependent()) {
2861 // Delay type-checking for type-dependent expressions.
2862 } else if (ExprKind == UETT_AlignOf) {
2863 isInvalid = CheckAlignOfExpr(*this, E);
2864 } else if (ExprKind == UETT_VecStep) {
2865 isInvalid = CheckVecStepExpr(E);
2866 } else if (E->getBitField()) { // C99 6.5.3.4p1.
2867 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
2868 isInvalid = true;
2869 } else {
2870 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
2873 if (isInvalid)
2874 return ExprError();
2876 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2877 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
2878 ExprKind, E, Context.getSizeType(), OpLoc,
2879 E->getSourceRange().getEnd()));
2882 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2883 /// expr and the same for @c alignof and @c __alignof
2884 /// Note that the ArgRange is invalid if isType is false.
2885 ExprResult
2886 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2887 UnaryExprOrTypeTrait ExprKind, bool isType,
2888 void *TyOrEx, const SourceRange &ArgRange) {
2889 // If error parsing type, ignore.
2890 if (TyOrEx == 0) return ExprError();
2892 if (isType) {
2893 TypeSourceInfo *TInfo;
2894 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
2895 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
2898 Expr *ArgEx = (Expr *)TyOrEx;
2899 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
2900 return move(Result);
2903 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
2904 bool isReal) {
2905 if (V.get()->isTypeDependent())
2906 return S.Context.DependentTy;
2908 // _Real and _Imag are only l-values for normal l-values.
2909 if (V.get()->getObjectKind() != OK_Ordinary) {
2910 V = S.DefaultLvalueConversion(V.take());
2911 if (V.isInvalid())
2912 return QualType();
2915 // These operators return the element type of a complex type.
2916 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
2917 return CT->getElementType();
2919 // Otherwise they pass through real integer and floating point types here.
2920 if (V.get()->getType()->isArithmeticType())
2921 return V.get()->getType();
2923 // Test for placeholders.
2924 ExprResult PR = S.CheckPlaceholderExpr(V.get());
2925 if (PR.isInvalid()) return QualType();
2926 if (PR.get() != V.get()) {
2927 V = move(PR);
2928 return CheckRealImagOperand(S, V, Loc, isReal);
2931 // Reject anything else.
2932 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
2933 << (isReal ? "__real" : "__imag");
2934 return QualType();
2939 ExprResult
2940 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2941 tok::TokenKind Kind, Expr *Input) {
2942 UnaryOperatorKind Opc;
2943 switch (Kind) {
2944 default: assert(0 && "Unknown unary op!");
2945 case tok::plusplus: Opc = UO_PostInc; break;
2946 case tok::minusminus: Opc = UO_PostDec; break;
2949 return BuildUnaryOp(S, OpLoc, Opc, Input);
2952 ExprResult
2953 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2954 Expr *Idx, SourceLocation RLoc) {
2955 // Since this might be a postfix expression, get rid of ParenListExprs.
2956 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
2957 if (Result.isInvalid()) return ExprError();
2958 Base = Result.take();
2960 Expr *LHSExp = Base, *RHSExp = Idx;
2962 if (getLangOptions().CPlusPlus &&
2963 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2964 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2965 Context.DependentTy,
2966 VK_LValue, OK_Ordinary,
2967 RLoc));
2970 if (getLangOptions().CPlusPlus &&
2971 (LHSExp->getType()->isRecordType() ||
2972 LHSExp->getType()->isEnumeralType() ||
2973 RHSExp->getType()->isRecordType() ||
2974 RHSExp->getType()->isEnumeralType())) {
2975 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
2978 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
2982 ExprResult
2983 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2984 Expr *Idx, SourceLocation RLoc) {
2985 Expr *LHSExp = Base;
2986 Expr *RHSExp = Idx;
2988 // Perform default conversions.
2989 if (!LHSExp->getType()->getAs<VectorType>()) {
2990 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
2991 if (Result.isInvalid())
2992 return ExprError();
2993 LHSExp = Result.take();
2995 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
2996 if (Result.isInvalid())
2997 return ExprError();
2998 RHSExp = Result.take();
3000 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3001 ExprValueKind VK = VK_LValue;
3002 ExprObjectKind OK = OK_Ordinary;
3004 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3005 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3006 // in the subscript position. As a result, we need to derive the array base
3007 // and index from the expression types.
3008 Expr *BaseExpr, *IndexExpr;
3009 QualType ResultType;
3010 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3011 BaseExpr = LHSExp;
3012 IndexExpr = RHSExp;
3013 ResultType = Context.DependentTy;
3014 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3015 BaseExpr = LHSExp;
3016 IndexExpr = RHSExp;
3017 ResultType = PTy->getPointeeType();
3018 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3019 // Handle the uncommon case of "123[Ptr]".
3020 BaseExpr = RHSExp;
3021 IndexExpr = LHSExp;
3022 ResultType = PTy->getPointeeType();
3023 } else if (const ObjCObjectPointerType *PTy =
3024 LHSTy->getAs<ObjCObjectPointerType>()) {
3025 BaseExpr = LHSExp;
3026 IndexExpr = RHSExp;
3027 ResultType = PTy->getPointeeType();
3028 } else if (const ObjCObjectPointerType *PTy =
3029 RHSTy->getAs<ObjCObjectPointerType>()) {
3030 // Handle the uncommon case of "123[Ptr]".
3031 BaseExpr = RHSExp;
3032 IndexExpr = LHSExp;
3033 ResultType = PTy->getPointeeType();
3034 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3035 BaseExpr = LHSExp; // vectors: V[123]
3036 IndexExpr = RHSExp;
3037 VK = LHSExp->getValueKind();
3038 if (VK != VK_RValue)
3039 OK = OK_VectorComponent;
3041 // FIXME: need to deal with const...
3042 ResultType = VTy->getElementType();
3043 } else if (LHSTy->isArrayType()) {
3044 // If we see an array that wasn't promoted by
3045 // DefaultFunctionArrayLvalueConversion, it must be an array that
3046 // wasn't promoted because of the C90 rule that doesn't
3047 // allow promoting non-lvalue arrays. Warn, then
3048 // force the promotion here.
3049 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3050 LHSExp->getSourceRange();
3051 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3052 CK_ArrayToPointerDecay).take();
3053 LHSTy = LHSExp->getType();
3055 BaseExpr = LHSExp;
3056 IndexExpr = RHSExp;
3057 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3058 } else if (RHSTy->isArrayType()) {
3059 // Same as previous, except for 123[f().a] case
3060 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3061 RHSExp->getSourceRange();
3062 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3063 CK_ArrayToPointerDecay).take();
3064 RHSTy = RHSExp->getType();
3066 BaseExpr = RHSExp;
3067 IndexExpr = LHSExp;
3068 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3069 } else {
3070 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3071 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3073 // C99 6.5.2.1p1
3074 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3075 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3076 << IndexExpr->getSourceRange());
3078 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3079 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3080 && !IndexExpr->isTypeDependent())
3081 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3083 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3084 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3085 // type. Note that Functions are not objects, and that (in C99 parlance)
3086 // incomplete types are not object types.
3087 if (ResultType->isFunctionType()) {
3088 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3089 << ResultType << BaseExpr->getSourceRange();
3090 return ExprError();
3093 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3094 // GNU extension: subscripting on pointer to void
3095 Diag(LLoc, diag::ext_gnu_void_ptr)
3096 << BaseExpr->getSourceRange();
3098 // C forbids expressions of unqualified void type from being l-values.
3099 // See IsCForbiddenLValueType.
3100 if (!ResultType.hasQualifiers()) VK = VK_RValue;
3101 } else if (!ResultType->isDependentType() &&
3102 RequireCompleteType(LLoc, ResultType,
3103 PDiag(diag::err_subscript_incomplete_type)
3104 << BaseExpr->getSourceRange()))
3105 return ExprError();
3107 // Diagnose bad cases where we step over interface counts.
3108 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
3109 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3110 << ResultType << BaseExpr->getSourceRange();
3111 return ExprError();
3114 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3115 !ResultType.isCForbiddenLValueType());
3117 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3118 ResultType, VK, OK, RLoc));
3121 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3122 FunctionDecl *FD,
3123 ParmVarDecl *Param) {
3124 if (Param->hasUnparsedDefaultArg()) {
3125 Diag(CallLoc,
3126 diag::err_use_of_default_argument_to_function_declared_later) <<
3127 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3128 Diag(UnparsedDefaultArgLocs[Param],
3129 diag::note_default_argument_declared_here);
3130 return ExprError();
3133 if (Param->hasUninstantiatedDefaultArg()) {
3134 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3136 // Instantiate the expression.
3137 MultiLevelTemplateArgumentList ArgList
3138 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3140 std::pair<const TemplateArgument *, unsigned> Innermost
3141 = ArgList.getInnermost();
3142 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3143 Innermost.second);
3145 ExprResult Result;
3147 // C++ [dcl.fct.default]p5:
3148 // The names in the [default argument] expression are bound, and
3149 // the semantic constraints are checked, at the point where the
3150 // default argument expression appears.
3151 ContextRAII SavedContext(*this, FD);
3152 Result = SubstExpr(UninstExpr, ArgList);
3154 if (Result.isInvalid())
3155 return ExprError();
3157 // Check the expression as an initializer for the parameter.
3158 InitializedEntity Entity
3159 = InitializedEntity::InitializeParameter(Context, Param);
3160 InitializationKind Kind
3161 = InitializationKind::CreateCopy(Param->getLocation(),
3162 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3163 Expr *ResultE = Result.takeAs<Expr>();
3165 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3166 Result = InitSeq.Perform(*this, Entity, Kind,
3167 MultiExprArg(*this, &ResultE, 1));
3168 if (Result.isInvalid())
3169 return ExprError();
3171 // Build the default argument expression.
3172 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3173 Result.takeAs<Expr>()));
3176 // If the default expression creates temporaries, we need to
3177 // push them to the current stack of expression temporaries so they'll
3178 // be properly destroyed.
3179 // FIXME: We should really be rebuilding the default argument with new
3180 // bound temporaries; see the comment in PR5810.
3181 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3182 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3183 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3184 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3185 ExprTemporaries.push_back(Temporary);
3186 ExprNeedsCleanups = true;
3189 // We already type-checked the argument, so we know it works.
3190 // Just mark all of the declarations in this potentially-evaluated expression
3191 // as being "referenced".
3192 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
3193 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3196 /// ConvertArgumentsForCall - Converts the arguments specified in
3197 /// Args/NumArgs to the parameter types of the function FDecl with
3198 /// function prototype Proto. Call is the call expression itself, and
3199 /// Fn is the function expression. For a C++ member function, this
3200 /// routine does not attempt to convert the object argument. Returns
3201 /// true if the call is ill-formed.
3202 bool
3203 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3204 FunctionDecl *FDecl,
3205 const FunctionProtoType *Proto,
3206 Expr **Args, unsigned NumArgs,
3207 SourceLocation RParenLoc) {
3208 // Bail out early if calling a builtin with custom typechecking.
3209 // We don't need to do this in the
3210 if (FDecl)
3211 if (unsigned ID = FDecl->getBuiltinID())
3212 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3213 return false;
3215 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3216 // assignment, to the types of the corresponding parameter, ...
3217 unsigned NumArgsInProto = Proto->getNumArgs();
3218 bool Invalid = false;
3220 // If too few arguments are available (and we don't have default
3221 // arguments for the remaining parameters), don't make the call.
3222 if (NumArgs < NumArgsInProto) {
3223 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3224 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3225 << Fn->getType()->isBlockPointerType()
3226 << NumArgsInProto << NumArgs << Fn->getSourceRange();
3227 Call->setNumArgs(Context, NumArgsInProto);
3230 // If too many are passed and not variadic, error on the extras and drop
3231 // them.
3232 if (NumArgs > NumArgsInProto) {
3233 if (!Proto->isVariadic()) {
3234 Diag(Args[NumArgsInProto]->getLocStart(),
3235 diag::err_typecheck_call_too_many_args)
3236 << Fn->getType()->isBlockPointerType()
3237 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3238 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3239 Args[NumArgs-1]->getLocEnd());
3241 // Emit the location of the prototype.
3242 if (FDecl && !FDecl->getBuiltinID())
3243 Diag(FDecl->getLocStart(),
3244 diag::note_typecheck_call_too_many_args)
3245 << FDecl;
3247 // This deletes the extra arguments.
3248 Call->setNumArgs(Context, NumArgsInProto);
3249 return true;
3252 llvm::SmallVector<Expr *, 8> AllArgs;
3253 VariadicCallType CallType =
3254 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3255 if (Fn->getType()->isBlockPointerType())
3256 CallType = VariadicBlock; // Block
3257 else if (isa<MemberExpr>(Fn))
3258 CallType = VariadicMethod;
3259 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
3260 Proto, 0, Args, NumArgs, AllArgs, CallType);
3261 if (Invalid)
3262 return true;
3263 unsigned TotalNumArgs = AllArgs.size();
3264 for (unsigned i = 0; i < TotalNumArgs; ++i)
3265 Call->setArg(i, AllArgs[i]);
3267 return false;
3270 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3271 FunctionDecl *FDecl,
3272 const FunctionProtoType *Proto,
3273 unsigned FirstProtoArg,
3274 Expr **Args, unsigned NumArgs,
3275 llvm::SmallVector<Expr *, 8> &AllArgs,
3276 VariadicCallType CallType) {
3277 unsigned NumArgsInProto = Proto->getNumArgs();
3278 unsigned NumArgsToCheck = NumArgs;
3279 bool Invalid = false;
3280 if (NumArgs != NumArgsInProto)
3281 // Use default arguments for missing arguments
3282 NumArgsToCheck = NumArgsInProto;
3283 unsigned ArgIx = 0;
3284 // Continue to check argument types (even if we have too few/many args).
3285 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3286 QualType ProtoArgType = Proto->getArgType(i);
3288 Expr *Arg;
3289 if (ArgIx < NumArgs) {
3290 Arg = Args[ArgIx++];
3292 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3293 ProtoArgType,
3294 PDiag(diag::err_call_incomplete_argument)
3295 << Arg->getSourceRange()))
3296 return true;
3298 // Pass the argument
3299 ParmVarDecl *Param = 0;
3300 if (FDecl && i < FDecl->getNumParams())
3301 Param = FDecl->getParamDecl(i);
3303 InitializedEntity Entity =
3304 Param? InitializedEntity::InitializeParameter(Context, Param)
3305 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3306 Proto->isArgConsumed(i));
3307 ExprResult ArgE = PerformCopyInitialization(Entity,
3308 SourceLocation(),
3309 Owned(Arg));
3310 if (ArgE.isInvalid())
3311 return true;
3313 Arg = ArgE.takeAs<Expr>();
3314 } else {
3315 ParmVarDecl *Param = FDecl->getParamDecl(i);
3317 ExprResult ArgExpr =
3318 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3319 if (ArgExpr.isInvalid())
3320 return true;
3322 Arg = ArgExpr.takeAs<Expr>();
3324 AllArgs.push_back(Arg);
3327 // If this is a variadic call, handle args passed through "...".
3328 if (CallType != VariadicDoesNotApply) {
3330 // Assume that extern "C" functions with variadic arguments that
3331 // return __unknown_anytype aren't *really* variadic.
3332 if (Proto->getResultType() == Context.UnknownAnyTy &&
3333 FDecl && FDecl->isExternC()) {
3334 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3335 ExprResult arg;
3336 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3337 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3338 else
3339 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3340 Invalid |= arg.isInvalid();
3341 AllArgs.push_back(arg.take());
3344 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3345 } else {
3346 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3347 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3348 Invalid |= Arg.isInvalid();
3349 AllArgs.push_back(Arg.take());
3353 return Invalid;
3356 /// Given a function expression of unknown-any type, try to rebuild it
3357 /// to have a function type.
3358 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3360 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3361 /// This provides the location of the left/right parens and a list of comma
3362 /// locations.
3363 ExprResult
3364 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3365 MultiExprArg args, SourceLocation RParenLoc,
3366 Expr *ExecConfig) {
3367 unsigned NumArgs = args.size();
3369 // Since this might be a postfix expression, get rid of ParenListExprs.
3370 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3371 if (Result.isInvalid()) return ExprError();
3372 Fn = Result.take();
3374 Expr **Args = args.release();
3376 if (getLangOptions().CPlusPlus) {
3377 // If this is a pseudo-destructor expression, build the call immediately.
3378 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3379 if (NumArgs > 0) {
3380 // Pseudo-destructor calls should not have any arguments.
3381 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3382 << FixItHint::CreateRemoval(
3383 SourceRange(Args[0]->getLocStart(),
3384 Args[NumArgs-1]->getLocEnd()));
3386 NumArgs = 0;
3389 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3390 VK_RValue, RParenLoc));
3393 // Determine whether this is a dependent call inside a C++ template,
3394 // in which case we won't do any semantic analysis now.
3395 // FIXME: Will need to cache the results of name lookup (including ADL) in
3396 // Fn.
3397 bool Dependent = false;
3398 if (Fn->isTypeDependent())
3399 Dependent = true;
3400 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3401 Dependent = true;
3403 if (Dependent) {
3404 if (ExecConfig) {
3405 return Owned(new (Context) CUDAKernelCallExpr(
3406 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3407 Context.DependentTy, VK_RValue, RParenLoc));
3408 } else {
3409 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3410 Context.DependentTy, VK_RValue,
3411 RParenLoc));
3415 // Determine whether this is a call to an object (C++ [over.call.object]).
3416 if (Fn->getType()->isRecordType())
3417 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3418 RParenLoc));
3420 if (Fn->getType() == Context.UnknownAnyTy) {
3421 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3422 if (result.isInvalid()) return ExprError();
3423 Fn = result.take();
3426 if (Fn->getType() == Context.BoundMemberTy) {
3427 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3428 RParenLoc);
3432 // Check for overloaded calls. This can happen even in C due to extensions.
3433 if (Fn->getType() == Context.OverloadTy) {
3434 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3436 // We aren't supposed to apply this logic if there's an '&' involved.
3437 if (!find.IsAddressOfOperand) {
3438 OverloadExpr *ovl = find.Expression;
3439 if (isa<UnresolvedLookupExpr>(ovl)) {
3440 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3441 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3442 RParenLoc, ExecConfig);
3443 } else {
3444 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3445 RParenLoc);
3450 // If we're directly calling a function, get the appropriate declaration.
3452 Expr *NakedFn = Fn->IgnoreParens();
3454 NamedDecl *NDecl = 0;
3455 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3456 if (UnOp->getOpcode() == UO_AddrOf)
3457 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3459 if (isa<DeclRefExpr>(NakedFn))
3460 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3461 else if (isa<MemberExpr>(NakedFn))
3462 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3464 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3465 ExecConfig);
3468 ExprResult
3469 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3470 MultiExprArg execConfig, SourceLocation GGGLoc) {
3471 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3472 if (!ConfigDecl)
3473 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3474 << "cudaConfigureCall");
3475 QualType ConfigQTy = ConfigDecl->getType();
3477 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3478 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3480 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
3483 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3485 /// __builtin_astype( value, dst type )
3487 ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3488 SourceLocation BuiltinLoc,
3489 SourceLocation RParenLoc) {
3490 ExprValueKind VK = VK_RValue;
3491 ExprObjectKind OK = OK_Ordinary;
3492 QualType DstTy = GetTypeFromParser(destty);
3493 QualType SrcTy = expr->getType();
3494 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3495 return ExprError(Diag(BuiltinLoc,
3496 diag::err_invalid_astype_of_different_size)
3497 << DstTy
3498 << SrcTy
3499 << expr->getSourceRange());
3500 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
3503 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3504 /// i.e. an expression not of \p OverloadTy. The expression should
3505 /// unary-convert to an expression of function-pointer or
3506 /// block-pointer type.
3508 /// \param NDecl the declaration being called, if available
3509 ExprResult
3510 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3511 SourceLocation LParenLoc,
3512 Expr **Args, unsigned NumArgs,
3513 SourceLocation RParenLoc,
3514 Expr *Config) {
3515 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3517 // Promote the function operand.
3518 ExprResult Result = UsualUnaryConversions(Fn);
3519 if (Result.isInvalid())
3520 return ExprError();
3521 Fn = Result.take();
3523 // Make the call expr early, before semantic checks. This guarantees cleanup
3524 // of arguments and function on error.
3525 CallExpr *TheCall;
3526 if (Config) {
3527 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3528 cast<CallExpr>(Config),
3529 Args, NumArgs,
3530 Context.BoolTy,
3531 VK_RValue,
3532 RParenLoc);
3533 } else {
3534 TheCall = new (Context) CallExpr(Context, Fn,
3535 Args, NumArgs,
3536 Context.BoolTy,
3537 VK_RValue,
3538 RParenLoc);
3541 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3543 // Bail out early if calling a builtin with custom typechecking.
3544 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3545 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3547 retry:
3548 const FunctionType *FuncT;
3549 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
3550 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3551 // have type pointer to function".
3552 FuncT = PT->getPointeeType()->getAs<FunctionType>();
3553 if (FuncT == 0)
3554 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3555 << Fn->getType() << Fn->getSourceRange());
3556 } else if (const BlockPointerType *BPT =
3557 Fn->getType()->getAs<BlockPointerType>()) {
3558 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3559 } else {
3560 // Handle calls to expressions of unknown-any type.
3561 if (Fn->getType() == Context.UnknownAnyTy) {
3562 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
3563 if (rewrite.isInvalid()) return ExprError();
3564 Fn = rewrite.take();
3565 TheCall->setCallee(Fn);
3566 goto retry;
3569 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3570 << Fn->getType() << Fn->getSourceRange());
3573 if (getLangOptions().CUDA) {
3574 if (Config) {
3575 // CUDA: Kernel calls must be to global functions
3576 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3577 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3578 << FDecl->getName() << Fn->getSourceRange());
3580 // CUDA: Kernel function must have 'void' return type
3581 if (!FuncT->getResultType()->isVoidType())
3582 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3583 << Fn->getType() << Fn->getSourceRange());
3587 // Check for a valid return type
3588 if (CheckCallReturnType(FuncT->getResultType(),
3589 Fn->getSourceRange().getBegin(), TheCall,
3590 FDecl))
3591 return ExprError();
3593 // We know the result type of the call, set it.
3594 TheCall->setType(FuncT->getCallResultType(Context));
3595 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
3597 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
3598 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
3599 RParenLoc))
3600 return ExprError();
3601 } else {
3602 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3604 if (FDecl) {
3605 // Check if we have too few/too many template arguments, based
3606 // on our knowledge of the function definition.
3607 const FunctionDecl *Def = 0;
3608 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
3609 const FunctionProtoType *Proto
3610 = Def->getType()->getAs<FunctionProtoType>();
3611 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
3612 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3613 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3616 // If the function we're calling isn't a function prototype, but we have
3617 // a function prototype from a prior declaratiom, use that prototype.
3618 if (!FDecl->hasPrototype())
3619 Proto = FDecl->getType()->getAs<FunctionProtoType>();
3622 // Promote the arguments (C99 6.5.2.2p6).
3623 for (unsigned i = 0; i != NumArgs; i++) {
3624 Expr *Arg = Args[i];
3626 if (Proto && i < Proto->getNumArgs()) {
3627 InitializedEntity Entity
3628 = InitializedEntity::InitializeParameter(Context,
3629 Proto->getArgType(i),
3630 Proto->isArgConsumed(i));
3631 ExprResult ArgE = PerformCopyInitialization(Entity,
3632 SourceLocation(),
3633 Owned(Arg));
3634 if (ArgE.isInvalid())
3635 return true;
3637 Arg = ArgE.takeAs<Expr>();
3639 } else {
3640 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3642 if (ArgE.isInvalid())
3643 return true;
3645 Arg = ArgE.takeAs<Expr>();
3648 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3649 Arg->getType(),
3650 PDiag(diag::err_call_incomplete_argument)
3651 << Arg->getSourceRange()))
3652 return ExprError();
3654 TheCall->setArg(i, Arg);
3658 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3659 if (!Method->isStatic())
3660 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3661 << Fn->getSourceRange());
3663 // Check for sentinels
3664 if (NDecl)
3665 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3667 // Do special checking on direct calls to functions.
3668 if (FDecl) {
3669 if (CheckFunctionCall(FDecl, TheCall))
3670 return ExprError();
3672 if (BuiltinID)
3673 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3674 } else if (NDecl) {
3675 if (CheckBlockCall(NDecl, TheCall))
3676 return ExprError();
3679 return MaybeBindToTemporary(TheCall);
3682 ExprResult
3683 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
3684 SourceLocation RParenLoc, Expr *InitExpr) {
3685 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3686 // FIXME: put back this assert when initializers are worked out.
3687 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3689 TypeSourceInfo *TInfo;
3690 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3691 if (!TInfo)
3692 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3694 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
3697 ExprResult
3698 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3699 SourceLocation RParenLoc, Expr *literalExpr) {
3700 QualType literalType = TInfo->getType();
3702 if (literalType->isArrayType()) {
3703 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3704 PDiag(diag::err_illegal_decl_array_incomplete_type)
3705 << SourceRange(LParenLoc,
3706 literalExpr->getSourceRange().getEnd())))
3707 return ExprError();
3708 if (literalType->isVariableArrayType())
3709 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3710 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
3711 } else if (!literalType->isDependentType() &&
3712 RequireCompleteType(LParenLoc, literalType,
3713 PDiag(diag::err_typecheck_decl_incomplete_type)
3714 << SourceRange(LParenLoc,
3715 literalExpr->getSourceRange().getEnd())))
3716 return ExprError();
3718 InitializedEntity Entity
3719 = InitializedEntity::InitializeTemporary(literalType);
3720 InitializationKind Kind
3721 = InitializationKind::CreateCStyleCast(LParenLoc,
3722 SourceRange(LParenLoc, RParenLoc));
3723 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3724 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3725 MultiExprArg(*this, &literalExpr, 1),
3726 &literalType);
3727 if (Result.isInvalid())
3728 return ExprError();
3729 literalExpr = Result.get();
3731 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3732 if (isFileScope) { // 6.5.2.5p3
3733 if (CheckForConstantInitializer(literalExpr, literalType))
3734 return ExprError();
3737 // In C, compound literals are l-values for some reason.
3738 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3740 return MaybeBindToTemporary(
3741 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3742 VK, literalExpr, isFileScope));
3745 ExprResult
3746 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
3747 SourceLocation RBraceLoc) {
3748 unsigned NumInit = initlist.size();
3749 Expr **InitList = initlist.release();
3751 // Semantic analysis for initializers is done by ActOnDeclarator() and
3752 // CheckInitializer() - it requires knowledge of the object being intialized.
3754 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3755 NumInit, RBraceLoc);
3756 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3757 return Owned(E);
3760 /// Prepares for a scalar cast, performing all the necessary stages
3761 /// except the final cast and returning the kind required.
3762 static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
3763 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3764 // Also, callers should have filtered out the invalid cases with
3765 // pointers. Everything else should be possible.
3767 QualType SrcTy = Src.get()->getType();
3768 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
3769 return CK_NoOp;
3771 switch (SrcTy->getScalarTypeKind()) {
3772 case Type::STK_MemberPointer:
3773 llvm_unreachable("member pointer type in C");
3775 case Type::STK_Pointer:
3776 switch (DestTy->getScalarTypeKind()) {
3777 case Type::STK_Pointer:
3778 return DestTy->isObjCObjectPointerType() ?
3779 CK_AnyPointerToObjCPointerCast :
3780 CK_BitCast;
3781 case Type::STK_Bool:
3782 return CK_PointerToBoolean;
3783 case Type::STK_Integral:
3784 return CK_PointerToIntegral;
3785 case Type::STK_Floating:
3786 case Type::STK_FloatingComplex:
3787 case Type::STK_IntegralComplex:
3788 case Type::STK_MemberPointer:
3789 llvm_unreachable("illegal cast from pointer");
3791 break;
3793 case Type::STK_Bool: // casting from bool is like casting from an integer
3794 case Type::STK_Integral:
3795 switch (DestTy->getScalarTypeKind()) {
3796 case Type::STK_Pointer:
3797 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
3798 return CK_NullToPointer;
3799 return CK_IntegralToPointer;
3800 case Type::STK_Bool:
3801 return CK_IntegralToBoolean;
3802 case Type::STK_Integral:
3803 return CK_IntegralCast;
3804 case Type::STK_Floating:
3805 return CK_IntegralToFloating;
3806 case Type::STK_IntegralComplex:
3807 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3808 CK_IntegralCast);
3809 return CK_IntegralRealToComplex;
3810 case Type::STK_FloatingComplex:
3811 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3812 CK_IntegralToFloating);
3813 return CK_FloatingRealToComplex;
3814 case Type::STK_MemberPointer:
3815 llvm_unreachable("member pointer type in C");
3817 break;
3819 case Type::STK_Floating:
3820 switch (DestTy->getScalarTypeKind()) {
3821 case Type::STK_Floating:
3822 return CK_FloatingCast;
3823 case Type::STK_Bool:
3824 return CK_FloatingToBoolean;
3825 case Type::STK_Integral:
3826 return CK_FloatingToIntegral;
3827 case Type::STK_FloatingComplex:
3828 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3829 CK_FloatingCast);
3830 return CK_FloatingRealToComplex;
3831 case Type::STK_IntegralComplex:
3832 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3833 CK_FloatingToIntegral);
3834 return CK_IntegralRealToComplex;
3835 case Type::STK_Pointer:
3836 llvm_unreachable("valid float->pointer cast?");
3837 case Type::STK_MemberPointer:
3838 llvm_unreachable("member pointer type in C");
3840 break;
3842 case Type::STK_FloatingComplex:
3843 switch (DestTy->getScalarTypeKind()) {
3844 case Type::STK_FloatingComplex:
3845 return CK_FloatingComplexCast;
3846 case Type::STK_IntegralComplex:
3847 return CK_FloatingComplexToIntegralComplex;
3848 case Type::STK_Floating: {
3849 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
3850 if (S.Context.hasSameType(ET, DestTy))
3851 return CK_FloatingComplexToReal;
3852 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
3853 return CK_FloatingCast;
3855 case Type::STK_Bool:
3856 return CK_FloatingComplexToBoolean;
3857 case Type::STK_Integral:
3858 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3859 CK_FloatingComplexToReal);
3860 return CK_FloatingToIntegral;
3861 case Type::STK_Pointer:
3862 llvm_unreachable("valid complex float->pointer cast?");
3863 case Type::STK_MemberPointer:
3864 llvm_unreachable("member pointer type in C");
3866 break;
3868 case Type::STK_IntegralComplex:
3869 switch (DestTy->getScalarTypeKind()) {
3870 case Type::STK_FloatingComplex:
3871 return CK_IntegralComplexToFloatingComplex;
3872 case Type::STK_IntegralComplex:
3873 return CK_IntegralComplexCast;
3874 case Type::STK_Integral: {
3875 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
3876 if (S.Context.hasSameType(ET, DestTy))
3877 return CK_IntegralComplexToReal;
3878 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
3879 return CK_IntegralCast;
3881 case Type::STK_Bool:
3882 return CK_IntegralComplexToBoolean;
3883 case Type::STK_Floating:
3884 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3885 CK_IntegralComplexToReal);
3886 return CK_IntegralToFloating;
3887 case Type::STK_Pointer:
3888 llvm_unreachable("valid complex int->pointer cast?");
3889 case Type::STK_MemberPointer:
3890 llvm_unreachable("member pointer type in C");
3892 break;
3895 llvm_unreachable("Unhandled scalar cast");
3896 return CK_BitCast;
3899 /// CheckCastTypes - Check type constraints for casting between types.
3900 ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3901 QualType castType, Expr *castExpr,
3902 CastKind& Kind, ExprValueKind &VK,
3903 CXXCastPath &BasePath, bool FunctionalStyle) {
3904 if (castExpr->getType() == Context.UnknownAnyTy)
3905 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3907 if (getLangOptions().CPlusPlus)
3908 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
3909 castExpr->getLocEnd()),
3910 castType, VK, castExpr, Kind, BasePath,
3911 FunctionalStyle);
3913 assert(!castExpr->getType()->isPlaceholderType());
3915 // We only support r-value casts in C.
3916 VK = VK_RValue;
3918 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3919 // type needs to be scalar.
3920 if (castType->isVoidType()) {
3921 // We don't necessarily do lvalue-to-rvalue conversions on this.
3922 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3923 if (castExprRes.isInvalid())
3924 return ExprError();
3925 castExpr = castExprRes.take();
3927 // Cast to void allows any expr type.
3928 Kind = CK_ToVoid;
3929 return Owned(castExpr);
3932 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3933 if (castExprRes.isInvalid())
3934 return ExprError();
3935 castExpr = castExprRes.take();
3937 if (RequireCompleteType(TyR.getBegin(), castType,
3938 diag::err_typecheck_cast_to_incomplete))
3939 return ExprError();
3941 if (!castType->isScalarType() && !castType->isVectorType()) {
3942 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
3943 (castType->isStructureType() || castType->isUnionType())) {
3944 // GCC struct/union extension: allow cast to self.
3945 // FIXME: Check that the cast destination type is complete.
3946 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3947 << castType << castExpr->getSourceRange();
3948 Kind = CK_NoOp;
3949 return Owned(castExpr);
3952 if (castType->isUnionType()) {
3953 // GCC cast to union extension
3954 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
3955 RecordDecl::field_iterator Field, FieldEnd;
3956 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
3957 Field != FieldEnd; ++Field) {
3958 if (Context.hasSameUnqualifiedType(Field->getType(),
3959 castExpr->getType()) &&
3960 !Field->isUnnamedBitfield()) {
3961 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3962 << castExpr->getSourceRange();
3963 break;
3966 if (Field == FieldEnd) {
3967 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3968 << castExpr->getType() << castExpr->getSourceRange();
3969 return ExprError();
3971 Kind = CK_ToUnion;
3972 return Owned(castExpr);
3975 // Reject any other conversions to non-scalar types.
3976 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3977 << castType << castExpr->getSourceRange();
3978 return ExprError();
3981 // The type we're casting to is known to be a scalar or vector.
3983 // Require the operand to be a scalar or vector.
3984 if (!castExpr->getType()->isScalarType() &&
3985 !castExpr->getType()->isVectorType()) {
3986 Diag(castExpr->getLocStart(),
3987 diag::err_typecheck_expect_scalar_operand)
3988 << castExpr->getType() << castExpr->getSourceRange();
3989 return ExprError();
3992 if (castType->isExtVectorType())
3993 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3995 if (castType->isVectorType()) {
3996 if (castType->getAs<VectorType>()->getVectorKind() ==
3997 VectorType::AltiVecVector &&
3998 (castExpr->getType()->isIntegerType() ||
3999 castExpr->getType()->isFloatingType())) {
4000 Kind = CK_VectorSplat;
4001 return Owned(castExpr);
4002 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4003 return ExprError();
4004 } else
4005 return Owned(castExpr);
4007 if (castExpr->getType()->isVectorType()) {
4008 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4009 return ExprError();
4010 else
4011 return Owned(castExpr);
4014 // The source and target types are both scalars, i.e.
4015 // - arithmetic types (fundamental, enum, and complex)
4016 // - all kinds of pointers
4017 // Note that member pointers were filtered out with C++, above.
4019 if (isa<ObjCSelectorExpr>(castExpr)) {
4020 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4021 return ExprError();
4024 // If either type is a pointer, the other type has to be either an
4025 // integer or a pointer.
4026 QualType castExprType = castExpr->getType();
4027 if (!castType->isArithmeticType()) {
4028 if (!castExprType->isIntegralType(Context) &&
4029 castExprType->isArithmeticType()) {
4030 Diag(castExpr->getLocStart(),
4031 diag::err_cast_pointer_from_non_pointer_int)
4032 << castExprType << castExpr->getSourceRange();
4033 return ExprError();
4035 } else if (!castExpr->getType()->isArithmeticType()) {
4036 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4037 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4038 << castType << castExpr->getSourceRange();
4039 return ExprError();
4043 if (getLangOptions().ObjCAutoRefCount) {
4044 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4045 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4046 castType, castExpr, CCK_CStyleCast);
4048 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4049 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4050 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4051 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4052 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4053 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4054 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4055 Diag(castExpr->getLocStart(),
4056 diag::err_typecheck_incompatible_ownership)
4057 << castExprType << castType << AA_Casting
4058 << castExpr->getSourceRange();
4060 return ExprError();
4066 castExprRes = Owned(castExpr);
4067 Kind = PrepareScalarCast(*this, castExprRes, castType);
4068 if (castExprRes.isInvalid())
4069 return ExprError();
4070 castExpr = castExprRes.take();
4072 if (Kind == CK_BitCast)
4073 CheckCastAlign(castExpr, castType, TyR);
4075 return Owned(castExpr);
4078 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4079 CastKind &Kind) {
4080 assert(VectorTy->isVectorType() && "Not a vector type!");
4082 if (Ty->isVectorType() || Ty->isIntegerType()) {
4083 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4084 return Diag(R.getBegin(),
4085 Ty->isVectorType() ?
4086 diag::err_invalid_conversion_between_vectors :
4087 diag::err_invalid_conversion_between_vector_and_integer)
4088 << VectorTy << Ty << R;
4089 } else
4090 return Diag(R.getBegin(),
4091 diag::err_invalid_conversion_between_vector_and_scalar)
4092 << VectorTy << Ty << R;
4094 Kind = CK_BitCast;
4095 return false;
4098 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4099 Expr *CastExpr, CastKind &Kind) {
4100 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4102 QualType SrcTy = CastExpr->getType();
4104 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4105 // an ExtVectorType.
4106 if (SrcTy->isVectorType()) {
4107 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4108 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4109 << DestTy << SrcTy << R;
4110 return ExprError();
4112 Kind = CK_BitCast;
4113 return Owned(CastExpr);
4116 // All non-pointer scalars can be cast to ExtVector type. The appropriate
4117 // conversion will take place first from scalar to elt type, and then
4118 // splat from elt type to vector.
4119 if (SrcTy->isPointerType())
4120 return Diag(R.getBegin(),
4121 diag::err_invalid_conversion_between_vector_and_scalar)
4122 << DestTy << SrcTy << R;
4124 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4125 ExprResult CastExprRes = Owned(CastExpr);
4126 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4127 if (CastExprRes.isInvalid())
4128 return ExprError();
4129 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4131 Kind = CK_VectorSplat;
4132 return Owned(CastExpr);
4135 ExprResult
4136 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
4137 SourceLocation RParenLoc, Expr *castExpr) {
4138 assert((Ty != 0) && (castExpr != 0) &&
4139 "ActOnCastExpr(): missing type or expr");
4141 TypeSourceInfo *castTInfo;
4142 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4143 if (!castTInfo)
4144 castTInfo = Context.getTrivialTypeSourceInfo(castType);
4146 // If the Expr being casted is a ParenListExpr, handle it specially.
4147 if (isa<ParenListExpr>(castExpr))
4148 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
4149 castTInfo);
4151 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
4154 ExprResult
4155 Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
4156 SourceLocation RParenLoc, Expr *castExpr) {
4157 CastKind Kind = CK_Invalid;
4158 ExprValueKind VK = VK_RValue;
4159 CXXCastPath BasePath;
4160 ExprResult CastResult =
4161 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4162 castExpr, Kind, VK, BasePath);
4163 if (CastResult.isInvalid())
4164 return ExprError();
4165 castExpr = CastResult.take();
4167 return Owned(CStyleCastExpr::Create(Context,
4168 Ty->getType().getNonLValueExprType(Context),
4169 VK, Kind, castExpr, &BasePath, Ty,
4170 LParenLoc, RParenLoc));
4173 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4174 /// of comma binary operators.
4175 ExprResult
4176 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
4177 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4178 if (!E)
4179 return Owned(expr);
4181 ExprResult Result(E->getExpr(0));
4183 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4184 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4185 E->getExpr(i));
4187 if (Result.isInvalid()) return ExprError();
4189 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4192 ExprResult
4193 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4194 SourceLocation RParenLoc, Expr *Op,
4195 TypeSourceInfo *TInfo) {
4196 ParenListExpr *PE = cast<ParenListExpr>(Op);
4197 QualType Ty = TInfo->getType();
4198 bool isVectorLiteral = false;
4200 // Check for an altivec or OpenCL literal,
4201 // i.e. all the elements are integer constants.
4202 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4203 if (PE->getNumExprs() == 0) {
4204 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4205 return ExprError();
4207 if (PE->getNumExprs() == 1) {
4208 if (!PE->getExpr(0)->getType()->isVectorType())
4209 isVectorLiteral = true;
4211 else
4212 isVectorLiteral = true;
4215 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4216 // then handle it as such.
4217 if (isVectorLiteral) {
4218 llvm::SmallVector<Expr *, 8> initExprs;
4219 // '(...)' form of vector initialization in AltiVec: the number of
4220 // initializers must be one or must match the size of the vector.
4221 // If a single value is specified in the initializer then it will be
4222 // replicated to all the components of the vector
4223 if (Ty->getAs<VectorType>()->getVectorKind() ==
4224 VectorType::AltiVecVector) {
4225 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4226 // The number of initializers must be one or must match the size of the
4227 // vector. If a single value is specified in the initializer then it will
4228 // be replicated to all the components of the vector
4229 if (PE->getNumExprs() == 1) {
4230 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4231 ExprResult Literal = Owned(PE->getExpr(0));
4232 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4233 PrepareScalarCast(*this, Literal, ElemTy));
4234 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4236 else if (PE->getNumExprs() < numElems) {
4237 Diag(PE->getExprLoc(),
4238 diag::err_incorrect_number_of_vector_initializers);
4239 return ExprError();
4241 else
4242 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4243 initExprs.push_back(PE->getExpr(i));
4245 else
4246 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4247 initExprs.push_back(PE->getExpr(i));
4249 // FIXME: This means that pretty-printing the final AST will produce curly
4250 // braces instead of the original commas.
4251 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4252 &initExprs[0],
4253 initExprs.size(), RParenLoc);
4254 E->setType(Ty);
4255 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
4256 } else {
4257 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4258 // sequence of BinOp comma operators.
4259 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
4260 if (Result.isInvalid()) return ExprError();
4261 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
4265 ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
4266 SourceLocation R,
4267 MultiExprArg Val,
4268 ParsedType TypeOfCast) {
4269 unsigned nexprs = Val.size();
4270 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4271 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4272 Expr *expr;
4273 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4274 expr = new (Context) ParenExpr(L, R, exprs[0]);
4275 else
4276 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4277 exprs[nexprs-1]->getType());
4278 return Owned(expr);
4281 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4282 /// constant and the other is not a pointer.
4283 bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4284 SourceLocation QuestionLoc) {
4285 Expr *NullExpr = LHS;
4286 Expr *NonPointerExpr = RHS;
4287 Expr::NullPointerConstantKind NullKind =
4288 NullExpr->isNullPointerConstant(Context,
4289 Expr::NPC_ValueDependentIsNotNull);
4291 if (NullKind == Expr::NPCK_NotNull) {
4292 NullExpr = RHS;
4293 NonPointerExpr = LHS;
4294 NullKind =
4295 NullExpr->isNullPointerConstant(Context,
4296 Expr::NPC_ValueDependentIsNotNull);
4299 if (NullKind == Expr::NPCK_NotNull)
4300 return false;
4302 if (NullKind == Expr::NPCK_ZeroInteger) {
4303 // In this case, check to make sure that we got here from a "NULL"
4304 // string in the source code.
4305 NullExpr = NullExpr->IgnoreParenImpCasts();
4306 SourceLocation loc = NullExpr->getExprLoc();
4307 if (!findMacroSpelling(loc, "NULL"))
4308 return false;
4311 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4312 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4313 << NonPointerExpr->getType() << DiagType
4314 << NonPointerExpr->getSourceRange();
4315 return true;
4318 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4319 /// In that case, lhs = cond.
4320 /// C99 6.5.15
4321 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
4322 ExprValueKind &VK, ExprObjectKind &OK,
4323 SourceLocation QuestionLoc) {
4325 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
4326 if (!lhsResult.isUsable()) return QualType();
4327 LHS = move(lhsResult);
4329 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
4330 if (!rhsResult.isUsable()) return QualType();
4331 RHS = move(rhsResult);
4333 // C++ is sufficiently different to merit its own checker.
4334 if (getLangOptions().CPlusPlus)
4335 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4337 VK = VK_RValue;
4338 OK = OK_Ordinary;
4340 Cond = UsualUnaryConversions(Cond.take());
4341 if (Cond.isInvalid())
4342 return QualType();
4343 LHS = UsualUnaryConversions(LHS.take());
4344 if (LHS.isInvalid())
4345 return QualType();
4346 RHS = UsualUnaryConversions(RHS.take());
4347 if (RHS.isInvalid())
4348 return QualType();
4350 QualType CondTy = Cond.get()->getType();
4351 QualType LHSTy = LHS.get()->getType();
4352 QualType RHSTy = RHS.get()->getType();
4354 // first, check the condition.
4355 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4356 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4357 // Throw an error if its not either.
4358 if (getLangOptions().OpenCL) {
4359 if (!CondTy->isVectorType()) {
4360 Diag(Cond.get()->getLocStart(),
4361 diag::err_typecheck_cond_expect_scalar_or_vector)
4362 << CondTy;
4363 return QualType();
4366 else {
4367 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4368 << CondTy;
4369 return QualType();
4373 // Now check the two expressions.
4374 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4375 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4377 // OpenCL: If the condition is a vector, and both operands are scalar,
4378 // attempt to implicity convert them to the vector type to act like the
4379 // built in select.
4380 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4381 // Both operands should be of scalar type.
4382 if (!LHSTy->isScalarType()) {
4383 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4384 << CondTy;
4385 return QualType();
4387 if (!RHSTy->isScalarType()) {
4388 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4389 << CondTy;
4390 return QualType();
4392 // Implicity convert these scalars to the type of the condition.
4393 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4394 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4397 // If both operands have arithmetic type, do the usual arithmetic conversions
4398 // to find a common type: C99 6.5.15p3,5.
4399 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4400 UsualArithmeticConversions(LHS, RHS);
4401 if (LHS.isInvalid() || RHS.isInvalid())
4402 return QualType();
4403 return LHS.get()->getType();
4406 // If both operands are the same structure or union type, the result is that
4407 // type.
4408 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4409 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4410 if (LHSRT->getDecl() == RHSRT->getDecl())
4411 // "If both the operands have structure or union type, the result has
4412 // that type." This implies that CV qualifiers are dropped.
4413 return LHSTy.getUnqualifiedType();
4414 // FIXME: Type of conditional expression must be complete in C mode.
4417 // C99 6.5.15p5: "If both operands have void type, the result has void type."
4418 // The following || allows only one side to be void (a GCC-ism).
4419 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4420 if (!LHSTy->isVoidType())
4421 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4422 << RHS.get()->getSourceRange();
4423 if (!RHSTy->isVoidType())
4424 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4425 << LHS.get()->getSourceRange();
4426 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4427 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
4428 return Context.VoidTy;
4430 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4431 // the type of the other operand."
4432 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
4433 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4434 // promote the null to a pointer.
4435 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
4436 return LHSTy;
4438 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
4439 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4440 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
4441 return RHSTy;
4444 // All objective-c pointer type analysis is done here.
4445 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4446 QuestionLoc);
4447 if (LHS.isInvalid() || RHS.isInvalid())
4448 return QualType();
4449 if (!compositeType.isNull())
4450 return compositeType;
4453 // Handle block pointer types.
4454 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4455 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4456 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4457 QualType destType = Context.getPointerType(Context.VoidTy);
4458 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4459 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4460 return destType;
4462 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4463 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4464 return QualType();
4466 // We have 2 block pointer types.
4467 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4468 // Two identical block pointer types are always compatible.
4469 return LHSTy;
4471 // The block pointer types aren't identical, continue checking.
4472 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4473 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
4475 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4476 rhptee.getUnqualifiedType())) {
4477 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4478 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4479 // In this situation, we assume void* type. No especially good
4480 // reason, but this is what gcc does, and we do have to pick
4481 // to get a consistent AST.
4482 QualType incompatTy = Context.getPointerType(Context.VoidTy);
4483 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4484 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4485 return incompatTy;
4487 // The block pointer types are compatible.
4488 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4489 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4490 return LHSTy;
4493 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4494 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4495 // get the "pointed to" types
4496 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4497 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4499 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4500 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4501 // Figure out necessary qualifiers (C99 6.5.15p6)
4502 QualType destPointee
4503 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4504 QualType destType = Context.getPointerType(destPointee);
4505 // Add qualifiers if necessary.
4506 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4507 // Promote to void*.
4508 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4509 return destType;
4511 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4512 QualType destPointee
4513 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4514 QualType destType = Context.getPointerType(destPointee);
4515 // Add qualifiers if necessary.
4516 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4517 // Promote to void*.
4518 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4519 return destType;
4522 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4523 // Two identical pointer types are always compatible.
4524 return LHSTy;
4526 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4527 rhptee.getUnqualifiedType())) {
4528 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4529 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4530 // In this situation, we assume void* type. No especially good
4531 // reason, but this is what gcc does, and we do have to pick
4532 // to get a consistent AST.
4533 QualType incompatTy = Context.getPointerType(Context.VoidTy);
4534 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4535 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4536 return incompatTy;
4538 // The pointer types are compatible.
4539 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4540 // differently qualified versions of compatible types, the result type is
4541 // a pointer to an appropriately qualified version of the *composite*
4542 // type.
4543 // FIXME: Need to calculate the composite type.
4544 // FIXME: Need to add qualifiers
4545 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4546 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4547 return LHSTy;
4550 // GCC compatibility: soften pointer/integer mismatch. Note that
4551 // null pointers have been filtered out by this point.
4552 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4553 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4554 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4555 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
4556 return RHSTy;
4558 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4559 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4560 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4561 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
4562 return LHSTy;
4565 // Emit a better diagnostic if one of the expressions is a null pointer
4566 // constant and the other is not a pointer type. In this case, the user most
4567 // likely forgot to take the address of the other expression.
4568 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4569 return QualType();
4571 // Otherwise, the operands are not compatible.
4572 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4573 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4574 return QualType();
4577 /// FindCompositeObjCPointerType - Helper method to find composite type of
4578 /// two objective-c pointer types of the two input expressions.
4579 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
4580 SourceLocation QuestionLoc) {
4581 QualType LHSTy = LHS.get()->getType();
4582 QualType RHSTy = RHS.get()->getType();
4584 // Handle things like Class and struct objc_class*. Here we case the result
4585 // to the pseudo-builtin, because that will be implicitly cast back to the
4586 // redefinition type if an attempt is made to access its fields.
4587 if (LHSTy->isObjCClassType() &&
4588 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
4589 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4590 return LHSTy;
4592 if (RHSTy->isObjCClassType() &&
4593 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
4594 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
4595 return RHSTy;
4597 // And the same for struct objc_object* / id
4598 if (LHSTy->isObjCIdType() &&
4599 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
4600 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4601 return LHSTy;
4603 if (RHSTy->isObjCIdType() &&
4604 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
4605 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
4606 return RHSTy;
4608 // And the same for struct objc_selector* / SEL
4609 if (Context.isObjCSelType(LHSTy) &&
4610 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
4611 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4612 return LHSTy;
4614 if (Context.isObjCSelType(RHSTy) &&
4615 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
4616 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
4617 return RHSTy;
4619 // Check constraints for Objective-C object pointers types.
4620 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4622 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4623 // Two identical object pointer types are always compatible.
4624 return LHSTy;
4626 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4627 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4628 QualType compositeType = LHSTy;
4630 // If both operands are interfaces and either operand can be
4631 // assigned to the other, use that type as the composite
4632 // type. This allows
4633 // xxx ? (A*) a : (B*) b
4634 // where B is a subclass of A.
4636 // Additionally, as for assignment, if either type is 'id'
4637 // allow silent coercion. Finally, if the types are
4638 // incompatible then make sure to use 'id' as the composite
4639 // type so the result is acceptable for sending messages to.
4641 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4642 // It could return the composite type.
4643 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4644 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4645 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4646 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4647 } else if ((LHSTy->isObjCQualifiedIdType() ||
4648 RHSTy->isObjCQualifiedIdType()) &&
4649 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4650 // Need to handle "id<xx>" explicitly.
4651 // GCC allows qualified id and any Objective-C type to devolve to
4652 // id. Currently localizing to here until clear this should be
4653 // part of ObjCQualifiedIdTypesAreCompatible.
4654 compositeType = Context.getObjCIdType();
4655 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4656 compositeType = Context.getObjCIdType();
4657 } else if (!(compositeType =
4658 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4660 else {
4661 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4662 << LHSTy << RHSTy
4663 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4664 QualType incompatTy = Context.getObjCIdType();
4665 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4666 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4667 return incompatTy;
4669 // The object pointer types are compatible.
4670 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4671 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
4672 return compositeType;
4674 // Check Objective-C object pointer types and 'void *'
4675 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4676 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4677 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4678 QualType destPointee
4679 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4680 QualType destType = Context.getPointerType(destPointee);
4681 // Add qualifiers if necessary.
4682 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4683 // Promote to void*.
4684 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4685 return destType;
4687 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4688 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4689 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4690 QualType destPointee
4691 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4692 QualType destType = Context.getPointerType(destPointee);
4693 // Add qualifiers if necessary.
4694 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4695 // Promote to void*.
4696 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4697 return destType;
4699 return QualType();
4702 /// SuggestParentheses - Emit a note with a fixit hint that wraps
4703 /// ParenRange in parentheses.
4704 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
4705 const PartialDiagnostic &Note,
4706 SourceRange ParenRange) {
4707 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4708 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4709 EndLoc.isValid()) {
4710 Self.Diag(Loc, Note)
4711 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4712 << FixItHint::CreateInsertion(EndLoc, ")");
4713 } else {
4714 // We can't display the parentheses, so just show the bare note.
4715 Self.Diag(Loc, Note) << ParenRange;
4719 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4720 return Opc >= BO_Mul && Opc <= BO_Shr;
4723 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4724 /// expression, either using a built-in or overloaded operator,
4725 /// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4726 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4727 Expr **RHS) {
4728 E = E->IgnoreParenImpCasts();
4729 E = E->IgnoreConversionOperator();
4730 E = E->IgnoreParenImpCasts();
4732 // Built-in binary operator.
4733 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4734 if (IsArithmeticOp(OP->getOpcode())) {
4735 *Opcode = OP->getOpcode();
4736 *RHS = OP->getRHS();
4737 return true;
4741 // Overloaded operator.
4742 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4743 if (Call->getNumArgs() != 2)
4744 return false;
4746 // Make sure this is really a binary operator that is safe to pass into
4747 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4748 OverloadedOperatorKind OO = Call->getOperator();
4749 if (OO < OO_Plus || OO > OO_Arrow)
4750 return false;
4752 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4753 if (IsArithmeticOp(OpKind)) {
4754 *Opcode = OpKind;
4755 *RHS = Call->getArg(1);
4756 return true;
4760 return false;
4763 static bool IsLogicOp(BinaryOperatorKind Opc) {
4764 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4767 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4768 /// or is a logical expression such as (x==y) which has int type, but is
4769 /// commonly interpreted as boolean.
4770 static bool ExprLooksBoolean(Expr *E) {
4771 E = E->IgnoreParenImpCasts();
4773 if (E->getType()->isBooleanType())
4774 return true;
4775 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4776 return IsLogicOp(OP->getOpcode());
4777 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4778 return OP->getOpcode() == UO_LNot;
4780 return false;
4783 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4784 /// and binary operator are mixed in a way that suggests the programmer assumed
4785 /// the conditional operator has higher precedence, for example:
4786 /// "int x = a + someBinaryCondition ? 1 : 2".
4787 static void DiagnoseConditionalPrecedence(Sema &Self,
4788 SourceLocation OpLoc,
4789 Expr *Condition,
4790 Expr *LHS,
4791 Expr *RHS) {
4792 BinaryOperatorKind CondOpcode;
4793 Expr *CondRHS;
4795 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
4796 return;
4797 if (!ExprLooksBoolean(CondRHS))
4798 return;
4800 // The condition is an arithmetic binary expression, with a right-
4801 // hand side that looks boolean, so warn.
4803 Self.Diag(OpLoc, diag::warn_precedence_conditional)
4804 << Condition->getSourceRange()
4805 << BinaryOperator::getOpcodeStr(CondOpcode);
4807 SuggestParentheses(Self, OpLoc,
4808 Self.PDiag(diag::note_precedence_conditional_silence)
4809 << BinaryOperator::getOpcodeStr(CondOpcode),
4810 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
4812 SuggestParentheses(Self, OpLoc,
4813 Self.PDiag(diag::note_precedence_conditional_first),
4814 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
4817 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4818 /// in the case of a the GNU conditional expr extension.
4819 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4820 SourceLocation ColonLoc,
4821 Expr *CondExpr, Expr *LHSExpr,
4822 Expr *RHSExpr) {
4823 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4824 // was the condition.
4825 OpaqueValueExpr *opaqueValue = 0;
4826 Expr *commonExpr = 0;
4827 if (LHSExpr == 0) {
4828 commonExpr = CondExpr;
4830 // We usually want to apply unary conversions *before* saving, except
4831 // in the special case of a C++ l-value conditional.
4832 if (!(getLangOptions().CPlusPlus
4833 && !commonExpr->isTypeDependent()
4834 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4835 && commonExpr->isGLValue()
4836 && commonExpr->isOrdinaryOrBitFieldObject()
4837 && RHSExpr->isOrdinaryOrBitFieldObject()
4838 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
4839 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4840 if (commonRes.isInvalid())
4841 return ExprError();
4842 commonExpr = commonRes.take();
4845 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4846 commonExpr->getType(),
4847 commonExpr->getValueKind(),
4848 commonExpr->getObjectKind());
4849 LHSExpr = CondExpr = opaqueValue;
4852 ExprValueKind VK = VK_RValue;
4853 ExprObjectKind OK = OK_Ordinary;
4854 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4855 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
4856 VK, OK, QuestionLoc);
4857 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4858 RHS.isInvalid())
4859 return ExprError();
4861 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4862 RHS.get());
4864 if (!commonExpr)
4865 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4866 LHS.take(), ColonLoc,
4867 RHS.take(), result, VK, OK));
4869 return Owned(new (Context)
4870 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
4871 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
4874 // checkPointerTypesForAssignment - This is a very tricky routine (despite
4875 // being closely modeled after the C99 spec:-). The odd characteristic of this
4876 // routine is it effectively iqnores the qualifiers on the top level pointee.
4877 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4878 // FIXME: add a couple examples in this comment.
4879 static Sema::AssignConvertType
4880 checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
4881 assert(lhsType.isCanonical() && "LHS not canonicalized!");
4882 assert(rhsType.isCanonical() && "RHS not canonicalized!");
4884 // get the "pointed to" type (ignoring qualifiers at the top level)
4885 const Type *lhptee, *rhptee;
4886 Qualifiers lhq, rhq;
4887 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
4888 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
4890 Sema::AssignConvertType ConvTy = Sema::Compatible;
4892 // C99 6.5.16.1p1: This following citation is common to constraints
4893 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4894 // qualifiers of the type *pointed to* by the right;
4895 Qualifiers lq;
4897 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
4898 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
4899 lhq.compatiblyIncludesObjCLifetime(rhq)) {
4900 // Ignore lifetime for further calculation.
4901 lhq.removeObjCLifetime();
4902 rhq.removeObjCLifetime();
4905 if (!lhq.compatiblyIncludes(rhq)) {
4906 // Treat address-space mismatches as fatal. TODO: address subspaces
4907 if (lhq.getAddressSpace() != rhq.getAddressSpace())
4908 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4910 // It's okay to add or remove GC or lifetime qualifiers when converting to
4911 // and from void*.
4912 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
4913 .compatiblyIncludes(
4914 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
4915 && (lhptee->isVoidType() || rhptee->isVoidType()))
4916 ; // keep old
4918 // Treat lifetime mismatches as fatal.
4919 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
4920 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4922 // For GCC compatibility, other qualifier mismatches are treated
4923 // as still compatible in C.
4924 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
4927 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4928 // incomplete type and the other is a pointer to a qualified or unqualified
4929 // version of void...
4930 if (lhptee->isVoidType()) {
4931 if (rhptee->isIncompleteOrObjectType())
4932 return ConvTy;
4934 // As an extension, we allow cast to/from void* to function pointer.
4935 assert(rhptee->isFunctionType());
4936 return Sema::FunctionVoidPointer;
4939 if (rhptee->isVoidType()) {
4940 if (lhptee->isIncompleteOrObjectType())
4941 return ConvTy;
4943 // As an extension, we allow cast to/from void* to function pointer.
4944 assert(lhptee->isFunctionType());
4945 return Sema::FunctionVoidPointer;
4948 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
4949 // unqualified versions of compatible types, ...
4950 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
4951 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
4952 // Check if the pointee types are compatible ignoring the sign.
4953 // We explicitly check for char so that we catch "char" vs
4954 // "unsigned char" on systems where "char" is unsigned.
4955 if (lhptee->isCharType())
4956 ltrans = S.Context.UnsignedCharTy;
4957 else if (lhptee->hasSignedIntegerRepresentation())
4958 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
4960 if (rhptee->isCharType())
4961 rtrans = S.Context.UnsignedCharTy;
4962 else if (rhptee->hasSignedIntegerRepresentation())
4963 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
4965 if (ltrans == rtrans) {
4966 // Types are compatible ignoring the sign. Qualifier incompatibility
4967 // takes priority over sign incompatibility because the sign
4968 // warning can be disabled.
4969 if (ConvTy != Sema::Compatible)
4970 return ConvTy;
4972 return Sema::IncompatiblePointerSign;
4975 // If we are a multi-level pointer, it's possible that our issue is simply
4976 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4977 // the eventual target type is the same and the pointers have the same
4978 // level of indirection, this must be the issue.
4979 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
4980 do {
4981 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
4982 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
4983 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
4985 if (lhptee == rhptee)
4986 return Sema::IncompatibleNestedPointerQualifiers;
4989 // General pointer incompatibility takes priority over qualifiers.
4990 return Sema::IncompatiblePointer;
4992 return ConvTy;
4995 /// checkBlockPointerTypesForAssignment - This routine determines whether two
4996 /// block pointer types are compatible or whether a block and normal pointer
4997 /// are compatible. It is more restrict than comparing two function pointer
4998 // types.
4999 static Sema::AssignConvertType
5000 checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5001 QualType rhsType) {
5002 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5003 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5005 QualType lhptee, rhptee;
5007 // get the "pointed to" type (ignoring qualifiers at the top level)
5008 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5009 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
5011 // In C++, the types have to match exactly.
5012 if (S.getLangOptions().CPlusPlus)
5013 return Sema::IncompatibleBlockPointer;
5015 Sema::AssignConvertType ConvTy = Sema::Compatible;
5017 // For blocks we enforce that qualifiers are identical.
5018 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5019 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5021 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5022 return Sema::IncompatibleBlockPointer;
5024 return ConvTy;
5027 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5028 /// for assignment compatibility.
5029 static Sema::AssignConvertType
5030 checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5031 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5032 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5034 if (lhsType->isObjCBuiltinType()) {
5035 // Class is not compatible with ObjC object pointers.
5036 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5037 !rhsType->isObjCQualifiedClassType())
5038 return Sema::IncompatiblePointer;
5039 return Sema::Compatible;
5041 if (rhsType->isObjCBuiltinType()) {
5042 // Class is not compatible with ObjC object pointers.
5043 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5044 !lhsType->isObjCQualifiedClassType())
5045 return Sema::IncompatiblePointer;
5046 return Sema::Compatible;
5048 QualType lhptee =
5049 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5050 QualType rhptee =
5051 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5053 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5054 return Sema::CompatiblePointerDiscardsQualifiers;
5056 if (S.Context.typesAreCompatible(lhsType, rhsType))
5057 return Sema::Compatible;
5058 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5059 return Sema::IncompatibleObjCQualifiedId;
5060 return Sema::IncompatiblePointer;
5063 Sema::AssignConvertType
5064 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5065 QualType lhsType, QualType rhsType) {
5066 // Fake up an opaque expression. We don't actually care about what
5067 // cast operations are required, so if CheckAssignmentConstraints
5068 // adds casts to this they'll be wasted, but fortunately that doesn't
5069 // usually happen on valid code.
5070 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
5071 ExprResult rhsPtr = &rhs;
5072 CastKind K = CK_Invalid;
5074 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5077 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5078 /// has code to accommodate several GCC extensions when type checking
5079 /// pointers. Here are some objectionable examples that GCC considers warnings:
5081 /// int a, *pint;
5082 /// short *pshort;
5083 /// struct foo *pfoo;
5085 /// pint = pshort; // warning: assignment from incompatible pointer type
5086 /// a = pint; // warning: assignment makes integer from pointer without a cast
5087 /// pint = a; // warning: assignment makes pointer from integer without a cast
5088 /// pint = pfoo; // warning: assignment from incompatible pointer type
5090 /// As a result, the code for dealing with pointers is more complex than the
5091 /// C99 spec dictates.
5093 /// Sets 'Kind' for any result kind except Incompatible.
5094 Sema::AssignConvertType
5095 Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
5096 CastKind &Kind) {
5097 QualType rhsType = rhs.get()->getType();
5099 // Get canonical types. We're not formatting these types, just comparing
5100 // them.
5101 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5102 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
5104 // Common case: no conversion required.
5105 if (lhsType == rhsType) {
5106 Kind = CK_NoOp;
5107 return Compatible;
5110 // If the left-hand side is a reference type, then we are in a
5111 // (rare!) case where we've allowed the use of references in C,
5112 // e.g., as a parameter type in a built-in function. In this case,
5113 // just make sure that the type referenced is compatible with the
5114 // right-hand side type. The caller is responsible for adjusting
5115 // lhsType so that the resulting expression does not have reference
5116 // type.
5117 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
5118 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5119 Kind = CK_LValueBitCast;
5120 return Compatible;
5122 return Incompatible;
5125 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5126 // to the same ExtVector type.
5127 if (lhsType->isExtVectorType()) {
5128 if (rhsType->isExtVectorType())
5129 return Incompatible;
5130 if (rhsType->isArithmeticType()) {
5131 // CK_VectorSplat does T -> vector T, so first cast to the
5132 // element type.
5133 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5134 if (elType != rhsType) {
5135 Kind = PrepareScalarCast(*this, rhs, elType);
5136 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
5138 Kind = CK_VectorSplat;
5139 return Compatible;
5143 // Conversions to or from vector type.
5144 if (lhsType->isVectorType() || rhsType->isVectorType()) {
5145 if (lhsType->isVectorType() && rhsType->isVectorType()) {
5146 // Allow assignments of an AltiVec vector type to an equivalent GCC
5147 // vector type and vice versa
5148 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5149 Kind = CK_BitCast;
5150 return Compatible;
5153 // If we are allowing lax vector conversions, and LHS and RHS are both
5154 // vectors, the total size only needs to be the same. This is a bitcast;
5155 // no bits are changed but the result type is different.
5156 if (getLangOptions().LaxVectorConversions &&
5157 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
5158 Kind = CK_BitCast;
5159 return IncompatibleVectors;
5162 return Incompatible;
5165 // Arithmetic conversions.
5166 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
5167 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
5168 Kind = PrepareScalarCast(*this, rhs, lhsType);
5169 return Compatible;
5172 // Conversions to normal pointers.
5173 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5174 // U* -> T*
5175 if (isa<PointerType>(rhsType)) {
5176 Kind = CK_BitCast;
5177 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
5180 // int -> T*
5181 if (rhsType->isIntegerType()) {
5182 Kind = CK_IntegralToPointer; // FIXME: null?
5183 return IntToPointer;
5186 // C pointers are not compatible with ObjC object pointers,
5187 // with two exceptions:
5188 if (isa<ObjCObjectPointerType>(rhsType)) {
5189 // - conversions to void*
5190 if (lhsPointer->getPointeeType()->isVoidType()) {
5191 Kind = CK_AnyPointerToObjCPointerCast;
5192 return Compatible;
5195 // - conversions from 'Class' to the redefinition type
5196 if (rhsType->isObjCClassType() &&
5197 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
5198 Kind = CK_BitCast;
5199 return Compatible;
5202 Kind = CK_BitCast;
5203 return IncompatiblePointer;
5206 // U^ -> void*
5207 if (rhsType->getAs<BlockPointerType>()) {
5208 if (lhsPointer->getPointeeType()->isVoidType()) {
5209 Kind = CK_BitCast;
5210 return Compatible;
5214 return Incompatible;
5217 // Conversions to block pointers.
5218 if (isa<BlockPointerType>(lhsType)) {
5219 // U^ -> T^
5220 if (rhsType->isBlockPointerType()) {
5221 Kind = CK_AnyPointerToBlockPointerCast;
5222 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
5225 // int or null -> T^
5226 if (rhsType->isIntegerType()) {
5227 Kind = CK_IntegralToPointer; // FIXME: null
5228 return IntToBlockPointer;
5231 // id -> T^
5232 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5233 Kind = CK_AnyPointerToBlockPointerCast;
5234 return Compatible;
5237 // void* -> T^
5238 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
5239 if (RHSPT->getPointeeType()->isVoidType()) {
5240 Kind = CK_AnyPointerToBlockPointerCast;
5241 return Compatible;
5244 return Incompatible;
5247 // Conversions to Objective-C pointers.
5248 if (isa<ObjCObjectPointerType>(lhsType)) {
5249 // A* -> B*
5250 if (rhsType->isObjCObjectPointerType()) {
5251 Kind = CK_BitCast;
5252 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5255 // int or null -> A*
5256 if (rhsType->isIntegerType()) {
5257 Kind = CK_IntegralToPointer; // FIXME: null
5258 return IntToPointer;
5261 // In general, C pointers are not compatible with ObjC object pointers,
5262 // with two exceptions:
5263 if (isa<PointerType>(rhsType)) {
5264 // - conversions from 'void*'
5265 if (rhsType->isVoidPointerType()) {
5266 Kind = CK_AnyPointerToObjCPointerCast;
5267 return Compatible;
5270 // - conversions to 'Class' from its redefinition type
5271 if (lhsType->isObjCClassType() &&
5272 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5273 Kind = CK_BitCast;
5274 return Compatible;
5277 Kind = CK_AnyPointerToObjCPointerCast;
5278 return IncompatiblePointer;
5281 // T^ -> A*
5282 if (rhsType->isBlockPointerType()) {
5283 Kind = CK_AnyPointerToObjCPointerCast;
5284 return Compatible;
5287 return Incompatible;
5290 // Conversions from pointers that are not covered by the above.
5291 if (isa<PointerType>(rhsType)) {
5292 // T* -> _Bool
5293 if (lhsType == Context.BoolTy) {
5294 Kind = CK_PointerToBoolean;
5295 return Compatible;
5298 // T* -> int
5299 if (lhsType->isIntegerType()) {
5300 Kind = CK_PointerToIntegral;
5301 return PointerToInt;
5304 return Incompatible;
5307 // Conversions from Objective-C pointers that are not covered by the above.
5308 if (isa<ObjCObjectPointerType>(rhsType)) {
5309 // T* -> _Bool
5310 if (lhsType == Context.BoolTy) {
5311 Kind = CK_PointerToBoolean;
5312 return Compatible;
5315 // T* -> int
5316 if (lhsType->isIntegerType()) {
5317 Kind = CK_PointerToIntegral;
5318 return PointerToInt;
5321 return Incompatible;
5324 // struct A -> struct B
5325 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
5326 if (Context.typesAreCompatible(lhsType, rhsType)) {
5327 Kind = CK_NoOp;
5328 return Compatible;
5332 return Incompatible;
5335 /// \brief Constructs a transparent union from an expression that is
5336 /// used to initialize the transparent union.
5337 static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
5338 QualType UnionType, FieldDecl *Field) {
5339 // Build an initializer list that designates the appropriate member
5340 // of the transparent union.
5341 Expr *E = EResult.take();
5342 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5343 &E, 1,
5344 SourceLocation());
5345 Initializer->setType(UnionType);
5346 Initializer->setInitializedFieldInUnion(Field);
5348 // Build a compound literal constructing a value of the transparent
5349 // union type from this initializer list.
5350 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5351 EResult = S.Owned(
5352 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5353 VK_RValue, Initializer, false));
5356 Sema::AssignConvertType
5357 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
5358 QualType FromType = rExpr.get()->getType();
5360 // If the ArgType is a Union type, we want to handle a potential
5361 // transparent_union GCC extension.
5362 const RecordType *UT = ArgType->getAsUnionType();
5363 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5364 return Incompatible;
5366 // The field to initialize within the transparent union.
5367 RecordDecl *UD = UT->getDecl();
5368 FieldDecl *InitField = 0;
5369 // It's compatible if the expression matches any of the fields.
5370 for (RecordDecl::field_iterator it = UD->field_begin(),
5371 itend = UD->field_end();
5372 it != itend; ++it) {
5373 if (it->getType()->isPointerType()) {
5374 // If the transparent union contains a pointer type, we allow:
5375 // 1) void pointer
5376 // 2) null pointer constant
5377 if (FromType->isPointerType())
5378 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5379 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
5380 InitField = *it;
5381 break;
5384 if (rExpr.get()->isNullPointerConstant(Context,
5385 Expr::NPC_ValueDependentIsNull)) {
5386 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
5387 InitField = *it;
5388 break;
5392 CastKind Kind = CK_Invalid;
5393 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
5394 == Compatible) {
5395 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
5396 InitField = *it;
5397 break;
5401 if (!InitField)
5402 return Incompatible;
5404 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
5405 return Compatible;
5408 Sema::AssignConvertType
5409 Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
5410 if (getLangOptions().CPlusPlus) {
5411 if (!lhsType->isRecordType()) {
5412 // C++ 5.17p3: If the left operand is not of class type, the
5413 // expression is implicitly converted (C++ 4) to the
5414 // cv-unqualified type of the left operand.
5415 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5416 lhsType.getUnqualifiedType(),
5417 AA_Assigning);
5418 if (Res.isInvalid())
5419 return Incompatible;
5420 rExpr = move(Res);
5421 return Compatible;
5424 // FIXME: Currently, we fall through and treat C++ classes like C
5425 // structures.
5428 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5429 // a null pointer constant.
5430 if ((lhsType->isPointerType() ||
5431 lhsType->isObjCObjectPointerType() ||
5432 lhsType->isBlockPointerType())
5433 && rExpr.get()->isNullPointerConstant(Context,
5434 Expr::NPC_ValueDependentIsNull)) {
5435 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
5436 return Compatible;
5439 // This check seems unnatural, however it is necessary to ensure the proper
5440 // conversion of functions/arrays. If the conversion were done for all
5441 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5442 // expressions that suppress this implicit conversion (&, sizeof).
5444 // Suppress this for references: C++ 8.5.3p5.
5445 if (!lhsType->isReferenceType()) {
5446 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5447 if (rExpr.isInvalid())
5448 return Incompatible;
5451 CastKind Kind = CK_Invalid;
5452 Sema::AssignConvertType result =
5453 CheckAssignmentConstraints(lhsType, rExpr, Kind);
5455 // C99 6.5.16.1p2: The value of the right operand is converted to the
5456 // type of the assignment expression.
5457 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5458 // so that we can use references in built-in functions even in C.
5459 // The getNonReferenceType() call makes sure that the resulting expression
5460 // does not have reference type.
5461 if (result != Incompatible && rExpr.get()->getType() != lhsType)
5462 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
5463 return result;
5466 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
5467 Diag(Loc, diag::err_typecheck_invalid_operands)
5468 << lex.get()->getType() << rex.get()->getType()
5469 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5470 return QualType();
5473 QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5474 SourceLocation Loc, bool isCompAssign) {
5475 // For conversion purposes, we ignore any qualifiers.
5476 // For example, "const float" and "float" are equivalent.
5477 QualType lhsType =
5478 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
5479 QualType rhsType =
5480 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
5482 // If the vector types are identical, return.
5483 if (lhsType == rhsType)
5484 return lhsType;
5486 // Handle the case of equivalent AltiVec and GCC vector types
5487 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5488 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5489 if (lhsType->isExtVectorType()) {
5490 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5491 return lhsType;
5494 if (!isCompAssign)
5495 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
5496 return rhsType;
5499 if (getLangOptions().LaxVectorConversions &&
5500 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5501 // If we are allowing lax vector conversions, and LHS and RHS are both
5502 // vectors, the total size only needs to be the same. This is a
5503 // bitcast; no bits are changed but the result type is different.
5504 // FIXME: Should we really be allowing this?
5505 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5506 return lhsType;
5509 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5510 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5511 bool swapped = false;
5512 if (rhsType->isExtVectorType() && !isCompAssign) {
5513 swapped = true;
5514 std::swap(rex, lex);
5515 std::swap(rhsType, lhsType);
5518 // Handle the case of an ext vector and scalar.
5519 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
5520 QualType EltTy = LV->getElementType();
5521 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
5522 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5523 if (order > 0)
5524 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
5525 if (order >= 0) {
5526 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
5527 if (swapped) std::swap(rex, lex);
5528 return lhsType;
5531 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5532 rhsType->isRealFloatingType()) {
5533 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5534 if (order > 0)
5535 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
5536 if (order >= 0) {
5537 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
5538 if (swapped) std::swap(rex, lex);
5539 return lhsType;
5544 // Vectors of different size or scalar and non-ext-vector are errors.
5545 if (swapped) std::swap(rex, lex);
5546 Diag(Loc, diag::err_typecheck_vector_not_convertable)
5547 << lex.get()->getType() << rex.get()->getType()
5548 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5549 return QualType();
5552 QualType Sema::CheckMultiplyDivideOperands(
5553 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5554 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
5555 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
5557 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
5558 if (lex.isInvalid() || rex.isInvalid())
5559 return QualType();
5561 if (!lex.get()->getType()->isArithmeticType() ||
5562 !rex.get()->getType()->isArithmeticType())
5563 return InvalidOperands(Loc, lex, rex);
5565 // Check for division by zero.
5566 if (isDiv &&
5567 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5568 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
5569 << rex.get()->getSourceRange());
5571 return compType;
5574 QualType Sema::CheckRemainderOperands(
5575 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
5576 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5577 if (lex.get()->getType()->hasIntegerRepresentation() &&
5578 rex.get()->getType()->hasIntegerRepresentation())
5579 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
5580 return InvalidOperands(Loc, lex, rex);
5583 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
5584 if (lex.isInvalid() || rex.isInvalid())
5585 return QualType();
5587 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
5588 return InvalidOperands(Loc, lex, rex);
5590 // Check for remainder by zero.
5591 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5592 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5593 << rex.get()->getSourceRange());
5595 return compType;
5598 QualType Sema::CheckAdditionOperands( // C99 6.5.6
5599 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
5600 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5601 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
5602 if (CompLHSTy) *CompLHSTy = compType;
5603 return compType;
5606 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
5607 if (lex.isInvalid() || rex.isInvalid())
5608 return QualType();
5610 // handle the common case first (both operands are arithmetic).
5611 if (lex.get()->getType()->isArithmeticType() &&
5612 rex.get()->getType()->isArithmeticType()) {
5613 if (CompLHSTy) *CompLHSTy = compType;
5614 return compType;
5617 // Put any potential pointer into PExp
5618 Expr* PExp = lex.get(), *IExp = rex.get();
5619 if (IExp->getType()->isAnyPointerType())
5620 std::swap(PExp, IExp);
5622 if (PExp->getType()->isAnyPointerType()) {
5624 if (IExp->getType()->isIntegerType()) {
5625 QualType PointeeTy = PExp->getType()->getPointeeType();
5627 // Check for arithmetic on pointers to incomplete types.
5628 if (PointeeTy->isVoidType()) {
5629 if (getLangOptions().CPlusPlus) {
5630 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5631 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5632 return QualType();
5635 // GNU extension: arithmetic on pointer to void
5636 Diag(Loc, diag::ext_gnu_void_ptr)
5637 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5638 } else if (PointeeTy->isFunctionType()) {
5639 if (getLangOptions().CPlusPlus) {
5640 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5641 << PExp->getType() << PExp->getSourceRange();
5642 return QualType();
5645 // GNU extension: arithmetic on pointer to function
5646 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5647 << PExp->getType() << PExp->getSourceRange();
5648 } else {
5649 // Check if we require a complete type.
5650 if (((PExp->getType()->isPointerType() &&
5651 !PExp->getType()->isDependentType()) ||
5652 PExp->getType()->isObjCObjectPointerType()) &&
5653 RequireCompleteType(Loc, PointeeTy,
5654 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5655 << PExp->getSourceRange()
5656 << PExp->getType()))
5657 return QualType();
5659 // Diagnose bad cases where we step over interface counts.
5660 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
5661 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5662 << PointeeTy << PExp->getSourceRange();
5663 return QualType();
5666 if (CompLHSTy) {
5667 QualType LHSTy = Context.isPromotableBitField(lex.get());
5668 if (LHSTy.isNull()) {
5669 LHSTy = lex.get()->getType();
5670 if (LHSTy->isPromotableIntegerType())
5671 LHSTy = Context.getPromotedIntegerType(LHSTy);
5673 *CompLHSTy = LHSTy;
5675 return PExp->getType();
5679 return InvalidOperands(Loc, lex, rex);
5682 // C99 6.5.6
5683 QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
5684 SourceLocation Loc, QualType* CompLHSTy) {
5685 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5686 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
5687 if (CompLHSTy) *CompLHSTy = compType;
5688 return compType;
5691 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
5692 if (lex.isInvalid() || rex.isInvalid())
5693 return QualType();
5695 // Enforce type constraints: C99 6.5.6p3.
5697 // Handle the common case first (both operands are arithmetic).
5698 if (lex.get()->getType()->isArithmeticType() &&
5699 rex.get()->getType()->isArithmeticType()) {
5700 if (CompLHSTy) *CompLHSTy = compType;
5701 return compType;
5704 // Either ptr - int or ptr - ptr.
5705 if (lex.get()->getType()->isAnyPointerType()) {
5706 QualType lpointee = lex.get()->getType()->getPointeeType();
5708 // The LHS must be an completely-defined object type.
5710 bool ComplainAboutVoid = false;
5711 Expr *ComplainAboutFunc = 0;
5712 if (lpointee->isVoidType()) {
5713 if (getLangOptions().CPlusPlus) {
5714 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5715 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5716 return QualType();
5719 // GNU C extension: arithmetic on pointer to void
5720 ComplainAboutVoid = true;
5721 } else if (lpointee->isFunctionType()) {
5722 if (getLangOptions().CPlusPlus) {
5723 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5724 << lex.get()->getType() << lex.get()->getSourceRange();
5725 return QualType();
5728 // GNU C extension: arithmetic on pointer to function
5729 ComplainAboutFunc = lex.get();
5730 } else if (!lpointee->isDependentType() &&
5731 RequireCompleteType(Loc, lpointee,
5732 PDiag(diag::err_typecheck_sub_ptr_object)
5733 << lex.get()->getSourceRange()
5734 << lex.get()->getType()))
5735 return QualType();
5737 // Diagnose bad cases where we step over interface counts.
5738 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
5739 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5740 << lpointee << lex.get()->getSourceRange();
5741 return QualType();
5744 // The result type of a pointer-int computation is the pointer type.
5745 if (rex.get()->getType()->isIntegerType()) {
5746 if (ComplainAboutVoid)
5747 Diag(Loc, diag::ext_gnu_void_ptr)
5748 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5749 if (ComplainAboutFunc)
5750 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5751 << ComplainAboutFunc->getType()
5752 << ComplainAboutFunc->getSourceRange();
5754 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5755 return lex.get()->getType();
5758 // Handle pointer-pointer subtractions.
5759 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
5760 QualType rpointee = RHSPTy->getPointeeType();
5762 // RHS must be a completely-type object type.
5763 // Handle the GNU void* extension.
5764 if (rpointee->isVoidType()) {
5765 if (getLangOptions().CPlusPlus) {
5766 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5767 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5768 return QualType();
5771 ComplainAboutVoid = true;
5772 } else if (rpointee->isFunctionType()) {
5773 if (getLangOptions().CPlusPlus) {
5774 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5775 << rex.get()->getType() << rex.get()->getSourceRange();
5776 return QualType();
5779 // GNU extension: arithmetic on pointer to function
5780 if (!ComplainAboutFunc)
5781 ComplainAboutFunc = rex.get();
5782 } else if (!rpointee->isDependentType() &&
5783 RequireCompleteType(Loc, rpointee,
5784 PDiag(diag::err_typecheck_sub_ptr_object)
5785 << rex.get()->getSourceRange()
5786 << rex.get()->getType()))
5787 return QualType();
5789 if (getLangOptions().CPlusPlus) {
5790 // Pointee types must be the same: C++ [expr.add]
5791 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5792 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5793 << lex.get()->getType() << rex.get()->getType()
5794 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5795 return QualType();
5797 } else {
5798 // Pointee types must be compatible C99 6.5.6p3
5799 if (!Context.typesAreCompatible(
5800 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5801 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5802 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5803 << lex.get()->getType() << rex.get()->getType()
5804 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5805 return QualType();
5809 if (ComplainAboutVoid)
5810 Diag(Loc, diag::ext_gnu_void_ptr)
5811 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5812 if (ComplainAboutFunc)
5813 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5814 << ComplainAboutFunc->getType()
5815 << ComplainAboutFunc->getSourceRange();
5817 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5818 return Context.getPointerDiffType();
5822 return InvalidOperands(Loc, lex, rex);
5825 static bool isScopedEnumerationType(QualType T) {
5826 if (const EnumType *ET = dyn_cast<EnumType>(T))
5827 return ET->getDecl()->isScoped();
5828 return false;
5831 static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
5832 SourceLocation Loc, unsigned Opc,
5833 QualType LHSTy) {
5834 llvm::APSInt Right;
5835 // Check right/shifter operand
5836 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
5837 return;
5839 if (Right.isNegative()) {
5840 S.DiagRuntimeBehavior(Loc, rex.get(),
5841 S.PDiag(diag::warn_shift_negative)
5842 << rex.get()->getSourceRange());
5843 return;
5845 llvm::APInt LeftBits(Right.getBitWidth(),
5846 S.Context.getTypeSize(lex.get()->getType()));
5847 if (Right.uge(LeftBits)) {
5848 S.DiagRuntimeBehavior(Loc, rex.get(),
5849 S.PDiag(diag::warn_shift_gt_typewidth)
5850 << rex.get()->getSourceRange());
5851 return;
5853 if (Opc != BO_Shl)
5854 return;
5856 // When left shifting an ICE which is signed, we can check for overflow which
5857 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
5858 // integers have defined behavior modulo one more than the maximum value
5859 // representable in the result type, so never warn for those.
5860 llvm::APSInt Left;
5861 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
5862 LHSTy->hasUnsignedIntegerRepresentation())
5863 return;
5864 llvm::APInt ResultBits =
5865 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
5866 if (LeftBits.uge(ResultBits))
5867 return;
5868 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
5869 Result = Result.shl(Right);
5871 // Print the bit representation of the signed integer as an unsigned
5872 // hexadecimal number.
5873 llvm::SmallString<40> HexResult;
5874 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
5876 // If we are only missing a sign bit, this is less likely to result in actual
5877 // bugs -- if the result is cast back to an unsigned type, it will have the
5878 // expected value. Thus we place this behind a different warning that can be
5879 // turned off separately if needed.
5880 if (LeftBits == ResultBits - 1) {
5881 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
5882 << HexResult.str() << LHSTy
5883 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5884 return;
5887 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
5888 << HexResult.str() << Result.getMinSignedBits() << LHSTy
5889 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5892 // C99 6.5.7
5893 QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
5894 unsigned Opc, bool isCompAssign) {
5895 // C99 6.5.7p2: Each of the operands shall have integer type.
5896 if (!lex.get()->getType()->hasIntegerRepresentation() ||
5897 !rex.get()->getType()->hasIntegerRepresentation())
5898 return InvalidOperands(Loc, lex, rex);
5900 // C++0x: Don't allow scoped enums. FIXME: Use something better than
5901 // hasIntegerRepresentation() above instead of this.
5902 if (isScopedEnumerationType(lex.get()->getType()) ||
5903 isScopedEnumerationType(rex.get()->getType())) {
5904 return InvalidOperands(Loc, lex, rex);
5907 // Vector shifts promote their scalar inputs to vector type.
5908 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
5909 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
5911 // Shifts don't perform usual arithmetic conversions, they just do integer
5912 // promotions on each operand. C99 6.5.7p3
5914 // For the LHS, do usual unary conversions, but then reset them away
5915 // if this is a compound assignment.
5916 ExprResult old_lex = lex;
5917 lex = UsualUnaryConversions(lex.take());
5918 if (lex.isInvalid())
5919 return QualType();
5920 QualType LHSTy = lex.get()->getType();
5921 if (isCompAssign) lex = old_lex;
5923 // The RHS is simpler.
5924 rex = UsualUnaryConversions(rex.take());
5925 if (rex.isInvalid())
5926 return QualType();
5928 // Sanity-check shift operands
5929 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
5931 // "The type of the result is that of the promoted left operand."
5932 return LHSTy;
5935 static bool IsWithinTemplateSpecialization(Decl *D) {
5936 if (DeclContext *DC = D->getDeclContext()) {
5937 if (isa<ClassTemplateSpecializationDecl>(DC))
5938 return true;
5939 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5940 return FD->isFunctionTemplateSpecialization();
5942 return false;
5945 // C99 6.5.8, C++ [expr.rel]
5946 QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
5947 unsigned OpaqueOpc, bool isRelational) {
5948 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
5950 // Handle vector comparisons separately.
5951 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
5952 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
5954 QualType lType = lex.get()->getType();
5955 QualType rType = rex.get()->getType();
5957 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
5958 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
5959 QualType LHSStrippedType = LHSStripped->getType();
5960 QualType RHSStrippedType = RHSStripped->getType();
5964 // Two different enums will raise a warning when compared.
5965 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
5966 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
5967 if (LHSEnumType->getDecl()->getIdentifier() &&
5968 RHSEnumType->getDecl()->getIdentifier() &&
5969 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
5970 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
5971 << LHSStrippedType << RHSStrippedType
5972 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
5977 if (!lType->hasFloatingRepresentation() &&
5978 !(lType->isBlockPointerType() && isRelational) &&
5979 !lex.get()->getLocStart().isMacroID() &&
5980 !rex.get()->getLocStart().isMacroID()) {
5981 // For non-floating point types, check for self-comparisons of the form
5982 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5983 // often indicate logic errors in the program.
5985 // NOTE: Don't warn about comparison expressions resulting from macro
5986 // expansion. Also don't warn about comparisons which are only self
5987 // comparisons within a template specialization. The warnings should catch
5988 // obvious cases in the definition of the template anyways. The idea is to
5989 // warn when the typed comparison operator will always evaluate to the same
5990 // result.
5991 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
5992 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
5993 if (DRL->getDecl() == DRR->getDecl() &&
5994 !IsWithinTemplateSpecialization(DRL->getDecl())) {
5995 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
5996 << 0 // self-
5997 << (Opc == BO_EQ
5998 || Opc == BO_LE
5999 || Opc == BO_GE));
6000 } else if (lType->isArrayType() && rType->isArrayType() &&
6001 !DRL->getDecl()->getType()->isReferenceType() &&
6002 !DRR->getDecl()->getType()->isReferenceType()) {
6003 // what is it always going to eval to?
6004 char always_evals_to;
6005 switch(Opc) {
6006 case BO_EQ: // e.g. array1 == array2
6007 always_evals_to = 0; // false
6008 break;
6009 case BO_NE: // e.g. array1 != array2
6010 always_evals_to = 1; // true
6011 break;
6012 default:
6013 // best we can say is 'a constant'
6014 always_evals_to = 2; // e.g. array1 <= array2
6015 break;
6017 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6018 << 1 // array
6019 << always_evals_to);
6024 if (isa<CastExpr>(LHSStripped))
6025 LHSStripped = LHSStripped->IgnoreParenCasts();
6026 if (isa<CastExpr>(RHSStripped))
6027 RHSStripped = RHSStripped->IgnoreParenCasts();
6029 // Warn about comparisons against a string constant (unless the other
6030 // operand is null), the user probably wants strcmp.
6031 Expr *literalString = 0;
6032 Expr *literalStringStripped = 0;
6033 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6034 !RHSStripped->isNullPointerConstant(Context,
6035 Expr::NPC_ValueDependentIsNull)) {
6036 literalString = lex.get();
6037 literalStringStripped = LHSStripped;
6038 } else if ((isa<StringLiteral>(RHSStripped) ||
6039 isa<ObjCEncodeExpr>(RHSStripped)) &&
6040 !LHSStripped->isNullPointerConstant(Context,
6041 Expr::NPC_ValueDependentIsNull)) {
6042 literalString = rex.get();
6043 literalStringStripped = RHSStripped;
6046 if (literalString) {
6047 std::string resultComparison;
6048 switch (Opc) {
6049 case BO_LT: resultComparison = ") < 0"; break;
6050 case BO_GT: resultComparison = ") > 0"; break;
6051 case BO_LE: resultComparison = ") <= 0"; break;
6052 case BO_GE: resultComparison = ") >= 0"; break;
6053 case BO_EQ: resultComparison = ") == 0"; break;
6054 case BO_NE: resultComparison = ") != 0"; break;
6055 default: assert(false && "Invalid comparison operator");
6058 DiagRuntimeBehavior(Loc, 0,
6059 PDiag(diag::warn_stringcompare)
6060 << isa<ObjCEncodeExpr>(literalStringStripped)
6061 << literalString->getSourceRange());
6065 // C99 6.5.8p3 / C99 6.5.9p4
6066 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
6067 UsualArithmeticConversions(lex, rex);
6068 if (lex.isInvalid() || rex.isInvalid())
6069 return QualType();
6071 else {
6072 lex = UsualUnaryConversions(lex.take());
6073 if (lex.isInvalid())
6074 return QualType();
6076 rex = UsualUnaryConversions(rex.take());
6077 if (rex.isInvalid())
6078 return QualType();
6081 lType = lex.get()->getType();
6082 rType = rex.get()->getType();
6084 // The result of comparisons is 'bool' in C++, 'int' in C.
6085 QualType ResultTy = Context.getLogicalOperationType();
6087 if (isRelational) {
6088 if (lType->isRealType() && rType->isRealType())
6089 return ResultTy;
6090 } else {
6091 // Check for comparisons of floating point operands using != and ==.
6092 if (lType->hasFloatingRepresentation())
6093 CheckFloatComparison(Loc, lex.get(), rex.get());
6095 if (lType->isArithmeticType() && rType->isArithmeticType())
6096 return ResultTy;
6099 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
6100 Expr::NPC_ValueDependentIsNull);
6101 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
6102 Expr::NPC_ValueDependentIsNull);
6104 // All of the following pointer-related warnings are GCC extensions, except
6105 // when handling null pointer constants.
6106 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
6107 QualType LCanPointeeTy =
6108 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
6109 QualType RCanPointeeTy =
6110 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
6112 if (getLangOptions().CPlusPlus) {
6113 if (LCanPointeeTy == RCanPointeeTy)
6114 return ResultTy;
6115 if (!isRelational &&
6116 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6117 // Valid unless comparison between non-null pointer and function pointer
6118 // This is a gcc extension compatibility comparison.
6119 // In a SFINAE context, we treat this as a hard error to maintain
6120 // conformance with the C++ standard.
6121 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6122 && !LHSIsNull && !RHSIsNull) {
6123 Diag(Loc,
6124 isSFINAEContext()?
6125 diag::err_typecheck_comparison_of_fptr_to_void
6126 : diag::ext_typecheck_comparison_of_fptr_to_void)
6127 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6129 if (isSFINAEContext())
6130 return QualType();
6132 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
6133 return ResultTy;
6137 // C++ [expr.rel]p2:
6138 // [...] Pointer conversions (4.10) and qualification
6139 // conversions (4.4) are performed on pointer operands (or on
6140 // a pointer operand and a null pointer constant) to bring
6141 // them to their composite pointer type. [...]
6143 // C++ [expr.eq]p1 uses the same notion for (in)equality
6144 // comparisons of pointers.
6145 bool NonStandardCompositeType = false;
6146 QualType T = FindCompositePointerType(Loc, lex, rex,
6147 isSFINAEContext()? 0 : &NonStandardCompositeType);
6148 if (T.isNull()) {
6149 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6150 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6151 return QualType();
6152 } else if (NonStandardCompositeType) {
6153 Diag(Loc,
6154 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6155 << lType << rType << T
6156 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6159 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6160 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
6161 return ResultTy;
6163 // C99 6.5.9p2 and C99 6.5.8p2
6164 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6165 RCanPointeeTy.getUnqualifiedType())) {
6166 // Valid unless a relational comparison of function pointers
6167 if (isRelational && LCanPointeeTy->isFunctionType()) {
6168 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6169 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6171 } else if (!isRelational &&
6172 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6173 // Valid unless comparison between non-null pointer and function pointer
6174 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6175 && !LHSIsNull && !RHSIsNull) {
6176 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6177 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6179 } else {
6180 // Invalid
6181 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6182 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6184 if (LCanPointeeTy != RCanPointeeTy) {
6185 if (LHSIsNull && !RHSIsNull)
6186 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
6187 else
6188 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
6190 return ResultTy;
6193 if (getLangOptions().CPlusPlus) {
6194 // Comparison of nullptr_t with itself.
6195 if (lType->isNullPtrType() && rType->isNullPtrType())
6196 return ResultTy;
6198 // Comparison of pointers with null pointer constants and equality
6199 // comparisons of member pointers to null pointer constants.
6200 if (RHSIsNull &&
6201 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
6202 (!isRelational &&
6203 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
6204 rex = ImpCastExprToType(rex.take(), lType,
6205 lType->isMemberPointerType()
6206 ? CK_NullToMemberPointer
6207 : CK_NullToPointer);
6208 return ResultTy;
6210 if (LHSIsNull &&
6211 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
6212 (!isRelational &&
6213 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
6214 lex = ImpCastExprToType(lex.take(), rType,
6215 rType->isMemberPointerType()
6216 ? CK_NullToMemberPointer
6217 : CK_NullToPointer);
6218 return ResultTy;
6221 // Comparison of member pointers.
6222 if (!isRelational &&
6223 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6224 // C++ [expr.eq]p2:
6225 // In addition, pointers to members can be compared, or a pointer to
6226 // member and a null pointer constant. Pointer to member conversions
6227 // (4.11) and qualification conversions (4.4) are performed to bring
6228 // them to a common type. If one operand is a null pointer constant,
6229 // the common type is the type of the other operand. Otherwise, the
6230 // common type is a pointer to member type similar (4.4) to the type
6231 // of one of the operands, with a cv-qualification signature (4.4)
6232 // that is the union of the cv-qualification signatures of the operand
6233 // types.
6234 bool NonStandardCompositeType = false;
6235 QualType T = FindCompositePointerType(Loc, lex, rex,
6236 isSFINAEContext()? 0 : &NonStandardCompositeType);
6237 if (T.isNull()) {
6238 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6239 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6240 return QualType();
6241 } else if (NonStandardCompositeType) {
6242 Diag(Loc,
6243 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6244 << lType << rType << T
6245 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6248 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6249 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
6250 return ResultTy;
6253 // Handle scoped enumeration types specifically, since they don't promote
6254 // to integers.
6255 if (lex.get()->getType()->isEnumeralType() &&
6256 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
6257 return ResultTy;
6260 // Handle block pointer types.
6261 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
6262 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6263 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
6265 if (!LHSIsNull && !RHSIsNull &&
6266 !Context.typesAreCompatible(lpointee, rpointee)) {
6267 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6268 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6270 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
6271 return ResultTy;
6274 // Allow block pointers to be compared with null pointer constants.
6275 if (!isRelational
6276 && ((lType->isBlockPointerType() && rType->isPointerType())
6277 || (lType->isPointerType() && rType->isBlockPointerType()))) {
6278 if (!LHSIsNull && !RHSIsNull) {
6279 if (!((rType->isPointerType() && rType->castAs<PointerType>()
6280 ->getPointeeType()->isVoidType())
6281 || (lType->isPointerType() && lType->castAs<PointerType>()
6282 ->getPointeeType()->isVoidType())))
6283 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6284 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6286 if (LHSIsNull && !RHSIsNull)
6287 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
6288 else
6289 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
6290 return ResultTy;
6293 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6294 const PointerType *LPT = lType->getAs<PointerType>();
6295 const PointerType *RPT = rType->getAs<PointerType>();
6296 if (LPT || RPT) {
6297 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6298 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
6300 if (!LPtrToVoid && !RPtrToVoid &&
6301 !Context.typesAreCompatible(lType, rType)) {
6302 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6303 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6305 if (LHSIsNull && !RHSIsNull)
6306 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
6307 else
6308 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
6309 return ResultTy;
6311 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
6312 if (!Context.areComparableObjCPointerTypes(lType, rType))
6313 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6314 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6315 if (LHSIsNull && !RHSIsNull)
6316 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
6317 else
6318 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
6319 return ResultTy;
6322 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6323 (lType->isIntegerType() && rType->isAnyPointerType())) {
6324 unsigned DiagID = 0;
6325 bool isError = false;
6326 if ((LHSIsNull && lType->isIntegerType()) ||
6327 (RHSIsNull && rType->isIntegerType())) {
6328 if (isRelational && !getLangOptions().CPlusPlus)
6329 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
6330 } else if (isRelational && !getLangOptions().CPlusPlus)
6331 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
6332 else if (getLangOptions().CPlusPlus) {
6333 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6334 isError = true;
6335 } else
6336 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
6338 if (DiagID) {
6339 Diag(Loc, DiagID)
6340 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6341 if (isError)
6342 return QualType();
6345 if (lType->isIntegerType())
6346 lex = ImpCastExprToType(lex.take(), rType,
6347 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6348 else
6349 rex = ImpCastExprToType(rex.take(), lType,
6350 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6351 return ResultTy;
6354 // Handle block pointers.
6355 if (!isRelational && RHSIsNull
6356 && lType->isBlockPointerType() && rType->isIntegerType()) {
6357 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
6358 return ResultTy;
6360 if (!isRelational && LHSIsNull
6361 && lType->isIntegerType() && rType->isBlockPointerType()) {
6362 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
6363 return ResultTy;
6366 return InvalidOperands(Loc, lex, rex);
6369 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
6370 /// operates on extended vector types. Instead of producing an IntTy result,
6371 /// like a scalar comparison, a vector comparison produces a vector of integer
6372 /// types.
6373 QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
6374 SourceLocation Loc,
6375 bool isRelational) {
6376 // Check to make sure we're operating on vectors of the same type and width,
6377 // Allowing one side to be a scalar of element type.
6378 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
6379 if (vType.isNull())
6380 return vType;
6382 QualType lType = lex.get()->getType();
6383 QualType rType = rex.get()->getType();
6385 // If AltiVec, the comparison results in a numeric type, i.e.
6386 // bool for C++, int for C
6387 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
6388 return Context.getLogicalOperationType();
6390 // For non-floating point types, check for self-comparisons of the form
6391 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6392 // often indicate logic errors in the program.
6393 if (!lType->hasFloatingRepresentation()) {
6394 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6395 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
6396 if (DRL->getDecl() == DRR->getDecl())
6397 DiagRuntimeBehavior(Loc, 0,
6398 PDiag(diag::warn_comparison_always)
6399 << 0 // self-
6400 << 2 // "a constant"
6404 // Check for comparisons of floating point operands using != and ==.
6405 if (!isRelational && lType->hasFloatingRepresentation()) {
6406 assert (rType->hasFloatingRepresentation());
6407 CheckFloatComparison(Loc, lex.get(), rex.get());
6410 // Return the type for the comparison, which is the same as vector type for
6411 // integer vectors, or an integer type of identical size and number of
6412 // elements for floating point vectors.
6413 if (lType->hasIntegerRepresentation())
6414 return lType;
6416 const VectorType *VTy = lType->getAs<VectorType>();
6417 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6418 if (TypeSize == Context.getTypeSize(Context.IntTy))
6419 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6420 if (TypeSize == Context.getTypeSize(Context.LongTy))
6421 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6423 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6424 "Unhandled vector element size in vector compare");
6425 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6428 inline QualType Sema::CheckBitwiseOperands(
6429 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6430 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6431 if (lex.get()->getType()->hasIntegerRepresentation() &&
6432 rex.get()->getType()->hasIntegerRepresentation())
6433 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
6435 return InvalidOperands(Loc, lex, rex);
6438 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
6439 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
6440 if (lexResult.isInvalid() || rexResult.isInvalid())
6441 return QualType();
6442 lex = lexResult.take();
6443 rex = rexResult.take();
6445 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6446 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
6447 return compType;
6448 return InvalidOperands(Loc, lex, rex);
6451 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
6452 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
6454 // Diagnose cases where the user write a logical and/or but probably meant a
6455 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6456 // is a constant.
6457 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
6458 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
6459 // Don't warn in macros.
6460 !Loc.isMacroID()) {
6461 // If the RHS can be constant folded, and if it constant folds to something
6462 // that isn't 0 or 1 (which indicate a potential logical operation that
6463 // happened to fold to true/false) then warn.
6464 // Parens on the RHS are ignored.
6465 Expr::EvalResult Result;
6466 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6467 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6468 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6469 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6470 << rex.get()->getSourceRange()
6471 << (Opc == BO_LAnd ? "&&" : "||")
6472 << (Opc == BO_LAnd ? "&" : "|");
6476 if (!Context.getLangOptions().CPlusPlus) {
6477 lex = UsualUnaryConversions(lex.take());
6478 if (lex.isInvalid())
6479 return QualType();
6481 rex = UsualUnaryConversions(rex.take());
6482 if (rex.isInvalid())
6483 return QualType();
6485 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
6486 return InvalidOperands(Loc, lex, rex);
6488 return Context.IntTy;
6491 // The following is safe because we only use this method for
6492 // non-overloadable operands.
6494 // C++ [expr.log.and]p1
6495 // C++ [expr.log.or]p1
6496 // The operands are both contextually converted to type bool.
6497 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6498 if (lexRes.isInvalid())
6499 return InvalidOperands(Loc, lex, rex);
6500 lex = move(lexRes);
6502 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6503 if (rexRes.isInvalid())
6504 return InvalidOperands(Loc, lex, rex);
6505 rex = move(rexRes);
6507 // C++ [expr.log.and]p2
6508 // C++ [expr.log.or]p2
6509 // The result is a bool.
6510 return Context.BoolTy;
6513 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6514 /// is a read-only property; return true if so. A readonly property expression
6515 /// depends on various declarations and thus must be treated specially.
6517 static bool IsReadonlyProperty(Expr *E, Sema &S) {
6518 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6519 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6520 if (PropExpr->isImplicitProperty()) return false;
6522 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6523 QualType BaseType = PropExpr->isSuperReceiver() ?
6524 PropExpr->getSuperReceiverType() :
6525 PropExpr->getBase()->getType();
6527 if (const ObjCObjectPointerType *OPT =
6528 BaseType->getAsObjCInterfacePointerType())
6529 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6530 if (S.isPropertyReadonly(PDecl, IFace))
6531 return true;
6533 return false;
6536 static bool IsConstProperty(Expr *E, Sema &S) {
6537 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6538 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6539 if (PropExpr->isImplicitProperty()) return false;
6541 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6542 QualType T = PDecl->getType();
6543 if (T->isReferenceType())
6544 T = T->getAs<ReferenceType>()->getPointeeType();
6545 CanQualType CT = S.Context.getCanonicalType(T);
6546 return CT.isConstQualified();
6548 return false;
6551 static bool IsReadonlyMessage(Expr *E, Sema &S) {
6552 if (E->getStmtClass() != Expr::MemberExprClass)
6553 return false;
6554 const MemberExpr *ME = cast<MemberExpr>(E);
6555 NamedDecl *Member = ME->getMemberDecl();
6556 if (isa<FieldDecl>(Member)) {
6557 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6558 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6559 return false;
6560 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6562 return false;
6565 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6566 /// emit an error and return true. If so, return false.
6567 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
6568 SourceLocation OrigLoc = Loc;
6569 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
6570 &Loc);
6571 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6572 IsLV = Expr::MLV_ReadonlyProperty;
6573 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6574 IsLV = Expr::MLV_Valid;
6575 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6576 IsLV = Expr::MLV_InvalidMessageExpression;
6577 if (IsLV == Expr::MLV_Valid)
6578 return false;
6580 unsigned Diag = 0;
6581 bool NeedType = false;
6582 switch (IsLV) { // C99 6.5.16p2
6583 case Expr::MLV_ConstQualified:
6584 Diag = diag::err_typecheck_assign_const;
6586 // In ARC, use some specialized diagnostics for occasions where we
6587 // infer 'const'. These are always pseudo-strong variables.
6588 if (S.getLangOptions().ObjCAutoRefCount) {
6589 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6590 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6591 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6593 // Use the normal diagnostic if it's pseudo-__strong but the
6594 // user actually wrote 'const'.
6595 if (var->isARCPseudoStrong() &&
6596 (!var->getTypeSourceInfo() ||
6597 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6598 // There are two pseudo-strong cases:
6599 // - self
6600 ObjCMethodDecl *method = S.getCurMethodDecl();
6601 if (method && var == method->getSelfDecl())
6602 Diag = diag::err_typecheck_arr_assign_self;
6604 // - fast enumeration variables
6605 else
6606 Diag = diag::err_typecheck_arr_assign_enumeration;
6608 SourceRange Assign;
6609 if (Loc != OrigLoc)
6610 Assign = SourceRange(OrigLoc, OrigLoc);
6611 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6612 // We need to preserve the AST regardless, so migration tool
6613 // can do its job.
6614 return false;
6619 break;
6620 case Expr::MLV_ArrayType:
6621 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6622 NeedType = true;
6623 break;
6624 case Expr::MLV_NotObjectType:
6625 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6626 NeedType = true;
6627 break;
6628 case Expr::MLV_LValueCast:
6629 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6630 break;
6631 case Expr::MLV_Valid:
6632 llvm_unreachable("did not take early return for MLV_Valid");
6633 case Expr::MLV_InvalidExpression:
6634 case Expr::MLV_MemberFunction:
6635 case Expr::MLV_ClassTemporary:
6636 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6637 break;
6638 case Expr::MLV_IncompleteType:
6639 case Expr::MLV_IncompleteVoidType:
6640 return S.RequireCompleteType(Loc, E->getType(),
6641 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
6642 << E->getSourceRange());
6643 case Expr::MLV_DuplicateVectorComponents:
6644 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6645 break;
6646 case Expr::MLV_NotBlockQualified:
6647 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6648 break;
6649 case Expr::MLV_ReadonlyProperty:
6650 Diag = diag::error_readonly_property_assignment;
6651 break;
6652 case Expr::MLV_NoSetterProperty:
6653 Diag = diag::error_nosetter_property_assignment;
6654 break;
6655 case Expr::MLV_InvalidMessageExpression:
6656 Diag = diag::error_readonly_message_assignment;
6657 break;
6658 case Expr::MLV_SubObjCPropertySetting:
6659 Diag = diag::error_no_subobject_property_setting;
6660 break;
6663 SourceRange Assign;
6664 if (Loc != OrigLoc)
6665 Assign = SourceRange(OrigLoc, OrigLoc);
6666 if (NeedType)
6667 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
6668 else
6669 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6670 return true;
6675 // C99 6.5.16.1
6676 QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
6677 SourceLocation Loc,
6678 QualType CompoundType) {
6679 // Verify that LHS is a modifiable lvalue, and emit error if not.
6680 if (CheckForModifiableLvalue(LHS, Loc, *this))
6681 return QualType();
6683 QualType LHSType = LHS->getType();
6684 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
6685 AssignConvertType ConvTy;
6686 if (CompoundType.isNull()) {
6687 QualType LHSTy(LHSType);
6688 // Simple assignment "x = y".
6689 if (LHS->getObjectKind() == OK_ObjCProperty) {
6690 ExprResult LHSResult = Owned(LHS);
6691 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6692 if (LHSResult.isInvalid())
6693 return QualType();
6694 LHS = LHSResult.take();
6696 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
6697 if (RHS.isInvalid())
6698 return QualType();
6699 // Special case of NSObject attributes on c-style pointer types.
6700 if (ConvTy == IncompatiblePointer &&
6701 ((Context.isObjCNSObjectType(LHSType) &&
6702 RHSType->isObjCObjectPointerType()) ||
6703 (Context.isObjCNSObjectType(RHSType) &&
6704 LHSType->isObjCObjectPointerType())))
6705 ConvTy = Compatible;
6707 if (ConvTy == Compatible &&
6708 getLangOptions().ObjCNonFragileABI &&
6709 LHSType->isObjCObjectType())
6710 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6711 << LHSType;
6713 // If the RHS is a unary plus or minus, check to see if they = and + are
6714 // right next to each other. If so, the user may have typo'd "x =+ 4"
6715 // instead of "x += 4".
6716 Expr *RHSCheck = RHS.get();
6717 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6718 RHSCheck = ICE->getSubExpr();
6719 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
6720 if ((UO->getOpcode() == UO_Plus ||
6721 UO->getOpcode() == UO_Minus) &&
6722 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
6723 // Only if the two operators are exactly adjacent.
6724 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6725 // And there is a space or other character before the subexpr of the
6726 // unary +/-. We don't want to warn on "x=-1".
6727 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6728 UO->getSubExpr()->getLocStart().isFileID()) {
6729 Diag(Loc, diag::warn_not_compound_assign)
6730 << (UO->getOpcode() == UO_Plus ? "+" : "-")
6731 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
6735 if (ConvTy == Compatible) {
6736 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6737 checkRetainCycles(LHS, RHS.get());
6738 else
6739 checkUnsafeAssigns(Loc, LHSType, RHS.get());
6741 } else {
6742 // Compound assignment "x += y"
6743 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
6746 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
6747 RHS.get(), AA_Assigning))
6748 return QualType();
6750 CheckForNullPointerDereference(*this, LHS);
6751 // Check for trivial buffer overflows.
6752 CheckArrayAccess(LHS->IgnoreParenCasts());
6754 // C99 6.5.16p3: The type of an assignment expression is the type of the
6755 // left operand unless the left operand has qualified type, in which case
6756 // it is the unqualified version of the type of the left operand.
6757 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6758 // is converted to the type of the assignment expression (above).
6759 // C++ 5.17p1: the type of the assignment expression is that of its left
6760 // operand.
6761 return (getLangOptions().CPlusPlus
6762 ? LHSType : LHSType.getUnqualifiedType());
6765 // C99 6.5.17
6766 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
6767 SourceLocation Loc) {
6768 S.DiagnoseUnusedExprResult(LHS.get());
6770 LHS = S.CheckPlaceholderExpr(LHS.take());
6771 RHS = S.CheckPlaceholderExpr(RHS.take());
6772 if (LHS.isInvalid() || RHS.isInvalid())
6773 return QualType();
6775 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6776 // operands, but not unary promotions.
6777 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
6779 // So we treat the LHS as a ignored value, and in C++ we allow the
6780 // containing site to determine what should be done with the RHS.
6781 LHS = S.IgnoredValueConversions(LHS.take());
6782 if (LHS.isInvalid())
6783 return QualType();
6785 if (!S.getLangOptions().CPlusPlus) {
6786 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
6787 if (RHS.isInvalid())
6788 return QualType();
6789 if (!RHS.get()->getType()->isVoidType())
6790 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
6793 return RHS.get()->getType();
6796 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6797 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
6798 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6799 ExprValueKind &VK,
6800 SourceLocation OpLoc,
6801 bool isInc, bool isPrefix) {
6802 if (Op->isTypeDependent())
6803 return S.Context.DependentTy;
6805 QualType ResType = Op->getType();
6806 assert(!ResType.isNull() && "no type for increment/decrement expression");
6808 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
6809 // Decrement of bool is not allowed.
6810 if (!isInc) {
6811 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
6812 return QualType();
6814 // Increment of bool sets it to true, but is deprecated.
6815 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
6816 } else if (ResType->isRealType()) {
6817 // OK!
6818 } else if (ResType->isAnyPointerType()) {
6819 QualType PointeeTy = ResType->getPointeeType();
6821 // C99 6.5.2.4p2, 6.5.6p2
6822 if (PointeeTy->isVoidType()) {
6823 if (S.getLangOptions().CPlusPlus) {
6824 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
6825 << Op->getSourceRange();
6826 return QualType();
6829 // Pointer to void is a GNU extension in C.
6830 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
6831 } else if (PointeeTy->isFunctionType()) {
6832 if (S.getLangOptions().CPlusPlus) {
6833 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
6834 << Op->getType() << Op->getSourceRange();
6835 return QualType();
6838 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
6839 << ResType << Op->getSourceRange();
6840 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
6841 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6842 << Op->getSourceRange()
6843 << ResType))
6844 return QualType();
6845 // Diagnose bad cases where we step over interface counts.
6846 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6847 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6848 << PointeeTy << Op->getSourceRange();
6849 return QualType();
6851 } else if (ResType->isAnyComplexType()) {
6852 // C99 does not support ++/-- on complex types, we allow as an extension.
6853 S.Diag(OpLoc, diag::ext_integer_increment_complex)
6854 << ResType << Op->getSourceRange();
6855 } else if (ResType->isPlaceholderType()) {
6856 ExprResult PR = S.CheckPlaceholderExpr(Op);
6857 if (PR.isInvalid()) return QualType();
6858 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6859 isInc, isPrefix);
6860 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
6861 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
6862 } else {
6863 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
6864 << ResType << int(isInc) << Op->getSourceRange();
6865 return QualType();
6867 // At this point, we know we have a real, complex or pointer type.
6868 // Now make sure the operand is a modifiable lvalue.
6869 if (CheckForModifiableLvalue(Op, OpLoc, S))
6870 return QualType();
6871 // In C++, a prefix increment is the same type as the operand. Otherwise
6872 // (in C or with postfix), the increment is the unqualified type of the
6873 // operand.
6874 if (isPrefix && S.getLangOptions().CPlusPlus) {
6875 VK = VK_LValue;
6876 return ResType;
6877 } else {
6878 VK = VK_RValue;
6879 return ResType.getUnqualifiedType();
6883 ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
6884 assert(E->getValueKind() == VK_LValue &&
6885 E->getObjectKind() == OK_ObjCProperty);
6886 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
6888 QualType T = E->getType();
6889 QualType ReceiverType;
6890 if (PRE->isObjectReceiver())
6891 ReceiverType = PRE->getBase()->getType();
6892 else if (PRE->isSuperReceiver())
6893 ReceiverType = PRE->getSuperReceiverType();
6894 else
6895 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
6897 ExprValueKind VK = VK_RValue;
6898 if (PRE->isImplicitProperty()) {
6899 if (ObjCMethodDecl *GetterMethod =
6900 PRE->getImplicitPropertyGetter()) {
6901 T = getMessageSendResultType(ReceiverType, GetterMethod,
6902 PRE->isClassReceiver(),
6903 PRE->isSuperReceiver());
6904 VK = Expr::getValueKindForType(GetterMethod->getResultType());
6906 else {
6907 Diag(PRE->getLocation(), diag::err_getter_not_found)
6908 << PRE->getBase()->getType();
6912 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
6913 E, 0, VK);
6915 ExprResult Result = MaybeBindToTemporary(E);
6916 if (!Result.isInvalid())
6917 E = Result.take();
6919 return Owned(E);
6922 void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
6923 assert(LHS.get()->getValueKind() == VK_LValue &&
6924 LHS.get()->getObjectKind() == OK_ObjCProperty);
6925 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
6927 bool Consumed = false;
6929 if (PropRef->isImplicitProperty()) {
6930 // If using property-dot syntax notation for assignment, and there is a
6931 // setter, RHS expression is being passed to the setter argument. So,
6932 // type conversion (and comparison) is RHS to setter's argument type.
6933 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
6934 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
6935 LHSTy = (*P)->getType();
6936 Consumed = (getLangOptions().ObjCAutoRefCount &&
6937 (*P)->hasAttr<NSConsumedAttr>());
6939 // Otherwise, if the getter returns an l-value, just call that.
6940 } else {
6941 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
6942 ExprValueKind VK = Expr::getValueKindForType(Result);
6943 if (VK == VK_LValue) {
6944 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
6945 CK_GetObjCProperty, LHS.take(), 0, VK);
6946 return;
6949 } else if (getLangOptions().ObjCAutoRefCount) {
6950 const ObjCMethodDecl *setter
6951 = PropRef->getExplicitProperty()->getSetterMethodDecl();
6952 if (setter) {
6953 ObjCMethodDecl::param_iterator P = setter->param_begin();
6954 LHSTy = (*P)->getType();
6955 Consumed = (*P)->hasAttr<NSConsumedAttr>();
6959 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
6960 getLangOptions().ObjCAutoRefCount) {
6961 InitializedEntity Entity =
6962 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
6963 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
6964 if (!ArgE.isInvalid()) {
6965 RHS = ArgE;
6966 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
6967 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
6973 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
6974 /// This routine allows us to typecheck complex/recursive expressions
6975 /// where the declaration is needed for type checking. We only need to
6976 /// handle cases when the expression references a function designator
6977 /// or is an lvalue. Here are some examples:
6978 /// - &(x) => x
6979 /// - &*****f => f for f a function designator.
6980 /// - &s.xx => s
6981 /// - &s.zz[1].yy -> s, if zz is an array
6982 /// - *(x + 1) -> x, if x is an array
6983 /// - &"123"[2] -> 0
6984 /// - & __real__ x -> x
6985 static ValueDecl *getPrimaryDecl(Expr *E) {
6986 switch (E->getStmtClass()) {
6987 case Stmt::DeclRefExprClass:
6988 return cast<DeclRefExpr>(E)->getDecl();
6989 case Stmt::MemberExprClass:
6990 // If this is an arrow operator, the address is an offset from
6991 // the base's value, so the object the base refers to is
6992 // irrelevant.
6993 if (cast<MemberExpr>(E)->isArrow())
6994 return 0;
6995 // Otherwise, the expression refers to a part of the base
6996 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
6997 case Stmt::ArraySubscriptExprClass: {
6998 // FIXME: This code shouldn't be necessary! We should catch the implicit
6999 // promotion of register arrays earlier.
7000 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7001 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7002 if (ICE->getSubExpr()->getType()->isArrayType())
7003 return getPrimaryDecl(ICE->getSubExpr());
7005 return 0;
7007 case Stmt::UnaryOperatorClass: {
7008 UnaryOperator *UO = cast<UnaryOperator>(E);
7010 switch(UO->getOpcode()) {
7011 case UO_Real:
7012 case UO_Imag:
7013 case UO_Extension:
7014 return getPrimaryDecl(UO->getSubExpr());
7015 default:
7016 return 0;
7019 case Stmt::ParenExprClass:
7020 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7021 case Stmt::ImplicitCastExprClass:
7022 // If the result of an implicit cast is an l-value, we care about
7023 // the sub-expression; otherwise, the result here doesn't matter.
7024 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7025 default:
7026 return 0;
7030 /// CheckAddressOfOperand - The operand of & must be either a function
7031 /// designator or an lvalue designating an object. If it is an lvalue, the
7032 /// object cannot be declared with storage class register or be a bit field.
7033 /// Note: The usual conversions are *not* applied to the operand of the &
7034 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7035 /// In C++, the operand might be an overloaded function name, in which case
7036 /// we allow the '&' but retain the overloaded-function type.
7037 static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7038 SourceLocation OpLoc) {
7039 if (OrigOp->isTypeDependent())
7040 return S.Context.DependentTy;
7041 if (OrigOp->getType() == S.Context.OverloadTy)
7042 return S.Context.OverloadTy;
7043 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7044 return S.Context.UnknownAnyTy;
7045 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7046 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7047 << OrigOp->getSourceRange();
7048 return QualType();
7051 assert(!OrigOp->getType()->isPlaceholderType());
7053 // Make sure to ignore parentheses in subsequent checks
7054 Expr *op = OrigOp->IgnoreParens();
7056 if (S.getLangOptions().C99) {
7057 // Implement C99-only parts of addressof rules.
7058 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7059 if (uOp->getOpcode() == UO_Deref)
7060 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7061 // (assuming the deref expression is valid).
7062 return uOp->getSubExpr()->getType();
7064 // Technically, there should be a check for array subscript
7065 // expressions here, but the result of one is always an lvalue anyway.
7067 ValueDecl *dcl = getPrimaryDecl(op);
7068 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7070 if (lval == Expr::LV_ClassTemporary) {
7071 bool sfinae = S.isSFINAEContext();
7072 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7073 : diag::ext_typecheck_addrof_class_temporary)
7074 << op->getType() << op->getSourceRange();
7075 if (sfinae)
7076 return QualType();
7077 } else if (isa<ObjCSelectorExpr>(op)) {
7078 return S.Context.getPointerType(op->getType());
7079 } else if (lval == Expr::LV_MemberFunction) {
7080 // If it's an instance method, make a member pointer.
7081 // The expression must have exactly the form &A::foo.
7083 // If the underlying expression isn't a decl ref, give up.
7084 if (!isa<DeclRefExpr>(op)) {
7085 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7086 << OrigOp->getSourceRange();
7087 return QualType();
7089 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7090 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7092 // The id-expression was parenthesized.
7093 if (OrigOp != DRE) {
7094 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7095 << OrigOp->getSourceRange();
7097 // The method was named without a qualifier.
7098 } else if (!DRE->getQualifier()) {
7099 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7100 << op->getSourceRange();
7103 return S.Context.getMemberPointerType(op->getType(),
7104 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7105 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7106 // C99 6.5.3.2p1
7107 // The operand must be either an l-value or a function designator
7108 if (!op->getType()->isFunctionType()) {
7109 // FIXME: emit more specific diag...
7110 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7111 << op->getSourceRange();
7112 return QualType();
7114 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7115 // The operand cannot be a bit-field
7116 S.Diag(OpLoc, diag::err_typecheck_address_of)
7117 << "bit-field" << op->getSourceRange();
7118 return QualType();
7119 } else if (op->getObjectKind() == OK_VectorComponent) {
7120 // The operand cannot be an element of a vector
7121 S.Diag(OpLoc, diag::err_typecheck_address_of)
7122 << "vector element" << op->getSourceRange();
7123 return QualType();
7124 } else if (op->getObjectKind() == OK_ObjCProperty) {
7125 // cannot take address of a property expression.
7126 S.Diag(OpLoc, diag::err_typecheck_address_of)
7127 << "property expression" << op->getSourceRange();
7128 return QualType();
7129 } else if (dcl) { // C99 6.5.3.2p1
7130 // We have an lvalue with a decl. Make sure the decl is not declared
7131 // with the register storage-class specifier.
7132 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7133 // in C++ it is not error to take address of a register
7134 // variable (c++03 7.1.1P3)
7135 if (vd->getStorageClass() == SC_Register &&
7136 !S.getLangOptions().CPlusPlus) {
7137 S.Diag(OpLoc, diag::err_typecheck_address_of)
7138 << "register variable" << op->getSourceRange();
7139 return QualType();
7141 } else if (isa<FunctionTemplateDecl>(dcl)) {
7142 return S.Context.OverloadTy;
7143 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
7144 // Okay: we can take the address of a field.
7145 // Could be a pointer to member, though, if there is an explicit
7146 // scope qualifier for the class.
7147 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
7148 DeclContext *Ctx = dcl->getDeclContext();
7149 if (Ctx && Ctx->isRecord()) {
7150 if (dcl->getType()->isReferenceType()) {
7151 S.Diag(OpLoc,
7152 diag::err_cannot_form_pointer_to_member_of_reference_type)
7153 << dcl->getDeclName() << dcl->getType();
7154 return QualType();
7157 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7158 Ctx = Ctx->getParent();
7159 return S.Context.getMemberPointerType(op->getType(),
7160 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
7163 } else if (!isa<FunctionDecl>(dcl))
7164 assert(0 && "Unknown/unexpected decl type");
7167 if (lval == Expr::LV_IncompleteVoidType) {
7168 // Taking the address of a void variable is technically illegal, but we
7169 // allow it in cases which are otherwise valid.
7170 // Example: "extern void x; void* y = &x;".
7171 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
7174 // If the operand has type "type", the result has type "pointer to type".
7175 if (op->getType()->isObjCObjectType())
7176 return S.Context.getObjCObjectPointerType(op->getType());
7177 return S.Context.getPointerType(op->getType());
7180 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7181 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7182 SourceLocation OpLoc) {
7183 if (Op->isTypeDependent())
7184 return S.Context.DependentTy;
7186 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7187 if (ConvResult.isInvalid())
7188 return QualType();
7189 Op = ConvResult.take();
7190 QualType OpTy = Op->getType();
7191 QualType Result;
7193 if (isa<CXXReinterpretCastExpr>(Op)) {
7194 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7195 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7196 Op->getSourceRange());
7199 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7200 // is an incomplete type or void. It would be possible to warn about
7201 // dereferencing a void pointer, but it's completely well-defined, and such a
7202 // warning is unlikely to catch any mistakes.
7203 if (const PointerType *PT = OpTy->getAs<PointerType>())
7204 Result = PT->getPointeeType();
7205 else if (const ObjCObjectPointerType *OPT =
7206 OpTy->getAs<ObjCObjectPointerType>())
7207 Result = OPT->getPointeeType();
7208 else {
7209 ExprResult PR = S.CheckPlaceholderExpr(Op);
7210 if (PR.isInvalid()) return QualType();
7211 if (PR.take() != Op)
7212 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
7215 if (Result.isNull()) {
7216 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
7217 << OpTy << Op->getSourceRange();
7218 return QualType();
7221 // Dereferences are usually l-values...
7222 VK = VK_LValue;
7224 // ...except that certain expressions are never l-values in C.
7225 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
7226 VK = VK_RValue;
7228 return Result;
7231 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
7232 tok::TokenKind Kind) {
7233 BinaryOperatorKind Opc;
7234 switch (Kind) {
7235 default: assert(0 && "Unknown binop!");
7236 case tok::periodstar: Opc = BO_PtrMemD; break;
7237 case tok::arrowstar: Opc = BO_PtrMemI; break;
7238 case tok::star: Opc = BO_Mul; break;
7239 case tok::slash: Opc = BO_Div; break;
7240 case tok::percent: Opc = BO_Rem; break;
7241 case tok::plus: Opc = BO_Add; break;
7242 case tok::minus: Opc = BO_Sub; break;
7243 case tok::lessless: Opc = BO_Shl; break;
7244 case tok::greatergreater: Opc = BO_Shr; break;
7245 case tok::lessequal: Opc = BO_LE; break;
7246 case tok::less: Opc = BO_LT; break;
7247 case tok::greaterequal: Opc = BO_GE; break;
7248 case tok::greater: Opc = BO_GT; break;
7249 case tok::exclaimequal: Opc = BO_NE; break;
7250 case tok::equalequal: Opc = BO_EQ; break;
7251 case tok::amp: Opc = BO_And; break;
7252 case tok::caret: Opc = BO_Xor; break;
7253 case tok::pipe: Opc = BO_Or; break;
7254 case tok::ampamp: Opc = BO_LAnd; break;
7255 case tok::pipepipe: Opc = BO_LOr; break;
7256 case tok::equal: Opc = BO_Assign; break;
7257 case tok::starequal: Opc = BO_MulAssign; break;
7258 case tok::slashequal: Opc = BO_DivAssign; break;
7259 case tok::percentequal: Opc = BO_RemAssign; break;
7260 case tok::plusequal: Opc = BO_AddAssign; break;
7261 case tok::minusequal: Opc = BO_SubAssign; break;
7262 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7263 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7264 case tok::ampequal: Opc = BO_AndAssign; break;
7265 case tok::caretequal: Opc = BO_XorAssign; break;
7266 case tok::pipeequal: Opc = BO_OrAssign; break;
7267 case tok::comma: Opc = BO_Comma; break;
7269 return Opc;
7272 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
7273 tok::TokenKind Kind) {
7274 UnaryOperatorKind Opc;
7275 switch (Kind) {
7276 default: assert(0 && "Unknown unary op!");
7277 case tok::plusplus: Opc = UO_PreInc; break;
7278 case tok::minusminus: Opc = UO_PreDec; break;
7279 case tok::amp: Opc = UO_AddrOf; break;
7280 case tok::star: Opc = UO_Deref; break;
7281 case tok::plus: Opc = UO_Plus; break;
7282 case tok::minus: Opc = UO_Minus; break;
7283 case tok::tilde: Opc = UO_Not; break;
7284 case tok::exclaim: Opc = UO_LNot; break;
7285 case tok::kw___real: Opc = UO_Real; break;
7286 case tok::kw___imag: Opc = UO_Imag; break;
7287 case tok::kw___extension__: Opc = UO_Extension; break;
7289 return Opc;
7292 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7293 /// This warning is only emitted for builtin assignment operations. It is also
7294 /// suppressed in the event of macro expansions.
7295 static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7296 SourceLocation OpLoc) {
7297 if (!S.ActiveTemplateInstantiations.empty())
7298 return;
7299 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7300 return;
7301 lhs = lhs->IgnoreParenImpCasts();
7302 rhs = rhs->IgnoreParenImpCasts();
7303 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7304 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7305 if (!LeftDeclRef || !RightDeclRef ||
7306 LeftDeclRef->getLocation().isMacroID() ||
7307 RightDeclRef->getLocation().isMacroID())
7308 return;
7309 const ValueDecl *LeftDecl =
7310 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7311 const ValueDecl *RightDecl =
7312 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7313 if (LeftDecl != RightDecl)
7314 return;
7315 if (LeftDecl->getType().isVolatileQualified())
7316 return;
7317 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7318 if (RefTy->getPointeeType().isVolatileQualified())
7319 return;
7321 S.Diag(OpLoc, diag::warn_self_assignment)
7322 << LeftDeclRef->getType()
7323 << lhs->getSourceRange() << rhs->getSourceRange();
7326 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7327 /// operator @p Opc at location @c TokLoc. This routine only supports
7328 /// built-in operations; ActOnBinOp handles overloaded operators.
7329 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
7330 BinaryOperatorKind Opc,
7331 Expr *lhsExpr, Expr *rhsExpr) {
7332 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
7333 QualType ResultTy; // Result type of the binary operator.
7334 // The following two variables are used for compound assignment operators
7335 QualType CompLHSTy; // Type of LHS after promotions for computation
7336 QualType CompResultTy; // Type of computation result
7337 ExprValueKind VK = VK_RValue;
7338 ExprObjectKind OK = OK_Ordinary;
7340 // Check if a 'foo<int>' involved in a binary op, identifies a single
7341 // function unambiguously (i.e. an lvalue ala 13.4)
7342 // But since an assignment can trigger target based overload, exclude it in
7343 // our blind search. i.e:
7344 // template<class T> void f(); template<class T, class U> void f(U);
7345 // f<int> == 0; // resolve f<int> blindly
7346 // void (*p)(int); p = f<int>; // resolve f<int> using target
7347 if (Opc != BO_Assign) {
7348 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
7349 if (!resolvedLHS.isUsable()) return ExprError();
7350 lhs = move(resolvedLHS);
7352 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
7353 if (!resolvedRHS.isUsable()) return ExprError();
7354 rhs = move(resolvedRHS);
7357 // The canonical way to check for a GNU null is with isNullPointerConstant,
7358 // but we use a bit of a hack here for speed; this is a relatively
7359 // hot path, and isNullPointerConstant is slow.
7360 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7361 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
7363 // Detect when a NULL constant is used improperly in an expression. These
7364 // are mainly cases where the null pointer is used as an integer instead
7365 // of a pointer.
7366 if (LeftNull || RightNull) {
7367 // Avoid analyzing cases where the result will either be invalid (and
7368 // diagnosed as such) or entirely valid and not something to warn about.
7369 QualType LeftType = lhs.get()->getType();
7370 QualType RightType = rhs.get()->getType();
7371 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7372 !LeftType->isFunctionType() &&
7373 !RightType->isBlockPointerType() &&
7374 !RightType->isMemberPointerType() &&
7375 !RightType->isFunctionType()) {
7376 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7377 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7378 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7379 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7380 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7381 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7382 // These are the operations that would not make sense with a null pointer
7383 // no matter what the other expression is.
7384 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7385 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7386 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7387 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7388 Opc == BO_EQ || Opc == BO_NE) {
7389 // These are the operations that would not make sense with a null pointer
7390 // if the other expression the other expression is not a pointer.
7391 if (LeftNull != RightNull &&
7392 !LeftType->isAnyPointerType() &&
7393 !LeftType->canDecayToPointerType() &&
7394 !RightType->isAnyPointerType() &&
7395 !RightType->canDecayToPointerType()) {
7396 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7397 << (LeftNull ? lhs.get()->getSourceRange()
7398 : rhs.get()->getSourceRange());
7404 switch (Opc) {
7405 case BO_Assign:
7406 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
7407 if (getLangOptions().CPlusPlus &&
7408 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7409 VK = lhs.get()->getValueKind();
7410 OK = lhs.get()->getObjectKind();
7412 if (!ResultTy.isNull())
7413 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
7414 break;
7415 case BO_PtrMemD:
7416 case BO_PtrMemI:
7417 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
7418 Opc == BO_PtrMemI);
7419 break;
7420 case BO_Mul:
7421 case BO_Div:
7422 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
7423 Opc == BO_Div);
7424 break;
7425 case BO_Rem:
7426 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7427 break;
7428 case BO_Add:
7429 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7430 break;
7431 case BO_Sub:
7432 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7433 break;
7434 case BO_Shl:
7435 case BO_Shr:
7436 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
7437 break;
7438 case BO_LE:
7439 case BO_LT:
7440 case BO_GE:
7441 case BO_GT:
7442 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
7443 break;
7444 case BO_EQ:
7445 case BO_NE:
7446 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
7447 break;
7448 case BO_And:
7449 case BO_Xor:
7450 case BO_Or:
7451 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7452 break;
7453 case BO_LAnd:
7454 case BO_LOr:
7455 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
7456 break;
7457 case BO_MulAssign:
7458 case BO_DivAssign:
7459 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
7460 Opc == BO_DivAssign);
7461 CompLHSTy = CompResultTy;
7462 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7463 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
7464 break;
7465 case BO_RemAssign:
7466 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7467 CompLHSTy = CompResultTy;
7468 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7469 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
7470 break;
7471 case BO_AddAssign:
7472 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7473 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7474 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
7475 break;
7476 case BO_SubAssign:
7477 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7478 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7479 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
7480 break;
7481 case BO_ShlAssign:
7482 case BO_ShrAssign:
7483 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
7484 CompLHSTy = CompResultTy;
7485 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7486 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
7487 break;
7488 case BO_AndAssign:
7489 case BO_XorAssign:
7490 case BO_OrAssign:
7491 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7492 CompLHSTy = CompResultTy;
7493 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7494 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
7495 break;
7496 case BO_Comma:
7497 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
7498 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7499 VK = rhs.get()->getValueKind();
7500 OK = rhs.get()->getObjectKind();
7502 break;
7504 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
7505 return ExprError();
7506 if (CompResultTy.isNull())
7507 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7508 ResultTy, VK, OK, OpLoc));
7509 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
7510 VK = VK_LValue;
7511 OK = lhs.get()->getObjectKind();
7513 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7514 ResultTy, VK, OK, CompLHSTy,
7515 CompResultTy, OpLoc));
7518 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7519 /// operators are mixed in a way that suggests that the programmer forgot that
7520 /// comparison operators have higher precedence. The most typical example of
7521 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
7522 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
7523 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
7524 typedef BinaryOperator BinOp;
7525 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7526 rhsopc = static_cast<BinOp::Opcode>(-1);
7527 if (BinOp *BO = dyn_cast<BinOp>(lhs))
7528 lhsopc = BO->getOpcode();
7529 if (BinOp *BO = dyn_cast<BinOp>(rhs))
7530 rhsopc = BO->getOpcode();
7532 // Subs are not binary operators.
7533 if (lhsopc == -1 && rhsopc == -1)
7534 return;
7536 // Bitwise operations are sometimes used as eager logical ops.
7537 // Don't diagnose this.
7538 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7539 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
7540 return;
7542 if (BinOp::isComparisonOp(lhsopc)) {
7543 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7544 << SourceRange(lhs->getLocStart(), OpLoc)
7545 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
7546 SuggestParentheses(Self, OpLoc,
7547 Self.PDiag(diag::note_precedence_bitwise_silence)
7548 << BinOp::getOpcodeStr(lhsopc),
7549 lhs->getSourceRange());
7550 SuggestParentheses(Self, OpLoc,
7551 Self.PDiag(diag::note_precedence_bitwise_first)
7552 << BinOp::getOpcodeStr(Opc),
7553 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
7554 } else if (BinOp::isComparisonOp(rhsopc)) {
7555 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7556 << SourceRange(OpLoc, rhs->getLocEnd())
7557 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
7558 SuggestParentheses(Self, OpLoc,
7559 Self.PDiag(diag::note_precedence_bitwise_silence)
7560 << BinOp::getOpcodeStr(rhsopc),
7561 rhs->getSourceRange());
7562 SuggestParentheses(Self, OpLoc,
7563 Self.PDiag(diag::note_precedence_bitwise_first)
7564 << BinOp::getOpcodeStr(Opc),
7565 SourceRange(lhs->getLocStart(),
7566 cast<BinOp>(rhs)->getLHS()->getLocStart()));
7570 /// \brief It accepts a '&' expr that is inside a '|' one.
7571 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7572 /// in parentheses.
7573 static void
7574 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7575 BinaryOperator *Bop) {
7576 assert(Bop->getOpcode() == BO_And);
7577 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7578 << Bop->getSourceRange() << OpLoc;
7579 SuggestParentheses(Self, Bop->getOperatorLoc(),
7580 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7581 Bop->getSourceRange());
7584 /// \brief It accepts a '&&' expr that is inside a '||' one.
7585 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7586 /// in parentheses.
7587 static void
7588 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7589 BinaryOperator *Bop) {
7590 assert(Bop->getOpcode() == BO_LAnd);
7591 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7592 << Bop->getSourceRange() << OpLoc;
7593 SuggestParentheses(Self, Bop->getOperatorLoc(),
7594 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7595 Bop->getSourceRange());
7598 /// \brief Returns true if the given expression can be evaluated as a constant
7599 /// 'true'.
7600 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7601 bool Res;
7602 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7605 /// \brief Returns true if the given expression can be evaluated as a constant
7606 /// 'false'.
7607 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7608 bool Res;
7609 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7612 /// \brief Look for '&&' in the left hand of a '||' expr.
7613 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
7614 Expr *OrLHS, Expr *OrRHS) {
7615 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
7616 if (Bop->getOpcode() == BO_LAnd) {
7617 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7618 if (EvaluatesAsFalse(S, OrRHS))
7619 return;
7620 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7621 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7622 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7623 } else if (Bop->getOpcode() == BO_LOr) {
7624 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7625 // If it's "a || b && 1 || c" we didn't warn earlier for
7626 // "a || b && 1", but warn now.
7627 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7628 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7634 /// \brief Look for '&&' in the right hand of a '||' expr.
7635 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
7636 Expr *OrLHS, Expr *OrRHS) {
7637 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
7638 if (Bop->getOpcode() == BO_LAnd) {
7639 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7640 if (EvaluatesAsFalse(S, OrLHS))
7641 return;
7642 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7643 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7644 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7649 /// \brief Look for '&' in the left or right hand of a '|' expr.
7650 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7651 Expr *OrArg) {
7652 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7653 if (Bop->getOpcode() == BO_And)
7654 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7658 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
7659 /// precedence.
7660 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
7661 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
7662 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
7663 if (BinaryOperator::isBitwiseOp(Opc))
7664 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7666 // Diagnose "arg1 & arg2 | arg3"
7667 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7668 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7669 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7672 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7673 // We don't warn for 'assert(a || b && "bad")' since this is safe.
7674 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7675 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7676 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
7680 // Binary Operators. 'Tok' is the token for the operator.
7681 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
7682 tok::TokenKind Kind,
7683 Expr *lhs, Expr *rhs) {
7684 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
7685 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7686 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
7688 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7689 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7691 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7694 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
7695 BinaryOperatorKind Opc,
7696 Expr *lhs, Expr *rhs) {
7697 if (getLangOptions().CPlusPlus) {
7698 bool UseBuiltinOperator;
7700 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7701 UseBuiltinOperator = false;
7702 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7703 UseBuiltinOperator = true;
7704 } else {
7705 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7706 !rhs->getType()->isOverloadableType();
7709 if (!UseBuiltinOperator) {
7710 // Find all of the overloaded operators visible from this
7711 // point. We perform both an operator-name lookup from the local
7712 // scope and an argument-dependent lookup based on the types of
7713 // the arguments.
7714 UnresolvedSet<16> Functions;
7715 OverloadedOperatorKind OverOp
7716 = BinaryOperator::getOverloadedOperator(Opc);
7717 if (S && OverOp != OO_None)
7718 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7719 Functions);
7721 // Build the (potentially-overloaded, potentially-dependent)
7722 // binary operation.
7723 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7727 // Build a built-in binary operation.
7728 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
7731 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
7732 UnaryOperatorKind Opc,
7733 Expr *InputExpr) {
7734 ExprResult Input = Owned(InputExpr);
7735 ExprValueKind VK = VK_RValue;
7736 ExprObjectKind OK = OK_Ordinary;
7737 QualType resultType;
7738 switch (Opc) {
7739 case UO_PreInc:
7740 case UO_PreDec:
7741 case UO_PostInc:
7742 case UO_PostDec:
7743 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
7744 Opc == UO_PreInc ||
7745 Opc == UO_PostInc,
7746 Opc == UO_PreInc ||
7747 Opc == UO_PreDec);
7748 break;
7749 case UO_AddrOf:
7750 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
7751 break;
7752 case UO_Deref: {
7753 ExprResult resolved = CheckPlaceholderExpr(Input.get());
7754 if (!resolved.isUsable()) return ExprError();
7755 Input = move(resolved);
7756 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7757 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
7758 break;
7760 case UO_Plus:
7761 case UO_Minus:
7762 Input = UsualUnaryConversions(Input.take());
7763 if (Input.isInvalid()) return ExprError();
7764 resultType = Input.get()->getType();
7765 if (resultType->isDependentType())
7766 break;
7767 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7768 resultType->isVectorType())
7769 break;
7770 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7771 resultType->isEnumeralType())
7772 break;
7773 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
7774 Opc == UO_Plus &&
7775 resultType->isPointerType())
7776 break;
7777 else if (resultType->isPlaceholderType()) {
7778 Input = CheckPlaceholderExpr(Input.take());
7779 if (Input.isInvalid()) return ExprError();
7780 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
7783 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7784 << resultType << Input.get()->getSourceRange());
7786 case UO_Not: // bitwise complement
7787 Input = UsualUnaryConversions(Input.take());
7788 if (Input.isInvalid()) return ExprError();
7789 resultType = Input.get()->getType();
7790 if (resultType->isDependentType())
7791 break;
7792 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7793 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7794 // C99 does not support '~' for complex conjugation.
7795 Diag(OpLoc, diag::ext_integer_complement_complex)
7796 << resultType << Input.get()->getSourceRange();
7797 else if (resultType->hasIntegerRepresentation())
7798 break;
7799 else if (resultType->isPlaceholderType()) {
7800 Input = CheckPlaceholderExpr(Input.take());
7801 if (Input.isInvalid()) return ExprError();
7802 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
7803 } else {
7804 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7805 << resultType << Input.get()->getSourceRange());
7807 break;
7809 case UO_LNot: // logical negation
7810 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
7811 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7812 if (Input.isInvalid()) return ExprError();
7813 resultType = Input.get()->getType();
7814 if (resultType->isDependentType())
7815 break;
7816 if (resultType->isScalarType()) {
7817 // C99 6.5.3.3p1: ok, fallthrough;
7818 if (Context.getLangOptions().CPlusPlus) {
7819 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
7820 // operand contextually converted to bool.
7821 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
7822 ScalarTypeToBooleanCastKind(resultType));
7824 } else if (resultType->isPlaceholderType()) {
7825 Input = CheckPlaceholderExpr(Input.take());
7826 if (Input.isInvalid()) return ExprError();
7827 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
7828 } else {
7829 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7830 << resultType << Input.get()->getSourceRange());
7833 // LNot always has type int. C99 6.5.3.3p5.
7834 // In C++, it's bool. C++ 5.3.1p8
7835 resultType = Context.getLogicalOperationType();
7836 break;
7837 case UO_Real:
7838 case UO_Imag:
7839 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
7840 // _Real and _Imag map ordinary l-values into ordinary l-values.
7841 if (Input.isInvalid()) return ExprError();
7842 if (Input.get()->getValueKind() != VK_RValue &&
7843 Input.get()->getObjectKind() == OK_Ordinary)
7844 VK = Input.get()->getValueKind();
7845 break;
7846 case UO_Extension:
7847 resultType = Input.get()->getType();
7848 VK = Input.get()->getValueKind();
7849 OK = Input.get()->getObjectKind();
7850 break;
7852 if (resultType.isNull() || Input.isInvalid())
7853 return ExprError();
7855 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
7856 VK, OK, OpLoc));
7859 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
7860 UnaryOperatorKind Opc,
7861 Expr *Input) {
7862 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
7863 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
7864 // Find all of the overloaded operators visible from this
7865 // point. We perform both an operator-name lookup from the local
7866 // scope and an argument-dependent lookup based on the types of
7867 // the arguments.
7868 UnresolvedSet<16> Functions;
7869 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
7870 if (S && OverOp != OO_None)
7871 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7872 Functions);
7874 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
7877 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
7880 // Unary Operators. 'Tok' is the token for the operator.
7881 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
7882 tok::TokenKind Op, Expr *Input) {
7883 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
7886 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7887 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7888 LabelDecl *TheDecl) {
7889 TheDecl->setUsed();
7890 // Create the AST node. The address of a label always has type 'void*'.
7891 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
7892 Context.getPointerType(Context.VoidTy)));
7895 /// Given the last statement in a statement-expression, check whether
7896 /// the result is a producing expression (like a call to an
7897 /// ns_returns_retained function) and, if so, rebuild it to hoist the
7898 /// release out of the full-expression. Otherwise, return null.
7899 /// Cannot fail.
7900 static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
7901 // Should always be wrapped with one of these.
7902 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
7903 if (!cleanups) return 0;
7905 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
7906 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
7907 return 0;
7909 // Splice out the cast. This shouldn't modify any interesting
7910 // features of the statement.
7911 Expr *producer = cast->getSubExpr();
7912 assert(producer->getType() == cast->getType());
7913 assert(producer->getValueKind() == cast->getValueKind());
7914 cleanups->setSubExpr(producer);
7915 return cleanups;
7918 ExprResult
7919 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7920 SourceLocation RPLoc) { // "({..})"
7921 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
7922 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
7924 bool isFileScope
7925 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
7926 if (isFileScope)
7927 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
7929 // FIXME: there are a variety of strange constraints to enforce here, for
7930 // example, it is not possible to goto into a stmt expression apparently.
7931 // More semantic analysis is needed.
7933 // If there are sub stmts in the compound stmt, take the type of the last one
7934 // as the type of the stmtexpr.
7935 QualType Ty = Context.VoidTy;
7936 bool StmtExprMayBindToTemp = false;
7937 if (!Compound->body_empty()) {
7938 Stmt *LastStmt = Compound->body_back();
7939 LabelStmt *LastLabelStmt = 0;
7940 // If LastStmt is a label, skip down through into the body.
7941 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
7942 LastLabelStmt = Label;
7943 LastStmt = Label->getSubStmt();
7946 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
7947 // Do function/array conversion on the last expression, but not
7948 // lvalue-to-rvalue. However, initialize an unqualified type.
7949 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
7950 if (LastExpr.isInvalid())
7951 return ExprError();
7952 Ty = LastExpr.get()->getType().getUnqualifiedType();
7954 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
7955 // In ARC, if the final expression ends in a consume, splice
7956 // the consume out and bind it later. In the alternate case
7957 // (when dealing with a retainable type), the result
7958 // initialization will create a produce. In both cases the
7959 // result will be +1, and we'll need to balance that out with
7960 // a bind.
7961 if (Expr *rebuiltLastStmt
7962 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
7963 LastExpr = rebuiltLastStmt;
7964 } else {
7965 LastExpr = PerformCopyInitialization(
7966 InitializedEntity::InitializeResult(LPLoc,
7968 false),
7969 SourceLocation(),
7970 LastExpr);
7973 if (LastExpr.isInvalid())
7974 return ExprError();
7975 if (LastExpr.get() != 0) {
7976 if (!LastLabelStmt)
7977 Compound->setLastStmt(LastExpr.take());
7978 else
7979 LastLabelStmt->setSubStmt(LastExpr.take());
7980 StmtExprMayBindToTemp = true;
7986 // FIXME: Check that expression type is complete/non-abstract; statement
7987 // expressions are not lvalues.
7988 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
7989 if (StmtExprMayBindToTemp)
7990 return MaybeBindToTemporary(ResStmtExpr);
7991 return Owned(ResStmtExpr);
7994 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7995 TypeSourceInfo *TInfo,
7996 OffsetOfComponent *CompPtr,
7997 unsigned NumComponents,
7998 SourceLocation RParenLoc) {
7999 QualType ArgTy = TInfo->getType();
8000 bool Dependent = ArgTy->isDependentType();
8001 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8003 // We must have at least one component that refers to the type, and the first
8004 // one is known to be a field designator. Verify that the ArgTy represents
8005 // a struct/union/class.
8006 if (!Dependent && !ArgTy->isRecordType())
8007 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8008 << ArgTy << TypeRange);
8010 // Type must be complete per C99 7.17p3 because a declaring a variable
8011 // with an incomplete type would be ill-formed.
8012 if (!Dependent
8013 && RequireCompleteType(BuiltinLoc, ArgTy,
8014 PDiag(diag::err_offsetof_incomplete_type)
8015 << TypeRange))
8016 return ExprError();
8018 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8019 // GCC extension, diagnose them.
8020 // FIXME: This diagnostic isn't actually visible because the location is in
8021 // a system header!
8022 if (NumComponents != 1)
8023 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8024 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
8026 bool DidWarnAboutNonPOD = false;
8027 QualType CurrentType = ArgTy;
8028 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8029 llvm::SmallVector<OffsetOfNode, 4> Comps;
8030 llvm::SmallVector<Expr*, 4> Exprs;
8031 for (unsigned i = 0; i != NumComponents; ++i) {
8032 const OffsetOfComponent &OC = CompPtr[i];
8033 if (OC.isBrackets) {
8034 // Offset of an array sub-field. TODO: Should we allow vector elements?
8035 if (!CurrentType->isDependentType()) {
8036 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8037 if(!AT)
8038 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8039 << CurrentType);
8040 CurrentType = AT->getElementType();
8041 } else
8042 CurrentType = Context.DependentTy;
8044 // The expression must be an integral expression.
8045 // FIXME: An integral constant expression?
8046 Expr *Idx = static_cast<Expr*>(OC.U.E);
8047 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8048 !Idx->getType()->isIntegerType())
8049 return ExprError(Diag(Idx->getLocStart(),
8050 diag::err_typecheck_subscript_not_integer)
8051 << Idx->getSourceRange());
8053 // Record this array index.
8054 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8055 Exprs.push_back(Idx);
8056 continue;
8059 // Offset of a field.
8060 if (CurrentType->isDependentType()) {
8061 // We have the offset of a field, but we can't look into the dependent
8062 // type. Just record the identifier of the field.
8063 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8064 CurrentType = Context.DependentTy;
8065 continue;
8068 // We need to have a complete type to look into.
8069 if (RequireCompleteType(OC.LocStart, CurrentType,
8070 diag::err_offsetof_incomplete_type))
8071 return ExprError();
8073 // Look for the designated field.
8074 const RecordType *RC = CurrentType->getAs<RecordType>();
8075 if (!RC)
8076 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8077 << CurrentType);
8078 RecordDecl *RD = RC->getDecl();
8080 // C++ [lib.support.types]p5:
8081 // The macro offsetof accepts a restricted set of type arguments in this
8082 // International Standard. type shall be a POD structure or a POD union
8083 // (clause 9).
8084 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8085 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8086 DiagRuntimeBehavior(BuiltinLoc, 0,
8087 PDiag(diag::warn_offsetof_non_pod_type)
8088 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8089 << CurrentType))
8090 DidWarnAboutNonPOD = true;
8093 // Look for the field.
8094 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8095 LookupQualifiedName(R, RD);
8096 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
8097 IndirectFieldDecl *IndirectMemberDecl = 0;
8098 if (!MemberDecl) {
8099 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
8100 MemberDecl = IndirectMemberDecl->getAnonField();
8103 if (!MemberDecl)
8104 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8105 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8106 OC.LocEnd));
8108 // C99 7.17p3:
8109 // (If the specified member is a bit-field, the behavior is undefined.)
8111 // We diagnose this as an error.
8112 if (MemberDecl->getBitWidth()) {
8113 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8114 << MemberDecl->getDeclName()
8115 << SourceRange(BuiltinLoc, RParenLoc);
8116 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8117 return ExprError();
8120 RecordDecl *Parent = MemberDecl->getParent();
8121 if (IndirectMemberDecl)
8122 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
8124 // If the member was found in a base class, introduce OffsetOfNodes for
8125 // the base class indirections.
8126 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8127 /*DetectVirtual=*/false);
8128 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
8129 CXXBasePath &Path = Paths.front();
8130 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8131 B != BEnd; ++B)
8132 Comps.push_back(OffsetOfNode(B->Base));
8135 if (IndirectMemberDecl) {
8136 for (IndirectFieldDecl::chain_iterator FI =
8137 IndirectMemberDecl->chain_begin(),
8138 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8139 assert(isa<FieldDecl>(*FI));
8140 Comps.push_back(OffsetOfNode(OC.LocStart,
8141 cast<FieldDecl>(*FI), OC.LocEnd));
8143 } else
8144 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
8146 CurrentType = MemberDecl->getType().getNonReferenceType();
8149 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8150 TInfo, Comps.data(), Comps.size(),
8151 Exprs.data(), Exprs.size(), RParenLoc));
8154 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
8155 SourceLocation BuiltinLoc,
8156 SourceLocation TypeLoc,
8157 ParsedType argty,
8158 OffsetOfComponent *CompPtr,
8159 unsigned NumComponents,
8160 SourceLocation RPLoc) {
8162 TypeSourceInfo *ArgTInfo;
8163 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8164 if (ArgTy.isNull())
8165 return ExprError();
8167 if (!ArgTInfo)
8168 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8170 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8171 RPLoc);
8175 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
8176 Expr *CondExpr,
8177 Expr *LHSExpr, Expr *RHSExpr,
8178 SourceLocation RPLoc) {
8179 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8181 ExprValueKind VK = VK_RValue;
8182 ExprObjectKind OK = OK_Ordinary;
8183 QualType resType;
8184 bool ValueDependent = false;
8185 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
8186 resType = Context.DependentTy;
8187 ValueDependent = true;
8188 } else {
8189 // The conditional expression is required to be a constant expression.
8190 llvm::APSInt condEval(32);
8191 SourceLocation ExpLoc;
8192 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
8193 return ExprError(Diag(ExpLoc,
8194 diag::err_typecheck_choose_expr_requires_constant)
8195 << CondExpr->getSourceRange());
8197 // If the condition is > zero, then the AST type is the same as the LSHExpr.
8198 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8200 resType = ActiveExpr->getType();
8201 ValueDependent = ActiveExpr->isValueDependent();
8202 VK = ActiveExpr->getValueKind();
8203 OK = ActiveExpr->getObjectKind();
8206 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
8207 resType, VK, OK, RPLoc,
8208 resType->isDependentType(),
8209 ValueDependent));
8212 //===----------------------------------------------------------------------===//
8213 // Clang Extensions.
8214 //===----------------------------------------------------------------------===//
8216 /// ActOnBlockStart - This callback is invoked when a block literal is started.
8217 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
8218 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8219 PushBlockScope(BlockScope, Block);
8220 CurContext->addDecl(Block);
8221 if (BlockScope)
8222 PushDeclContext(BlockScope, Block);
8223 else
8224 CurContext = Block;
8227 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
8228 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
8229 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
8230 BlockScopeInfo *CurBlock = getCurBlock();
8232 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
8233 QualType T = Sig->getType();
8235 // GetTypeForDeclarator always produces a function type for a block
8236 // literal signature. Furthermore, it is always a FunctionProtoType
8237 // unless the function was written with a typedef.
8238 assert(T->isFunctionType() &&
8239 "GetTypeForDeclarator made a non-function block signature");
8241 // Look for an explicit signature in that function type.
8242 FunctionProtoTypeLoc ExplicitSignature;
8244 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8245 if (isa<FunctionProtoTypeLoc>(tmp)) {
8246 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8248 // Check whether that explicit signature was synthesized by
8249 // GetTypeForDeclarator. If so, don't save that as part of the
8250 // written signature.
8251 if (ExplicitSignature.getLocalRangeBegin() ==
8252 ExplicitSignature.getLocalRangeEnd()) {
8253 // This would be much cheaper if we stored TypeLocs instead of
8254 // TypeSourceInfos.
8255 TypeLoc Result = ExplicitSignature.getResultLoc();
8256 unsigned Size = Result.getFullDataSize();
8257 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8258 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8260 ExplicitSignature = FunctionProtoTypeLoc();
8264 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8265 CurBlock->FunctionType = T;
8267 const FunctionType *Fn = T->getAs<FunctionType>();
8268 QualType RetTy = Fn->getResultType();
8269 bool isVariadic =
8270 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8272 CurBlock->TheDecl->setIsVariadic(isVariadic);
8274 // Don't allow returning a objc interface by value.
8275 if (RetTy->isObjCObjectType()) {
8276 Diag(ParamInfo.getSourceRange().getBegin(),
8277 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8278 return;
8281 // Context.DependentTy is used as a placeholder for a missing block
8282 // return type. TODO: what should we do with declarators like:
8283 // ^ * { ... }
8284 // If the answer is "apply template argument deduction"....
8285 if (RetTy != Context.DependentTy)
8286 CurBlock->ReturnType = RetTy;
8288 // Push block parameters from the declarator if we had them.
8289 llvm::SmallVector<ParmVarDecl*, 8> Params;
8290 if (ExplicitSignature) {
8291 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8292 ParmVarDecl *Param = ExplicitSignature.getArg(I);
8293 if (Param->getIdentifier() == 0 &&
8294 !Param->isImplicit() &&
8295 !Param->isInvalidDecl() &&
8296 !getLangOptions().CPlusPlus)
8297 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8298 Params.push_back(Param);
8301 // Fake up parameter variables if we have a typedef, like
8302 // ^ fntype { ... }
8303 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8304 for (FunctionProtoType::arg_type_iterator
8305 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8306 ParmVarDecl *Param =
8307 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8308 ParamInfo.getSourceRange().getBegin(),
8309 *I);
8310 Params.push_back(Param);
8314 // Set the parameters on the block decl.
8315 if (!Params.empty()) {
8316 CurBlock->TheDecl->setParams(Params.data(), Params.size());
8317 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8318 CurBlock->TheDecl->param_end(),
8319 /*CheckParameterNames=*/false);
8322 // Finally we can process decl attributes.
8323 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
8325 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
8326 Diag(ParamInfo.getAttributes()->getLoc(),
8327 diag::warn_attribute_sentinel_not_variadic) << 1;
8328 // FIXME: remove the attribute.
8331 // Put the parameter variables in scope. We can bail out immediately
8332 // if we don't have any.
8333 if (Params.empty())
8334 return;
8336 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
8337 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8338 (*AI)->setOwningFunction(CurBlock->TheDecl);
8340 // If this has an identifier, add it to the scope stack.
8341 if ((*AI)->getIdentifier()) {
8342 CheckShadow(CurBlock->TheScope, *AI);
8344 PushOnScopeChains(*AI, CurBlock->TheScope);
8349 /// ActOnBlockError - If there is an error parsing a block, this callback
8350 /// is invoked to pop the information about the block from the action impl.
8351 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
8352 // Pop off CurBlock, handle nested blocks.
8353 PopDeclContext();
8354 PopFunctionOrBlockScope();
8357 /// ActOnBlockStmtExpr - This is called when the body of a block statement
8358 /// literal was successfully completed. ^(int x){...}
8359 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
8360 Stmt *Body, Scope *CurScope) {
8361 // If blocks are disabled, emit an error.
8362 if (!LangOpts.Blocks)
8363 Diag(CaretLoc, diag::err_blocks_disable);
8365 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
8367 PopDeclContext();
8369 QualType RetTy = Context.VoidTy;
8370 if (!BSI->ReturnType.isNull())
8371 RetTy = BSI->ReturnType;
8373 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
8374 QualType BlockTy;
8376 // Set the captured variables on the block.
8377 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8378 BSI->CapturesCXXThis);
8380 // If the user wrote a function type in some form, try to use that.
8381 if (!BSI->FunctionType.isNull()) {
8382 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8384 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8385 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8387 // Turn protoless block types into nullary block types.
8388 if (isa<FunctionNoProtoType>(FTy)) {
8389 FunctionProtoType::ExtProtoInfo EPI;
8390 EPI.ExtInfo = Ext;
8391 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8393 // Otherwise, if we don't need to change anything about the function type,
8394 // preserve its sugar structure.
8395 } else if (FTy->getResultType() == RetTy &&
8396 (!NoReturn || FTy->getNoReturnAttr())) {
8397 BlockTy = BSI->FunctionType;
8399 // Otherwise, make the minimal modifications to the function type.
8400 } else {
8401 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8402 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8403 EPI.TypeQuals = 0; // FIXME: silently?
8404 EPI.ExtInfo = Ext;
8405 BlockTy = Context.getFunctionType(RetTy,
8406 FPT->arg_type_begin(),
8407 FPT->getNumArgs(),
8408 EPI);
8411 // If we don't have a function type, just build one from nothing.
8412 } else {
8413 FunctionProtoType::ExtProtoInfo EPI;
8414 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
8415 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8418 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8419 BSI->TheDecl->param_end());
8420 BlockTy = Context.getBlockPointerType(BlockTy);
8422 // If needed, diagnose invalid gotos and switches in the block.
8423 if (getCurFunction()->NeedsScopeChecking() &&
8424 !hasAnyUnrecoverableErrorsInThisFunction())
8425 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
8427 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
8429 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8431 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8432 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8433 return Owned(Result);
8436 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
8437 Expr *expr, ParsedType type,
8438 SourceLocation RPLoc) {
8439 TypeSourceInfo *TInfo;
8440 GetTypeFromParser(type, &TInfo);
8441 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
8444 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
8445 Expr *E, TypeSourceInfo *TInfo,
8446 SourceLocation RPLoc) {
8447 Expr *OrigExpr = E;
8449 // Get the va_list type
8450 QualType VaListType = Context.getBuiltinVaListType();
8451 if (VaListType->isArrayType()) {
8452 // Deal with implicit array decay; for example, on x86-64,
8453 // va_list is an array, but it's supposed to decay to
8454 // a pointer for va_arg.
8455 VaListType = Context.getArrayDecayedType(VaListType);
8456 // Make sure the input expression also decays appropriately.
8457 ExprResult Result = UsualUnaryConversions(E);
8458 if (Result.isInvalid())
8459 return ExprError();
8460 E = Result.take();
8461 } else {
8462 // Otherwise, the va_list argument must be an l-value because
8463 // it is modified by va_arg.
8464 if (!E->isTypeDependent() &&
8465 CheckForModifiableLvalue(E, BuiltinLoc, *this))
8466 return ExprError();
8469 if (!E->isTypeDependent() &&
8470 !Context.hasSameType(VaListType, E->getType())) {
8471 return ExprError(Diag(E->getLocStart(),
8472 diag::err_first_argument_to_va_arg_not_of_type_va_list)
8473 << OrigExpr->getType() << E->getSourceRange());
8476 if (!TInfo->getType()->isDependentType()) {
8477 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8478 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8479 << TInfo->getTypeLoc().getSourceRange()))
8480 return ExprError();
8482 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8483 TInfo->getType(),
8484 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8485 << TInfo->getTypeLoc().getSourceRange()))
8486 return ExprError();
8488 if (!TInfo->getType().isPODType(Context))
8489 Diag(TInfo->getTypeLoc().getBeginLoc(),
8490 diag::warn_second_parameter_to_va_arg_not_pod)
8491 << TInfo->getType()
8492 << TInfo->getTypeLoc().getSourceRange();
8495 QualType T = TInfo->getType().getNonLValueExprType(Context);
8496 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
8499 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
8500 // The type of __null will be int or long, depending on the size of
8501 // pointers on the target.
8502 QualType Ty;
8503 unsigned pw = Context.Target.getPointerWidth(0);
8504 if (pw == Context.Target.getIntWidth())
8505 Ty = Context.IntTy;
8506 else if (pw == Context.Target.getLongWidth())
8507 Ty = Context.LongTy;
8508 else if (pw == Context.Target.getLongLongWidth())
8509 Ty = Context.LongLongTy;
8510 else {
8511 assert(!"I don't know size of pointer!");
8512 Ty = Context.IntTy;
8515 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
8518 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
8519 Expr *SrcExpr, FixItHint &Hint) {
8520 if (!SemaRef.getLangOptions().ObjC1)
8521 return;
8523 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8524 if (!PT)
8525 return;
8527 // Check if the destination is of type 'id'.
8528 if (!PT->isObjCIdType()) {
8529 // Check if the destination is the 'NSString' interface.
8530 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8531 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8532 return;
8535 // Strip off any parens and casts.
8536 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8537 if (!SL || SL->isWide())
8538 return;
8540 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
8543 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8544 SourceLocation Loc,
8545 QualType DstType, QualType SrcType,
8546 Expr *SrcExpr, AssignmentAction Action,
8547 bool *Complained) {
8548 if (Complained)
8549 *Complained = false;
8551 // Decode the result (notice that AST's are still created for extensions).
8552 bool CheckInferredResultType = false;
8553 bool isInvalid = false;
8554 unsigned DiagKind;
8555 FixItHint Hint;
8557 switch (ConvTy) {
8558 default: assert(0 && "Unknown conversion type");
8559 case Compatible: return false;
8560 case PointerToInt:
8561 DiagKind = diag::ext_typecheck_convert_pointer_int;
8562 break;
8563 case IntToPointer:
8564 DiagKind = diag::ext_typecheck_convert_int_pointer;
8565 break;
8566 case IncompatiblePointer:
8567 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
8568 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8569 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8570 SrcType->isObjCObjectPointerType();
8571 break;
8572 case IncompatiblePointerSign:
8573 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8574 break;
8575 case FunctionVoidPointer:
8576 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8577 break;
8578 case IncompatiblePointerDiscardsQualifiers: {
8579 // Perform array-to-pointer decay if necessary.
8580 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8582 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8583 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8584 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8585 DiagKind = diag::err_typecheck_incompatible_address_space;
8586 break;
8589 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
8590 DiagKind = diag::err_typecheck_incompatible_ownership;
8591 break;
8594 llvm_unreachable("unknown error case for discarding qualifiers!");
8595 // fallthrough
8597 case CompatiblePointerDiscardsQualifiers:
8598 // If the qualifiers lost were because we were applying the
8599 // (deprecated) C++ conversion from a string literal to a char*
8600 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8601 // Ideally, this check would be performed in
8602 // checkPointerTypesForAssignment. However, that would require a
8603 // bit of refactoring (so that the second argument is an
8604 // expression, rather than a type), which should be done as part
8605 // of a larger effort to fix checkPointerTypesForAssignment for
8606 // C++ semantics.
8607 if (getLangOptions().CPlusPlus &&
8608 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8609 return false;
8610 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8611 break;
8612 case IncompatibleNestedPointerQualifiers:
8613 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
8614 break;
8615 case IntToBlockPointer:
8616 DiagKind = diag::err_int_to_block_pointer;
8617 break;
8618 case IncompatibleBlockPointer:
8619 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
8620 break;
8621 case IncompatibleObjCQualifiedId:
8622 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
8623 // it can give a more specific diagnostic.
8624 DiagKind = diag::warn_incompatible_qualified_id;
8625 break;
8626 case IncompatibleVectors:
8627 DiagKind = diag::warn_incompatible_vectors;
8628 break;
8629 case Incompatible:
8630 DiagKind = diag::err_typecheck_convert_incompatible;
8631 isInvalid = true;
8632 break;
8635 QualType FirstType, SecondType;
8636 switch (Action) {
8637 case AA_Assigning:
8638 case AA_Initializing:
8639 // The destination type comes first.
8640 FirstType = DstType;
8641 SecondType = SrcType;
8642 break;
8644 case AA_Returning:
8645 case AA_Passing:
8646 case AA_Converting:
8647 case AA_Sending:
8648 case AA_Casting:
8649 // The source type comes first.
8650 FirstType = SrcType;
8651 SecondType = DstType;
8652 break;
8655 Diag(Loc, DiagKind) << FirstType << SecondType << Action
8656 << SrcExpr->getSourceRange() << Hint;
8657 if (CheckInferredResultType)
8658 EmitRelatedResultTypeNote(SrcExpr);
8660 if (Complained)
8661 *Complained = true;
8662 return isInvalid;
8665 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
8666 llvm::APSInt ICEResult;
8667 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8668 if (Result)
8669 *Result = ICEResult;
8670 return false;
8673 Expr::EvalResult EvalResult;
8675 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
8676 EvalResult.HasSideEffects) {
8677 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8679 if (EvalResult.Diag) {
8680 // We only show the note if it's not the usual "invalid subexpression"
8681 // or if it's actually in a subexpression.
8682 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8683 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8684 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8687 return true;
8690 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8691 E->getSourceRange();
8693 if (EvalResult.Diag &&
8694 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8695 != Diagnostic::Ignored)
8696 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8698 if (Result)
8699 *Result = EvalResult.Val.getInt();
8700 return false;
8703 void
8704 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
8705 ExprEvalContexts.push_back(
8706 ExpressionEvaluationContextRecord(NewContext,
8707 ExprTemporaries.size(),
8708 ExprNeedsCleanups));
8709 ExprNeedsCleanups = false;
8712 void
8713 Sema::PopExpressionEvaluationContext() {
8714 // Pop the current expression evaluation context off the stack.
8715 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8716 ExprEvalContexts.pop_back();
8718 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8719 if (Rec.PotentiallyReferenced) {
8720 // Mark any remaining declarations in the current position of the stack
8721 // as "referenced". If they were not meant to be referenced, semantic
8722 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
8723 for (PotentiallyReferencedDecls::iterator
8724 I = Rec.PotentiallyReferenced->begin(),
8725 IEnd = Rec.PotentiallyReferenced->end();
8726 I != IEnd; ++I)
8727 MarkDeclarationReferenced(I->first, I->second);
8730 if (Rec.PotentiallyDiagnosed) {
8731 // Emit any pending diagnostics.
8732 for (PotentiallyEmittedDiagnostics::iterator
8733 I = Rec.PotentiallyDiagnosed->begin(),
8734 IEnd = Rec.PotentiallyDiagnosed->end();
8735 I != IEnd; ++I)
8736 Diag(I->first, I->second);
8740 // When are coming out of an unevaluated context, clear out any
8741 // temporaries that we may have created as part of the evaluation of
8742 // the expression in that context: they aren't relevant because they
8743 // will never be constructed.
8744 if (Rec.Context == Unevaluated) {
8745 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8746 ExprTemporaries.end());
8747 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
8749 // Otherwise, merge the contexts together.
8750 } else {
8751 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
8754 // Destroy the popped expression evaluation record.
8755 Rec.Destroy();
8758 void Sema::DiscardCleanupsInEvaluationContext() {
8759 ExprTemporaries.erase(
8760 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
8761 ExprTemporaries.end());
8762 ExprNeedsCleanups = false;
8765 /// \brief Note that the given declaration was referenced in the source code.
8767 /// This routine should be invoke whenever a given declaration is referenced
8768 /// in the source code, and where that reference occurred. If this declaration
8769 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8770 /// C99 6.9p3), then the declaration will be marked as used.
8772 /// \param Loc the location where the declaration was referenced.
8774 /// \param D the declaration that has been referenced by the source code.
8775 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8776 assert(D && "No declaration?");
8778 D->setReferenced();
8780 if (D->isUsed(false))
8781 return;
8783 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8784 // template or not. The reason for this is that unevaluated expressions
8785 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8786 // -Wunused-parameters)
8787 if (isa<ParmVarDecl>(D) ||
8788 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
8789 D->setUsed();
8790 return;
8793 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8794 return;
8796 // Do not mark anything as "used" within a dependent context; wait for
8797 // an instantiation.
8798 if (CurContext->isDependentContext())
8799 return;
8801 switch (ExprEvalContexts.back().Context) {
8802 case Unevaluated:
8803 // We are in an expression that is not potentially evaluated; do nothing.
8804 return;
8806 case PotentiallyEvaluated:
8807 // We are in a potentially-evaluated expression, so this declaration is
8808 // "used"; handle this below.
8809 break;
8811 case PotentiallyPotentiallyEvaluated:
8812 // We are in an expression that may be potentially evaluated; queue this
8813 // declaration reference until we know whether the expression is
8814 // potentially evaluated.
8815 ExprEvalContexts.back().addReferencedDecl(Loc, D);
8816 return;
8818 case PotentiallyEvaluatedIfUsed:
8819 // Referenced declarations will only be used if the construct in the
8820 // containing expression is used.
8821 return;
8824 // Note that this declaration has been used.
8825 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
8826 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
8827 if (Constructor->isTrivial())
8828 return;
8829 if (!Constructor->isUsed(false))
8830 DefineImplicitDefaultConstructor(Loc, Constructor);
8831 } else if (Constructor->isDefaulted() &&
8832 Constructor->isCopyConstructor()) {
8833 if (!Constructor->isUsed(false))
8834 DefineImplicitCopyConstructor(Loc, Constructor);
8837 MarkVTableUsed(Loc, Constructor->getParent());
8838 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
8839 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
8840 DefineImplicitDestructor(Loc, Destructor);
8841 if (Destructor->isVirtual())
8842 MarkVTableUsed(Loc, Destructor->getParent());
8843 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8844 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
8845 MethodDecl->getOverloadedOperator() == OO_Equal) {
8846 if (!MethodDecl->isUsed(false))
8847 DefineImplicitCopyAssignment(Loc, MethodDecl);
8848 } else if (MethodDecl->isVirtual())
8849 MarkVTableUsed(Loc, MethodDecl->getParent());
8851 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
8852 // Recursive functions should be marked when used from another function.
8853 if (CurContext == Function) return;
8855 // Implicit instantiation of function templates and member functions of
8856 // class templates.
8857 if (Function->isImplicitlyInstantiable()) {
8858 bool AlreadyInstantiated = false;
8859 if (FunctionTemplateSpecializationInfo *SpecInfo
8860 = Function->getTemplateSpecializationInfo()) {
8861 if (SpecInfo->getPointOfInstantiation().isInvalid())
8862 SpecInfo->setPointOfInstantiation(Loc);
8863 else if (SpecInfo->getTemplateSpecializationKind()
8864 == TSK_ImplicitInstantiation)
8865 AlreadyInstantiated = true;
8866 } else if (MemberSpecializationInfo *MSInfo
8867 = Function->getMemberSpecializationInfo()) {
8868 if (MSInfo->getPointOfInstantiation().isInvalid())
8869 MSInfo->setPointOfInstantiation(Loc);
8870 else if (MSInfo->getTemplateSpecializationKind()
8871 == TSK_ImplicitInstantiation)
8872 AlreadyInstantiated = true;
8875 if (!AlreadyInstantiated) {
8876 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8877 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8878 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8879 Loc));
8880 else
8881 PendingInstantiations.push_back(std::make_pair(Function, Loc));
8883 } else {
8884 // Walk redefinitions, as some of them may be instantiable.
8885 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8886 e(Function->redecls_end()); i != e; ++i) {
8887 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
8888 MarkDeclarationReferenced(Loc, *i);
8892 // Keep track of used but undefined functions.
8893 if (!Function->isPure() && !Function->hasBody() &&
8894 Function->getLinkage() != ExternalLinkage) {
8895 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
8896 if (old.isInvalid()) old = Loc;
8899 Function->setUsed(true);
8900 return;
8903 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
8904 // Implicit instantiation of static data members of class templates.
8905 if (Var->isStaticDataMember() &&
8906 Var->getInstantiatedFromStaticDataMember()) {
8907 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8908 assert(MSInfo && "Missing member specialization information?");
8909 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8910 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8911 MSInfo->setPointOfInstantiation(Loc);
8912 // This is a modification of an existing AST node. Notify listeners.
8913 if (ASTMutationListener *L = getASTMutationListener())
8914 L->StaticDataMemberInstantiated(Var);
8915 PendingInstantiations.push_back(std::make_pair(Var, Loc));
8919 // Keep track of used but undefined variables. We make a hole in
8920 // the warning for static const data members with in-line
8921 // initializers.
8922 if (Var->hasDefinition() == VarDecl::DeclarationOnly
8923 && Var->getLinkage() != ExternalLinkage
8924 && !(Var->isStaticDataMember() && Var->hasInit())) {
8925 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
8926 if (old.isInvalid()) old = Loc;
8929 D->setUsed(true);
8930 return;
8934 namespace {
8935 // Mark all of the declarations referenced
8936 // FIXME: Not fully implemented yet! We need to have a better understanding
8937 // of when we're entering
8938 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8939 Sema &S;
8940 SourceLocation Loc;
8942 public:
8943 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
8945 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
8947 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8948 bool TraverseRecordType(RecordType *T);
8952 bool MarkReferencedDecls::TraverseTemplateArgument(
8953 const TemplateArgument &Arg) {
8954 if (Arg.getKind() == TemplateArgument::Declaration) {
8955 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8958 return Inherited::TraverseTemplateArgument(Arg);
8961 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
8962 if (ClassTemplateSpecializationDecl *Spec
8963 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
8964 const TemplateArgumentList &Args = Spec->getTemplateArgs();
8965 return TraverseTemplateArguments(Args.data(), Args.size());
8968 return true;
8971 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
8972 MarkReferencedDecls Marker(*this, Loc);
8973 Marker.TraverseType(Context.getCanonicalType(T));
8976 namespace {
8977 /// \brief Helper class that marks all of the declarations referenced by
8978 /// potentially-evaluated subexpressions as "referenced".
8979 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
8980 Sema &S;
8982 public:
8983 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
8985 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
8987 void VisitDeclRefExpr(DeclRefExpr *E) {
8988 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
8991 void VisitMemberExpr(MemberExpr *E) {
8992 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
8993 Inherited::VisitMemberExpr(E);
8996 void VisitCXXNewExpr(CXXNewExpr *E) {
8997 if (E->getConstructor())
8998 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
8999 if (E->getOperatorNew())
9000 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9001 if (E->getOperatorDelete())
9002 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9003 Inherited::VisitCXXNewExpr(E);
9006 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9007 if (E->getOperatorDelete())
9008 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9009 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9010 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9011 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9012 S.MarkDeclarationReferenced(E->getLocStart(),
9013 S.LookupDestructor(Record));
9016 Inherited::VisitCXXDeleteExpr(E);
9019 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9020 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9021 Inherited::VisitCXXConstructExpr(E);
9024 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9025 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9028 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9029 Visit(E->getExpr());
9034 /// \brief Mark any declarations that appear within this expression or any
9035 /// potentially-evaluated subexpressions as "referenced".
9036 void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9037 EvaluatedExprMarker(*this).Visit(E);
9040 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
9041 /// of the program being compiled.
9043 /// This routine emits the given diagnostic when the code currently being
9044 /// type-checked is "potentially evaluated", meaning that there is a
9045 /// possibility that the code will actually be executable. Code in sizeof()
9046 /// expressions, code used only during overload resolution, etc., are not
9047 /// potentially evaluated. This routine will suppress such diagnostics or,
9048 /// in the absolutely nutty case of potentially potentially evaluated
9049 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
9050 /// later.
9052 /// This routine should be used for all diagnostics that describe the run-time
9053 /// behavior of a program, such as passing a non-POD value through an ellipsis.
9054 /// Failure to do so will likely result in spurious diagnostics or failures
9055 /// during overload resolution or within sizeof/alignof/typeof/typeid.
9056 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
9057 const PartialDiagnostic &PD) {
9058 switch (ExprEvalContexts.back().Context) {
9059 case Unevaluated:
9060 // The argument will never be evaluated, so don't complain.
9061 break;
9063 case PotentiallyEvaluated:
9064 case PotentiallyEvaluatedIfUsed:
9065 if (stmt && getCurFunctionOrMethodDecl()) {
9066 FunctionScopes.back()->PossiblyUnreachableDiags.
9067 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9069 else
9070 Diag(Loc, PD);
9072 return true;
9074 case PotentiallyPotentiallyEvaluated:
9075 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9076 break;
9079 return false;
9082 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9083 CallExpr *CE, FunctionDecl *FD) {
9084 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9085 return false;
9087 PartialDiagnostic Note =
9088 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9089 << FD->getDeclName() : PDiag();
9090 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
9092 if (RequireCompleteType(Loc, ReturnType,
9093 FD ?
9094 PDiag(diag::err_call_function_incomplete_return)
9095 << CE->getSourceRange() << FD->getDeclName() :
9096 PDiag(diag::err_call_incomplete_return)
9097 << CE->getSourceRange(),
9098 std::make_pair(NoteLoc, Note)))
9099 return true;
9101 return false;
9104 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
9105 // will prevent this condition from triggering, which is what we want.
9106 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9107 SourceLocation Loc;
9109 unsigned diagnostic = diag::warn_condition_is_assignment;
9110 bool IsOrAssign = false;
9112 if (isa<BinaryOperator>(E)) {
9113 BinaryOperator *Op = cast<BinaryOperator>(E);
9114 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
9115 return;
9117 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9119 // Greylist some idioms by putting them into a warning subcategory.
9120 if (ObjCMessageExpr *ME
9121 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9122 Selector Sel = ME->getSelector();
9124 // self = [<foo> init...]
9125 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
9126 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9128 // <foo> = [<bar> nextObject]
9129 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
9130 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9133 Loc = Op->getOperatorLoc();
9134 } else if (isa<CXXOperatorCallExpr>(E)) {
9135 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
9136 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
9137 return;
9139 IsOrAssign = Op->getOperator() == OO_PipeEqual;
9140 Loc = Op->getOperatorLoc();
9141 } else {
9142 // Not an assignment.
9143 return;
9146 Diag(Loc, diagnostic) << E->getSourceRange();
9148 SourceLocation Open = E->getSourceRange().getBegin();
9149 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9150 Diag(Loc, diag::note_condition_assign_silence)
9151 << FixItHint::CreateInsertion(Open, "(")
9152 << FixItHint::CreateInsertion(Close, ")");
9154 if (IsOrAssign)
9155 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9156 << FixItHint::CreateReplacement(Loc, "!=");
9157 else
9158 Diag(Loc, diag::note_condition_assign_to_comparison)
9159 << FixItHint::CreateReplacement(Loc, "==");
9162 /// \brief Redundant parentheses over an equality comparison can indicate
9163 /// that the user intended an assignment used as condition.
9164 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
9165 // Don't warn if the parens came from a macro.
9166 SourceLocation parenLoc = parenE->getLocStart();
9167 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9168 return;
9169 // Don't warn for dependent expressions.
9170 if (parenE->isTypeDependent())
9171 return;
9173 Expr *E = parenE->IgnoreParens();
9175 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
9176 if (opE->getOpcode() == BO_EQ &&
9177 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9178 == Expr::MLV_Valid) {
9179 SourceLocation Loc = opE->getOperatorLoc();
9181 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9182 Diag(Loc, diag::note_equality_comparison_silence)
9183 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9184 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
9185 Diag(Loc, diag::note_equality_comparison_to_assign)
9186 << FixItHint::CreateReplacement(Loc, "=");
9190 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
9191 DiagnoseAssignmentAsCondition(E);
9192 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9193 DiagnoseEqualityWithExtraParens(parenE);
9195 ExprResult result = CheckPlaceholderExpr(E);
9196 if (result.isInvalid()) return ExprError();
9197 E = result.take();
9199 if (!E->isTypeDependent()) {
9200 if (getLangOptions().CPlusPlus)
9201 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9203 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9204 if (ERes.isInvalid())
9205 return ExprError();
9206 E = ERes.take();
9208 QualType T = E->getType();
9209 if (!T->isScalarType()) { // C99 6.8.4.1p1
9210 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9211 << T << E->getSourceRange();
9212 return ExprError();
9216 return Owned(E);
9219 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9220 Expr *Sub) {
9221 if (!Sub)
9222 return ExprError();
9224 return CheckBooleanCondition(Sub, Loc);
9227 namespace {
9228 /// A visitor for rebuilding a call to an __unknown_any expression
9229 /// to have an appropriate type.
9230 struct RebuildUnknownAnyFunction
9231 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9233 Sema &S;
9235 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9237 ExprResult VisitStmt(Stmt *S) {
9238 llvm_unreachable("unexpected statement!");
9239 return ExprError();
9242 ExprResult VisitExpr(Expr *expr) {
9243 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9244 << expr->getSourceRange();
9245 return ExprError();
9248 /// Rebuild an expression which simply semantically wraps another
9249 /// expression which it shares the type and value kind of.
9250 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9251 ExprResult subResult = Visit(expr->getSubExpr());
9252 if (subResult.isInvalid()) return ExprError();
9254 Expr *subExpr = subResult.take();
9255 expr->setSubExpr(subExpr);
9256 expr->setType(subExpr->getType());
9257 expr->setValueKind(subExpr->getValueKind());
9258 assert(expr->getObjectKind() == OK_Ordinary);
9259 return expr;
9262 ExprResult VisitParenExpr(ParenExpr *paren) {
9263 return rebuildSugarExpr(paren);
9266 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9267 return rebuildSugarExpr(op);
9270 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9271 ExprResult subResult = Visit(op->getSubExpr());
9272 if (subResult.isInvalid()) return ExprError();
9274 Expr *subExpr = subResult.take();
9275 op->setSubExpr(subExpr);
9276 op->setType(S.Context.getPointerType(subExpr->getType()));
9277 assert(op->getValueKind() == VK_RValue);
9278 assert(op->getObjectKind() == OK_Ordinary);
9279 return op;
9282 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9283 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9285 expr->setType(decl->getType());
9287 assert(expr->getValueKind() == VK_RValue);
9288 if (S.getLangOptions().CPlusPlus &&
9289 !(isa<CXXMethodDecl>(decl) &&
9290 cast<CXXMethodDecl>(decl)->isInstance()))
9291 expr->setValueKind(VK_LValue);
9293 return expr;
9296 ExprResult VisitMemberExpr(MemberExpr *mem) {
9297 return resolveDecl(mem, mem->getMemberDecl());
9300 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9301 return resolveDecl(ref, ref->getDecl());
9306 /// Given a function expression of unknown-any type, try to rebuild it
9307 /// to have a function type.
9308 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9309 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9310 if (result.isInvalid()) return ExprError();
9311 return S.DefaultFunctionArrayConversion(result.take());
9314 namespace {
9315 /// A visitor for rebuilding an expression of type __unknown_anytype
9316 /// into one which resolves the type directly on the referring
9317 /// expression. Strict preservation of the original source
9318 /// structure is not a goal.
9319 struct RebuildUnknownAnyExpr
9320 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
9322 Sema &S;
9324 /// The current destination type.
9325 QualType DestType;
9327 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9328 : S(S), DestType(castType) {}
9330 ExprResult VisitStmt(Stmt *S) {
9331 llvm_unreachable("unexpected statement!");
9332 return ExprError();
9335 ExprResult VisitExpr(Expr *expr) {
9336 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9337 << expr->getSourceRange();
9338 return ExprError();
9341 ExprResult VisitCallExpr(CallExpr *call);
9342 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9344 /// Rebuild an expression which simply semantically wraps another
9345 /// expression which it shares the type and value kind of.
9346 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9347 ExprResult subResult = Visit(expr->getSubExpr());
9348 if (subResult.isInvalid()) return ExprError();
9349 Expr *subExpr = subResult.take();
9350 expr->setSubExpr(subExpr);
9351 expr->setType(subExpr->getType());
9352 expr->setValueKind(subExpr->getValueKind());
9353 assert(expr->getObjectKind() == OK_Ordinary);
9354 return expr;
9357 ExprResult VisitParenExpr(ParenExpr *paren) {
9358 return rebuildSugarExpr(paren);
9361 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9362 return rebuildSugarExpr(op);
9365 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9366 const PointerType *ptr = DestType->getAs<PointerType>();
9367 if (!ptr) {
9368 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9369 << op->getSourceRange();
9370 return ExprError();
9372 assert(op->getValueKind() == VK_RValue);
9373 assert(op->getObjectKind() == OK_Ordinary);
9374 op->setType(DestType);
9376 // Build the sub-expression as if it were an object of the pointee type.
9377 DestType = ptr->getPointeeType();
9378 ExprResult subResult = Visit(op->getSubExpr());
9379 if (subResult.isInvalid()) return ExprError();
9380 op->setSubExpr(subResult.take());
9381 return op;
9384 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
9386 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
9388 ExprResult VisitMemberExpr(MemberExpr *mem) {
9389 return resolveDecl(mem, mem->getMemberDecl());
9392 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9393 return resolveDecl(ref, ref->getDecl());
9398 /// Rebuilds a call expression which yielded __unknown_anytype.
9399 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9400 Expr *callee = call->getCallee();
9402 enum FnKind {
9403 FK_MemberFunction,
9404 FK_FunctionPointer,
9405 FK_BlockPointer
9408 FnKind kind;
9409 QualType type = callee->getType();
9410 if (type == S.Context.BoundMemberTy) {
9411 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9412 kind = FK_MemberFunction;
9413 type = Expr::findBoundMemberType(callee);
9414 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9415 type = ptr->getPointeeType();
9416 kind = FK_FunctionPointer;
9417 } else {
9418 type = type->castAs<BlockPointerType>()->getPointeeType();
9419 kind = FK_BlockPointer;
9421 const FunctionType *fnType = type->castAs<FunctionType>();
9423 // Verify that this is a legal result type of a function.
9424 if (DestType->isArrayType() || DestType->isFunctionType()) {
9425 unsigned diagID = diag::err_func_returning_array_function;
9426 if (kind == FK_BlockPointer)
9427 diagID = diag::err_block_returning_array_function;
9429 S.Diag(call->getExprLoc(), diagID)
9430 << DestType->isFunctionType() << DestType;
9431 return ExprError();
9434 // Otherwise, go ahead and set DestType as the call's result.
9435 call->setType(DestType.getNonLValueExprType(S.Context));
9436 call->setValueKind(Expr::getValueKindForType(DestType));
9437 assert(call->getObjectKind() == OK_Ordinary);
9439 // Rebuild the function type, replacing the result type with DestType.
9440 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9441 DestType = S.Context.getFunctionType(DestType,
9442 proto->arg_type_begin(),
9443 proto->getNumArgs(),
9444 proto->getExtProtoInfo());
9445 else
9446 DestType = S.Context.getFunctionNoProtoType(DestType,
9447 fnType->getExtInfo());
9449 // Rebuild the appropriate pointer-to-function type.
9450 switch (kind) {
9451 case FK_MemberFunction:
9452 // Nothing to do.
9453 break;
9455 case FK_FunctionPointer:
9456 DestType = S.Context.getPointerType(DestType);
9457 break;
9459 case FK_BlockPointer:
9460 DestType = S.Context.getBlockPointerType(DestType);
9461 break;
9464 // Finally, we can recurse.
9465 ExprResult calleeResult = Visit(callee);
9466 if (!calleeResult.isUsable()) return ExprError();
9467 call->setCallee(calleeResult.take());
9469 // Bind a temporary if necessary.
9470 return S.MaybeBindToTemporary(call);
9473 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
9474 ObjCMethodDecl *method = msg->getMethodDecl();
9475 assert(method && "__unknown_anytype message without result type?");
9477 // Verify that this is a legal result type of a call.
9478 if (DestType->isArrayType() || DestType->isFunctionType()) {
9479 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9480 << DestType->isFunctionType() << DestType;
9481 return ExprError();
9484 assert(method->getResultType() == S.Context.UnknownAnyTy);
9485 method->setResultType(DestType);
9487 // Change the type of the message.
9488 msg->setType(DestType.getNonReferenceType());
9489 msg->setValueKind(Expr::getValueKindForType(DestType));
9491 return S.MaybeBindToTemporary(msg);
9494 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
9495 // The only case we should ever see here is a function-to-pointer decay.
9496 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
9497 assert(ice->getValueKind() == VK_RValue);
9498 assert(ice->getObjectKind() == OK_Ordinary);
9500 ice->setType(DestType);
9502 // Rebuild the sub-expression as the pointee (function) type.
9503 DestType = DestType->castAs<PointerType>()->getPointeeType();
9505 ExprResult result = Visit(ice->getSubExpr());
9506 if (!result.isUsable()) return ExprError();
9508 ice->setSubExpr(result.take());
9509 return S.Owned(ice);
9512 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
9513 ExprValueKind valueKind = VK_LValue;
9514 QualType type = DestType;
9516 // We know how to make this work for certain kinds of decls:
9518 // - functions
9519 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
9520 // This is true because FunctionDecls must always have function
9521 // type, so we can't be resolving the entire thing at once.
9522 assert(type->isFunctionType());
9524 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9525 if (method->isInstance()) {
9526 valueKind = VK_RValue;
9527 type = S.Context.BoundMemberTy;
9530 // Function references aren't l-values in C.
9531 if (!S.getLangOptions().CPlusPlus)
9532 valueKind = VK_RValue;
9534 // - variables
9535 } else if (isa<VarDecl>(decl)) {
9536 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9537 type = refTy->getPointeeType();
9538 } else if (type->isFunctionType()) {
9539 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9540 << decl << expr->getSourceRange();
9541 return ExprError();
9544 // - nothing else
9545 } else {
9546 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9547 << decl << expr->getSourceRange();
9548 return ExprError();
9551 decl->setType(DestType);
9552 expr->setType(type);
9553 expr->setValueKind(valueKind);
9554 return S.Owned(expr);
9557 /// Check a cast of an unknown-any type. We intentionally only
9558 /// trigger this for C-style casts.
9559 ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9560 Expr *castExpr, CastKind &castKind,
9561 ExprValueKind &VK, CXXCastPath &path) {
9562 // Rewrite the casted expression from scratch.
9563 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9564 if (!result.isUsable()) return ExprError();
9566 castExpr = result.take();
9567 VK = castExpr->getValueKind();
9568 castKind = CK_NoOp;
9570 return castExpr;
9573 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9574 Expr *orig = e;
9575 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
9576 while (true) {
9577 e = e->IgnoreParenImpCasts();
9578 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
9579 e = call->getCallee();
9580 diagID = diag::err_uncasted_call_of_unknown_any;
9581 } else {
9582 break;
9586 SourceLocation loc;
9587 NamedDecl *d;
9588 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9589 loc = ref->getLocation();
9590 d = ref->getDecl();
9591 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9592 loc = mem->getMemberLoc();
9593 d = mem->getMemberDecl();
9594 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9595 diagID = diag::err_uncasted_call_of_unknown_any;
9596 loc = msg->getSelectorLoc();
9597 d = msg->getMethodDecl();
9598 assert(d && "unknown method returning __unknown_any?");
9599 } else {
9600 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9601 << e->getSourceRange();
9602 return ExprError();
9605 S.Diag(loc, diagID) << d << orig->getSourceRange();
9607 // Never recoverable.
9608 return ExprError();
9611 /// Check for operands with placeholder types and complain if found.
9612 /// Returns true if there was an error and no recovery was possible.
9613 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
9614 // Placeholder types are always *exactly* the appropriate builtin type.
9615 QualType type = E->getType();
9617 // Overloaded expressions.
9618 if (type == Context.OverloadTy)
9619 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
9620 E->getSourceRange(),
9621 QualType(),
9622 diag::err_ovl_unresolvable);
9624 // Bound member functions.
9625 if (type == Context.BoundMemberTy) {
9626 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9627 << E->getSourceRange();
9628 return ExprError();
9631 // Expressions of unknown type.
9632 if (type == Context.UnknownAnyTy)
9633 return diagnoseUnknownAnyExpr(*this, E);
9635 assert(!type->isPlaceholderType());
9636 return Owned(E);
9639 bool Sema::CheckCaseExpression(Expr *expr) {
9640 if (expr->isTypeDependent())
9641 return true;
9642 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9643 return expr->getType()->isIntegralOrEnumerationType();
9644 return false;