1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/DelayedDiagnostic.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/Sema/AnalysisBasedWarnings.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTMutationListener.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/EvaluatedExprVisitor.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/ExprObjC.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/PartialDiagnostic.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Lex/LiteralSupport.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Scope.h"
40 #include "clang/Sema/ScopeInfo.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/SemaFixItUtils.h"
43 #include "clang/Sema/Template.h"
44 #include "TreeTransform.h"
45 using namespace clang;
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
50 bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
69 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70 // Warn if this is used but marked unused.
71 if (D->hasAttr<UnusedAttr>()) {
72 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
73 if (!DC->hasAttr<UnusedAttr>())
74 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
78 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
79 NamedDecl *D, SourceLocation Loc,
80 const ObjCInterfaceDecl *UnknownObjCClass) {
81 // See if this declaration is unavailable or deprecated.
83 AvailabilityResult Result = D->getAvailability(&Message);
84 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85 if (Result == AR_Available) {
86 const DeclContext *DC = ECD->getDeclContext();
87 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88 Result = TheEnumDecl->getAvailability(&Message);
91 const ObjCPropertyDecl *ObjCPDecl = 0;
92 if (Result == AR_Deprecated || Result == AR_Unavailable) {
93 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
94 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
95 AvailabilityResult PDeclResult = PD->getAvailability(0);
96 if (PDeclResult == Result)
104 case AR_NotYetIntroduced:
108 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
112 if (S.getCurContextAvailability() != AR_Unavailable) {
113 if (Message.empty()) {
114 if (!UnknownObjCClass) {
115 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
117 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
118 << ObjCPDecl->getDeclName() << 1;
121 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
125 S.Diag(Loc, diag::err_unavailable_message)
126 << D->getDeclName() << Message;
127 S.Diag(D->getLocation(), diag::note_unavailable_here)
128 << isa<FunctionDecl>(D) << false;
130 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
131 << ObjCPDecl->getDeclName() << 1;
138 /// \brief Emit a note explaining that this function is deleted or unavailable.
139 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
142 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
143 // If the method was explicitly defaulted, point at that declaration.
144 if (!Method->isImplicit())
145 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
147 // Try to diagnose why this special member function was implicitly
148 // deleted. This might fail, if that reason no longer applies.
149 CXXSpecialMember CSM = getSpecialMember(Method);
150 if (CSM != CXXInvalid)
151 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
156 Diag(Decl->getLocation(), diag::note_unavailable_here)
157 << 1 << Decl->isDeleted();
160 /// \brief Determine whether a FunctionDecl was ever declared with an
161 /// explicit storage class.
162 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
163 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
164 E = D->redecls_end();
166 if (I->getStorageClassAsWritten() != SC_None)
172 /// \brief Check whether we're in an extern inline function and referring to a
173 /// variable or function with internal linkage (C11 6.7.4p3).
175 /// This is only a warning because we used to silently accept this code, but
176 /// in many cases it will not behave correctly. This is not enabled in C++ mode
177 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
178 /// and so while there may still be user mistakes, most of the time we can't
179 /// prove that there are errors.
180 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
182 SourceLocation Loc) {
183 // This is disabled under C++; there are too many ways for this to fire in
184 // contexts where the warning is a false positive, or where it is technically
185 // correct but benign.
186 if (S.getLangOpts().CPlusPlus)
189 // Check if this is an inlined function or method.
190 FunctionDecl *Current = S.getCurFunctionDecl();
193 if (!Current->isInlined())
195 if (Current->getLinkage() != ExternalLinkage)
198 // Check if the decl has internal linkage.
199 if (D->getLinkage() != InternalLinkage)
202 // Downgrade from ExtWarn to Extension if
203 // (1) the supposedly external inline function is in the main file,
204 // and probably won't be included anywhere else.
205 // (2) the thing we're referencing is a pure function.
206 // (3) the thing we're referencing is another inline function.
207 // This last can give us false negatives, but it's better than warning on
208 // wrappers for simple C library functions.
209 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
210 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
211 if (!DowngradeWarning && UsedFn)
212 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
214 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
215 : diag::warn_internal_in_extern_inline)
216 << /*IsVar=*/!UsedFn << D;
218 // Suggest "static" on the inline function, if possible.
219 if (!hasAnyExplicitStorageClass(Current)) {
220 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
221 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
222 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
223 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
226 S.Diag(D->getCanonicalDecl()->getLocation(),
227 diag::note_internal_decl_declared_here)
231 /// \brief Determine whether the use of this declaration is valid, and
232 /// emit any corresponding diagnostics.
234 /// This routine diagnoses various problems with referencing
235 /// declarations that can occur when using a declaration. For example,
236 /// it might warn if a deprecated or unavailable declaration is being
237 /// used, or produce an error (and return true) if a C++0x deleted
238 /// function is being used.
240 /// \returns true if there was an error (this declaration cannot be
241 /// referenced), false otherwise.
243 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
244 const ObjCInterfaceDecl *UnknownObjCClass) {
245 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
246 // If there were any diagnostics suppressed by template argument deduction,
248 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
249 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
250 if (Pos != SuppressedDiagnostics.end()) {
251 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
252 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
253 Diag(Suppressed[I].first, Suppressed[I].second);
255 // Clear out the list of suppressed diagnostics, so that we don't emit
256 // them again for this specialization. However, we don't obsolete this
257 // entry from the table, because we want to avoid ever emitting these
258 // diagnostics again.
263 // See if this is an auto-typed variable whose initializer we are parsing.
264 if (ParsingInitForAutoVars.count(D)) {
265 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
270 // See if this is a deleted function.
271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
272 if (FD->isDeleted()) {
273 Diag(Loc, diag::err_deleted_function_use);
274 NoteDeletedFunction(FD);
278 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
280 DiagnoseUnusedOfDecl(*this, D, Loc);
282 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
287 /// \brief Retrieve the message suffix that should be added to a
288 /// diagnostic complaining about the given function being deleted or
290 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
291 // FIXME: C++0x implicitly-deleted special member functions could be
292 // detected here so that we could improve diagnostics to say, e.g.,
293 // "base class 'A' had a deleted copy constructor".
295 return std::string();
298 if (FD->getAvailability(&Message))
299 return ": " + Message;
301 return std::string();
304 /// DiagnoseSentinelCalls - This routine checks whether a call or
305 /// message-send is to a declaration with the sentinel attribute, and
306 /// if so, it checks that the requirements of the sentinel are
308 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
309 Expr **args, unsigned numArgs) {
310 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
314 // The number of formal parameters of the declaration.
315 unsigned numFormalParams;
317 // The kind of declaration. This is also an index into a %select in
319 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
321 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
322 numFormalParams = MD->param_size();
323 calleeType = CT_Method;
324 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
325 numFormalParams = FD->param_size();
326 calleeType = CT_Function;
327 } else if (isa<VarDecl>(D)) {
328 QualType type = cast<ValueDecl>(D)->getType();
329 const FunctionType *fn = 0;
330 if (const PointerType *ptr = type->getAs<PointerType>()) {
331 fn = ptr->getPointeeType()->getAs<FunctionType>();
333 calleeType = CT_Function;
334 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
335 fn = ptr->getPointeeType()->castAs<FunctionType>();
336 calleeType = CT_Block;
341 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
342 numFormalParams = proto->getNumArgs();
350 // "nullPos" is the number of formal parameters at the end which
351 // effectively count as part of the variadic arguments. This is
352 // useful if you would prefer to not have *any* formal parameters,
353 // but the language forces you to have at least one.
354 unsigned nullPos = attr->getNullPos();
355 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
356 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
358 // The number of arguments which should follow the sentinel.
359 unsigned numArgsAfterSentinel = attr->getSentinel();
361 // If there aren't enough arguments for all the formal parameters,
362 // the sentinel, and the args after the sentinel, complain.
363 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
364 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
365 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
369 // Otherwise, find the sentinel expression.
370 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
371 if (!sentinelExpr) return;
372 if (sentinelExpr->isValueDependent()) return;
373 if (Context.isSentinelNullExpr(sentinelExpr)) return;
375 // Pick a reasonable string to insert. Optimistically use 'nil' or
376 // 'NULL' if those are actually defined in the context. Only use
377 // 'nil' for ObjC methods, where it's much more likely that the
378 // variadic arguments form a list of object pointers.
379 SourceLocation MissingNilLoc
380 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
381 std::string NullValue;
382 if (calleeType == CT_Method &&
383 PP.getIdentifierInfo("nil")->hasMacroDefinition())
385 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
388 NullValue = "(void*) 0";
390 if (MissingNilLoc.isInvalid())
391 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
393 Diag(MissingNilLoc, diag::warn_missing_sentinel)
395 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
396 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
399 SourceRange Sema::getExprRange(Expr *E) const {
400 return E ? E->getSourceRange() : SourceRange();
403 //===----------------------------------------------------------------------===//
404 // Standard Promotions and Conversions
405 //===----------------------------------------------------------------------===//
407 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
408 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
409 // Handle any placeholder expressions which made it here.
410 if (E->getType()->isPlaceholderType()) {
411 ExprResult result = CheckPlaceholderExpr(E);
412 if (result.isInvalid()) return ExprError();
416 QualType Ty = E->getType();
417 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
419 if (Ty->isFunctionType())
420 E = ImpCastExprToType(E, Context.getPointerType(Ty),
421 CK_FunctionToPointerDecay).take();
422 else if (Ty->isArrayType()) {
423 // In C90 mode, arrays only promote to pointers if the array expression is
424 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
425 // type 'array of type' is converted to an expression that has type 'pointer
426 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
427 // that has type 'array of type' ...". The relevant change is "an lvalue"
428 // (C90) to "an expression" (C99).
431 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
432 // T" can be converted to an rvalue of type "pointer to T".
434 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
435 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
436 CK_ArrayToPointerDecay).take();
441 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
442 // Check to see if we are dereferencing a null pointer. If so,
443 // and if not volatile-qualified, this is undefined behavior that the
444 // optimizer will delete, so warn about it. People sometimes try to use this
445 // to get a deterministic trap and are surprised by clang's behavior. This
446 // only handles the pattern "*null", which is a very syntactic check.
447 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
448 if (UO->getOpcode() == UO_Deref &&
449 UO->getSubExpr()->IgnoreParenCasts()->
450 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
451 !UO->getType().isVolatileQualified()) {
452 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
453 S.PDiag(diag::warn_indirection_through_null)
454 << UO->getSubExpr()->getSourceRange());
455 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
456 S.PDiag(diag::note_indirection_through_null));
460 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
461 // Handle any placeholder expressions which made it here.
462 if (E->getType()->isPlaceholderType()) {
463 ExprResult result = CheckPlaceholderExpr(E);
464 if (result.isInvalid()) return ExprError();
468 // C++ [conv.lval]p1:
469 // A glvalue of a non-function, non-array type T can be
470 // converted to a prvalue.
471 if (!E->isGLValue()) return Owned(E);
473 QualType T = E->getType();
474 assert(!T.isNull() && "r-value conversion on typeless expression?");
476 // We don't want to throw lvalue-to-rvalue casts on top of
477 // expressions of certain types in C++.
478 if (getLangOpts().CPlusPlus &&
479 (E->getType() == Context.OverloadTy ||
480 T->isDependentType() ||
484 // The C standard is actually really unclear on this point, and
485 // DR106 tells us what the result should be but not why. It's
486 // generally best to say that void types just doesn't undergo
487 // lvalue-to-rvalue at all. Note that expressions of unqualified
488 // 'void' type are never l-values, but qualified void can be.
492 CheckForNullPointerDereference(*this, E);
494 // C++ [conv.lval]p1:
495 // [...] If T is a non-class type, the type of the prvalue is the
496 // cv-unqualified version of T. Otherwise, the type of the
500 // If the lvalue has qualified type, the value has the unqualified
501 // version of the type of the lvalue; otherwise, the value has the
502 // type of the lvalue.
503 if (T.hasQualifiers())
504 T = T.getUnqualifiedType();
506 UpdateMarkingForLValueToRValue(E);
508 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
512 // ... if the lvalue has atomic type, the value has the non-atomic version
513 // of the type of the lvalue ...
514 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
515 T = Atomic->getValueType().getUnqualifiedType();
516 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
517 Res.get(), 0, VK_RValue));
523 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
524 ExprResult Res = DefaultFunctionArrayConversion(E);
527 Res = DefaultLvalueConversion(Res.take());
534 /// UsualUnaryConversions - Performs various conversions that are common to most
535 /// operators (C99 6.3). The conversions of array and function types are
536 /// sometimes suppressed. For example, the array->pointer conversion doesn't
537 /// apply if the array is an argument to the sizeof or address (&) operators.
538 /// In these instances, this routine should *not* be called.
539 ExprResult Sema::UsualUnaryConversions(Expr *E) {
540 // First, convert to an r-value.
541 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
546 QualType Ty = E->getType();
547 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
549 // Half FP is a bit different: it's a storage-only type, meaning that any
550 // "use" of it should be promoted to float.
551 if (Ty->isHalfType())
552 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
554 // Try to perform integral promotions if the object has a theoretically
556 if (Ty->isIntegralOrUnscopedEnumerationType()) {
559 // The following may be used in an expression wherever an int or
560 // unsigned int may be used:
561 // - an object or expression with an integer type whose integer
562 // conversion rank is less than or equal to the rank of int
564 // - A bit-field of type _Bool, int, signed int, or unsigned int.
566 // If an int can represent all values of the original type, the
567 // value is converted to an int; otherwise, it is converted to an
568 // unsigned int. These are called the integer promotions. All
569 // other types are unchanged by the integer promotions.
571 QualType PTy = Context.isPromotableBitField(E);
573 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
576 if (Ty->isPromotableIntegerType()) {
577 QualType PT = Context.getPromotedIntegerType(Ty);
578 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
585 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
586 /// do not have a prototype. Arguments that have type float are promoted to
587 /// double. All other argument types are converted by UsualUnaryConversions().
588 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
589 QualType Ty = E->getType();
590 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
592 ExprResult Res = UsualUnaryConversions(E);
597 // If this is a 'float' (CVR qualified or typedef) promote to double.
598 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
599 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
601 // C++ performs lvalue-to-rvalue conversion as a default argument
602 // promotion, even on class types, but note:
603 // C++11 [conv.lval]p2:
604 // When an lvalue-to-rvalue conversion occurs in an unevaluated
605 // operand or a subexpression thereof the value contained in the
606 // referenced object is not accessed. Otherwise, if the glvalue
607 // has a class type, the conversion copy-initializes a temporary
608 // of type T from the glvalue and the result of the conversion
609 // is a prvalue for the temporary.
610 // FIXME: add some way to gate this entire thing for correctness in
611 // potentially potentially evaluated contexts.
612 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
613 ExprResult Temp = PerformCopyInitialization(
614 InitializedEntity::InitializeTemporary(E->getType()),
617 if (Temp.isInvalid())
625 /// Determine the degree of POD-ness for an expression.
626 /// Incomplete types are considered POD, since this check can be performed
627 /// when we're in an unevaluated context.
628 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
629 if (Ty->isIncompleteType()) {
630 if (Ty->isObjCObjectType())
635 if (Ty.isCXX98PODType(Context))
638 // C++0x [expr.call]p7:
639 // Passing a potentially-evaluated argument of class type (Clause 9)
640 // having a non-trivial copy constructor, a non-trivial move constructor,
641 // or a non-trivial destructor, with no corresponding parameter,
642 // is conditionally-supported with implementation-defined semantics.
643 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
644 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
645 if (Record->hasTrivialCopyConstructor() &&
646 Record->hasTrivialMoveConstructor() &&
647 Record->hasTrivialDestructor())
648 return VAK_ValidInCXX11;
650 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
655 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
656 // Don't allow one to pass an Objective-C interface to a vararg.
657 const QualType & Ty = E->getType();
659 // Complain about passing non-POD types through varargs.
660 switch (isValidVarArgType(Ty)) {
663 case VAK_ValidInCXX11:
664 DiagRuntimeBehavior(E->getLocStart(), 0,
665 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
666 << E->getType() << CT);
669 if (Ty->isObjCObjectType())
670 return DiagRuntimeBehavior(E->getLocStart(), 0,
671 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
674 return DiagRuntimeBehavior(E->getLocStart(), 0,
675 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
676 << getLangOpts().CPlusPlus0x << Ty << CT);
679 // c++ rules are enforced elsewhere.
683 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
684 /// will create a trap if the resulting type is not a POD type.
685 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
686 FunctionDecl *FDecl) {
687 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
688 // Strip the unbridged-cast placeholder expression off, if applicable.
689 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
690 (CT == VariadicMethod ||
691 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
692 E = stripARCUnbridgedCast(E);
694 // Otherwise, do normal placeholder checking.
696 ExprResult ExprRes = CheckPlaceholderExpr(E);
697 if (ExprRes.isInvalid())
703 ExprResult ExprRes = DefaultArgumentPromotion(E);
704 if (ExprRes.isInvalid())
708 // Diagnostics regarding non-POD argument types are
709 // emitted along with format string checking in Sema::CheckFunctionCall().
710 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
711 // Turn this into a trap.
713 SourceLocation TemplateKWLoc;
715 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
717 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
719 if (TrapFn.isInvalid())
722 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
723 E->getLocStart(), MultiExprArg(),
725 if (Call.isInvalid())
728 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
730 if (Comma.isInvalid())
735 if (!getLangOpts().CPlusPlus &&
736 RequireCompleteType(E->getExprLoc(), E->getType(),
737 diag::err_call_incomplete_argument))
743 /// \brief Converts an integer to complex float type. Helper function of
744 /// UsualArithmeticConversions()
746 /// \return false if the integer expression is an integer type and is
747 /// successfully converted to the complex type.
748 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
749 ExprResult &ComplexExpr,
753 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
754 if (SkipCast) return false;
755 if (IntTy->isIntegerType()) {
756 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
757 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
758 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
759 CK_FloatingRealToComplex);
761 assert(IntTy->isComplexIntegerType());
762 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
763 CK_IntegralComplexToFloatingComplex);
768 /// \brief Takes two complex float types and converts them to the same type.
769 /// Helper function of UsualArithmeticConversions()
771 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
772 ExprResult &RHS, QualType LHSType,
775 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
778 // _Complex float -> _Complex double
780 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
784 // _Complex float -> _Complex double
785 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
789 /// \brief Converts otherExpr to complex float and promotes complexExpr if
790 /// necessary. Helper function of UsualArithmeticConversions()
791 static QualType handleOtherComplexFloatConversion(Sema &S,
792 ExprResult &ComplexExpr,
793 ExprResult &OtherExpr,
796 bool ConvertComplexExpr,
797 bool ConvertOtherExpr) {
798 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
800 // If just the complexExpr is complex, the otherExpr needs to be converted,
801 // and the complexExpr might need to be promoted.
802 if (order > 0) { // complexExpr is wider
803 // float -> _Complex double
804 if (ConvertOtherExpr) {
805 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
806 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
807 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
808 CK_FloatingRealToComplex);
813 // otherTy is at least as wide. Find its corresponding complex type.
814 QualType result = (order == 0 ? ComplexTy :
815 S.Context.getComplexType(OtherTy));
817 // double -> _Complex double
818 if (ConvertOtherExpr)
819 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
820 CK_FloatingRealToComplex);
822 // _Complex float -> _Complex double
823 if (ConvertComplexExpr && order < 0)
824 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
825 CK_FloatingComplexCast);
830 /// \brief Handle arithmetic conversion with complex types. Helper function of
831 /// UsualArithmeticConversions()
832 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
833 ExprResult &RHS, QualType LHSType,
836 // if we have an integer operand, the result is the complex type.
837 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
840 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
841 /*skipCast*/IsCompAssign))
844 // This handles complex/complex, complex/float, or float/complex.
845 // When both operands are complex, the shorter operand is converted to the
846 // type of the longer, and that is the type of the result. This corresponds
847 // to what is done when combining two real floating-point operands.
848 // The fun begins when size promotion occur across type domains.
849 // From H&S 6.3.4: When one operand is complex and the other is a real
850 // floating-point type, the less precise type is converted, within it's
851 // real or complex domain, to the precision of the other type. For example,
852 // when combining a "long double" with a "double _Complex", the
853 // "double _Complex" is promoted to "long double _Complex".
855 bool LHSComplexFloat = LHSType->isComplexType();
856 bool RHSComplexFloat = RHSType->isComplexType();
858 // If both are complex, just cast to the more precise type.
859 if (LHSComplexFloat && RHSComplexFloat)
860 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
864 // If only one operand is complex, promote it if necessary and convert the
865 // other operand to complex.
867 return handleOtherComplexFloatConversion(
868 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
869 /*convertOtherExpr*/ true);
871 assert(RHSComplexFloat);
872 return handleOtherComplexFloatConversion(
873 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
874 /*convertOtherExpr*/ !IsCompAssign);
877 /// \brief Hande arithmetic conversion from integer to float. Helper function
878 /// of UsualArithmeticConversions()
879 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
881 QualType FloatTy, QualType IntTy,
882 bool ConvertFloat, bool ConvertInt) {
883 if (IntTy->isIntegerType()) {
885 // Convert intExpr to the lhs floating point type.
886 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
887 CK_IntegralToFloating);
891 // Convert both sides to the appropriate complex float.
892 assert(IntTy->isComplexIntegerType());
893 QualType result = S.Context.getComplexType(FloatTy);
895 // _Complex int -> _Complex float
897 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
898 CK_IntegralComplexToFloatingComplex);
900 // float -> _Complex float
902 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
903 CK_FloatingRealToComplex);
908 /// \brief Handle arithmethic conversion with floating point types. Helper
909 /// function of UsualArithmeticConversions()
910 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
911 ExprResult &RHS, QualType LHSType,
912 QualType RHSType, bool IsCompAssign) {
913 bool LHSFloat = LHSType->isRealFloatingType();
914 bool RHSFloat = RHSType->isRealFloatingType();
916 // If we have two real floating types, convert the smaller operand
917 // to the bigger result.
918 if (LHSFloat && RHSFloat) {
919 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
921 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
925 assert(order < 0 && "illegal float comparison");
927 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
932 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
933 /*convertFloat=*/!IsCompAssign,
934 /*convertInt=*/ true);
936 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
937 /*convertInt=*/ true,
938 /*convertFloat=*/!IsCompAssign);
941 /// \brief Handle conversions with GCC complex int extension. Helper function
942 /// of UsualArithmeticConversions()
943 // FIXME: if the operands are (int, _Complex long), we currently
944 // don't promote the complex. Also, signedness?
945 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
946 ExprResult &RHS, QualType LHSType,
949 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
950 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
952 if (LHSComplexInt && RHSComplexInt) {
953 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
954 RHSComplexInt->getElementType());
955 assert(order && "inequal types with equal element ordering");
957 // _Complex int -> _Complex long
958 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
963 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
968 // int -> _Complex int
969 // FIXME: This needs to take integer ranks into account
970 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
972 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
976 assert(RHSComplexInt);
977 // int -> _Complex int
978 // FIXME: This needs to take integer ranks into account
980 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
982 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
987 /// \brief Handle integer arithmetic conversions. Helper function of
988 /// UsualArithmeticConversions()
989 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
990 ExprResult &RHS, QualType LHSType,
991 QualType RHSType, bool IsCompAssign) {
992 // The rules for this case are in C99 6.3.1.8
993 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
994 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
995 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
996 if (LHSSigned == RHSSigned) {
997 // Same signedness; use the higher-ranked type
999 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1001 } else if (!IsCompAssign)
1002 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1004 } else if (order != (LHSSigned ? 1 : -1)) {
1005 // The unsigned type has greater than or equal rank to the
1006 // signed type, so use the unsigned type
1008 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1010 } else if (!IsCompAssign)
1011 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1013 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1014 // The two types are different widths; if we are here, that
1015 // means the signed type is larger than the unsigned type, so
1016 // use the signed type.
1018 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1020 } else if (!IsCompAssign)
1021 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1024 // The signed type is higher-ranked than the unsigned type,
1025 // but isn't actually any bigger (like unsigned int and long
1026 // on most 32-bit systems). Use the unsigned type corresponding
1027 // to the signed type.
1029 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1030 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
1032 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
1037 /// UsualArithmeticConversions - Performs various conversions that are common to
1038 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1039 /// routine returns the first non-arithmetic type found. The client is
1040 /// responsible for emitting appropriate error diagnostics.
1041 /// FIXME: verify the conversion rules for "complex int" are consistent with
1043 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1044 bool IsCompAssign) {
1045 if (!IsCompAssign) {
1046 LHS = UsualUnaryConversions(LHS.take());
1047 if (LHS.isInvalid())
1051 RHS = UsualUnaryConversions(RHS.take());
1052 if (RHS.isInvalid())
1055 // For conversion purposes, we ignore any qualifiers.
1056 // For example, "const float" and "float" are equivalent.
1058 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1060 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1062 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1063 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1064 LHSType = AtomicLHS->getValueType();
1066 // If both types are identical, no conversion is needed.
1067 if (LHSType == RHSType)
1070 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1071 // The caller can deal with this (e.g. pointer + int).
1072 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1075 // Apply unary and bitfield promotions to the LHS's type.
1076 QualType LHSUnpromotedType = LHSType;
1077 if (LHSType->isPromotableIntegerType())
1078 LHSType = Context.getPromotedIntegerType(LHSType);
1079 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1080 if (!LHSBitfieldPromoteTy.isNull())
1081 LHSType = LHSBitfieldPromoteTy;
1082 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1083 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1085 // If both types are identical, no conversion is needed.
1086 if (LHSType == RHSType)
1089 // At this point, we have two different arithmetic types.
1091 // Handle complex types first (C99 6.3.1.8p1).
1092 if (LHSType->isComplexType() || RHSType->isComplexType())
1093 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1096 // Now handle "real" floating types (i.e. float, double, long double).
1097 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1098 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1101 // Handle GCC complex int extension.
1102 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1103 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1106 // Finally, we have two differing integer types.
1107 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
1111 //===----------------------------------------------------------------------===//
1112 // Semantic Analysis for various Expression Types
1113 //===----------------------------------------------------------------------===//
1117 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1118 SourceLocation DefaultLoc,
1119 SourceLocation RParenLoc,
1120 Expr *ControllingExpr,
1121 MultiTypeArg ArgTypes,
1122 MultiExprArg ArgExprs) {
1123 unsigned NumAssocs = ArgTypes.size();
1124 assert(NumAssocs == ArgExprs.size());
1126 ParsedType *ParsedTypes = ArgTypes.data();
1127 Expr **Exprs = ArgExprs.data();
1129 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1130 for (unsigned i = 0; i < NumAssocs; ++i) {
1132 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1137 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1138 ControllingExpr, Types, Exprs,
1145 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1146 SourceLocation DefaultLoc,
1147 SourceLocation RParenLoc,
1148 Expr *ControllingExpr,
1149 TypeSourceInfo **Types,
1151 unsigned NumAssocs) {
1152 bool TypeErrorFound = false,
1153 IsResultDependent = ControllingExpr->isTypeDependent(),
1154 ContainsUnexpandedParameterPack
1155 = ControllingExpr->containsUnexpandedParameterPack();
1157 for (unsigned i = 0; i < NumAssocs; ++i) {
1158 if (Exprs[i]->containsUnexpandedParameterPack())
1159 ContainsUnexpandedParameterPack = true;
1162 if (Types[i]->getType()->containsUnexpandedParameterPack())
1163 ContainsUnexpandedParameterPack = true;
1165 if (Types[i]->getType()->isDependentType()) {
1166 IsResultDependent = true;
1168 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1169 // complete object type other than a variably modified type."
1171 if (Types[i]->getType()->isIncompleteType())
1172 D = diag::err_assoc_type_incomplete;
1173 else if (!Types[i]->getType()->isObjectType())
1174 D = diag::err_assoc_type_nonobject;
1175 else if (Types[i]->getType()->isVariablyModifiedType())
1176 D = diag::err_assoc_type_variably_modified;
1179 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1180 << Types[i]->getTypeLoc().getSourceRange()
1181 << Types[i]->getType();
1182 TypeErrorFound = true;
1185 // C11 6.5.1.1p2 "No two generic associations in the same generic
1186 // selection shall specify compatible types."
1187 for (unsigned j = i+1; j < NumAssocs; ++j)
1188 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1189 Context.typesAreCompatible(Types[i]->getType(),
1190 Types[j]->getType())) {
1191 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1192 diag::err_assoc_compatible_types)
1193 << Types[j]->getTypeLoc().getSourceRange()
1194 << Types[j]->getType()
1195 << Types[i]->getType();
1196 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1197 diag::note_compat_assoc)
1198 << Types[i]->getTypeLoc().getSourceRange()
1199 << Types[i]->getType();
1200 TypeErrorFound = true;
1208 // If we determined that the generic selection is result-dependent, don't
1209 // try to compute the result expression.
1210 if (IsResultDependent)
1211 return Owned(new (Context) GenericSelectionExpr(
1212 Context, KeyLoc, ControllingExpr,
1213 llvm::makeArrayRef(Types, NumAssocs),
1214 llvm::makeArrayRef(Exprs, NumAssocs),
1215 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1217 SmallVector<unsigned, 1> CompatIndices;
1218 unsigned DefaultIndex = -1U;
1219 for (unsigned i = 0; i < NumAssocs; ++i) {
1222 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1223 Types[i]->getType()))
1224 CompatIndices.push_back(i);
1227 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1228 // type compatible with at most one of the types named in its generic
1229 // association list."
1230 if (CompatIndices.size() > 1) {
1231 // We strip parens here because the controlling expression is typically
1232 // parenthesized in macro definitions.
1233 ControllingExpr = ControllingExpr->IgnoreParens();
1234 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1235 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1236 << (unsigned) CompatIndices.size();
1237 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1238 E = CompatIndices.end(); I != E; ++I) {
1239 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1240 diag::note_compat_assoc)
1241 << Types[*I]->getTypeLoc().getSourceRange()
1242 << Types[*I]->getType();
1247 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1248 // its controlling expression shall have type compatible with exactly one of
1249 // the types named in its generic association list."
1250 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1251 // We strip parens here because the controlling expression is typically
1252 // parenthesized in macro definitions.
1253 ControllingExpr = ControllingExpr->IgnoreParens();
1254 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1255 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1259 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1260 // type name that is compatible with the type of the controlling expression,
1261 // then the result expression of the generic selection is the expression
1262 // in that generic association. Otherwise, the result expression of the
1263 // generic selection is the expression in the default generic association."
1264 unsigned ResultIndex =
1265 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1267 return Owned(new (Context) GenericSelectionExpr(
1268 Context, KeyLoc, ControllingExpr,
1269 llvm::makeArrayRef(Types, NumAssocs),
1270 llvm::makeArrayRef(Exprs, NumAssocs),
1271 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1275 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1276 /// location of the token and the offset of the ud-suffix within it.
1277 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1279 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1283 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1284 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1285 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1286 IdentifierInfo *UDSuffix,
1287 SourceLocation UDSuffixLoc,
1288 ArrayRef<Expr*> Args,
1289 SourceLocation LitEndLoc) {
1290 assert(Args.size() <= 2 && "too many arguments for literal operator");
1293 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1294 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1295 if (ArgTy[ArgIdx]->isArrayType())
1296 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1299 DeclarationName OpName =
1300 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1301 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1302 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1304 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1305 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1306 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1309 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1312 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1313 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1314 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1315 /// multiple tokens. However, the common case is that StringToks points to one
1319 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1321 assert(NumStringToks && "Must have at least one string!");
1323 StringLiteralParser Literal(StringToks, NumStringToks, PP);
1324 if (Literal.hadError)
1327 SmallVector<SourceLocation, 4> StringTokLocs;
1328 for (unsigned i = 0; i != NumStringToks; ++i)
1329 StringTokLocs.push_back(StringToks[i].getLocation());
1331 QualType StrTy = Context.CharTy;
1332 if (Literal.isWide())
1333 StrTy = Context.getWCharType();
1334 else if (Literal.isUTF16())
1335 StrTy = Context.Char16Ty;
1336 else if (Literal.isUTF32())
1337 StrTy = Context.Char32Ty;
1338 else if (Literal.isPascal())
1339 StrTy = Context.UnsignedCharTy;
1341 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1342 if (Literal.isWide())
1343 Kind = StringLiteral::Wide;
1344 else if (Literal.isUTF8())
1345 Kind = StringLiteral::UTF8;
1346 else if (Literal.isUTF16())
1347 Kind = StringLiteral::UTF16;
1348 else if (Literal.isUTF32())
1349 Kind = StringLiteral::UTF32;
1351 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1352 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1355 // Get an array type for the string, according to C99 6.4.5. This includes
1356 // the nul terminator character as well as the string length for pascal
1358 StrTy = Context.getConstantArrayType(StrTy,
1359 llvm::APInt(32, Literal.GetNumStringChars()+1),
1360 ArrayType::Normal, 0);
1362 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1363 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1364 Kind, Literal.Pascal, StrTy,
1366 StringTokLocs.size());
1367 if (Literal.getUDSuffix().empty())
1370 // We're building a user-defined literal.
1371 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1372 SourceLocation UDSuffixLoc =
1373 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1374 Literal.getUDSuffixOffset());
1376 // Make sure we're allowed user-defined literals here.
1378 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1380 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1381 // operator "" X (str, len)
1382 QualType SizeType = Context.getSizeType();
1383 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1384 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1386 Expr *Args[] = { Lit, LenArg };
1387 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1388 Args, StringTokLocs.back());
1392 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1394 const CXXScopeSpec *SS) {
1395 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1396 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1399 /// BuildDeclRefExpr - Build an expression that references a
1400 /// declaration that does not require a closure capture.
1402 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1403 const DeclarationNameInfo &NameInfo,
1404 const CXXScopeSpec *SS) {
1405 if (getLangOpts().CUDA)
1406 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1407 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1408 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1409 CalleeTarget = IdentifyCUDATarget(Callee);
1410 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1411 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1412 << CalleeTarget << D->getIdentifier() << CallerTarget;
1413 Diag(D->getLocation(), diag::note_previous_decl)
1414 << D->getIdentifier();
1419 bool refersToEnclosingScope =
1420 (CurContext != D->getDeclContext() &&
1421 D->getDeclContext()->isFunctionOrMethod());
1423 DeclRefExpr *E = DeclRefExpr::Create(Context,
1424 SS ? SS->getWithLocInContext(Context)
1425 : NestedNameSpecifierLoc(),
1427 D, refersToEnclosingScope,
1430 MarkDeclRefReferenced(E);
1432 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1433 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1434 DiagnosticsEngine::Level Level =
1435 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1437 if (Level != DiagnosticsEngine::Ignored)
1438 getCurFunction()->recordUseOfWeak(E);
1441 // Just in case we're building an illegal pointer-to-member.
1442 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1443 if (FD && FD->isBitField())
1444 E->setObjectKind(OK_BitField);
1449 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1450 /// possibly a list of template arguments.
1452 /// If this produces template arguments, it is permitted to call
1453 /// DecomposeTemplateName.
1455 /// This actually loses a lot of source location information for
1456 /// non-standard name kinds; we should consider preserving that in
1459 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1460 TemplateArgumentListInfo &Buffer,
1461 DeclarationNameInfo &NameInfo,
1462 const TemplateArgumentListInfo *&TemplateArgs) {
1463 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1464 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1465 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1467 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1468 Id.TemplateId->NumArgs);
1469 translateTemplateArguments(TemplateArgsPtr, Buffer);
1471 TemplateName TName = Id.TemplateId->Template.get();
1472 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1473 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1474 TemplateArgs = &Buffer;
1476 NameInfo = GetNameFromUnqualifiedId(Id);
1481 /// Diagnose an empty lookup.
1483 /// \return false if new lookup candidates were found
1484 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1485 CorrectionCandidateCallback &CCC,
1486 TemplateArgumentListInfo *ExplicitTemplateArgs,
1487 llvm::ArrayRef<Expr *> Args) {
1488 DeclarationName Name = R.getLookupName();
1490 unsigned diagnostic = diag::err_undeclared_var_use;
1491 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1492 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1493 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1494 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1495 diagnostic = diag::err_undeclared_use;
1496 diagnostic_suggest = diag::err_undeclared_use_suggest;
1499 // If the original lookup was an unqualified lookup, fake an
1500 // unqualified lookup. This is useful when (for example) the
1501 // original lookup would not have found something because it was a
1503 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1506 if (isa<CXXRecordDecl>(DC)) {
1507 LookupQualifiedName(R, DC);
1510 // Don't give errors about ambiguities in this lookup.
1511 R.suppressDiagnostics();
1513 // During a default argument instantiation the CurContext points
1514 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1515 // function parameter list, hence add an explicit check.
1516 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1517 ActiveTemplateInstantiations.back().Kind ==
1518 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1519 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1520 bool isInstance = CurMethod &&
1521 CurMethod->isInstance() &&
1522 DC == CurMethod->getParent() && !isDefaultArgument;
1525 // Give a code modification hint to insert 'this->'.
1526 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1527 // Actually quite difficult!
1528 if (getLangOpts().MicrosoftMode)
1529 diagnostic = diag::warn_found_via_dependent_bases_lookup;
1531 Diag(R.getNameLoc(), diagnostic) << Name
1532 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1533 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1534 CallsUndergoingInstantiation.back()->getCallee());
1537 CXXMethodDecl *DepMethod;
1538 if (CurMethod->getTemplatedKind() ==
1539 FunctionDecl::TK_FunctionTemplateSpecialization)
1540 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1541 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1543 DepMethod = cast<CXXMethodDecl>(
1544 CurMethod->getInstantiatedFromMemberFunction());
1545 assert(DepMethod && "No template pattern found");
1547 QualType DepThisType = DepMethod->getThisType(Context);
1548 CheckCXXThisCapture(R.getNameLoc());
1549 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1550 R.getNameLoc(), DepThisType, false);
1551 TemplateArgumentListInfo TList;
1552 if (ULE->hasExplicitTemplateArgs())
1553 ULE->copyTemplateArgumentsInto(TList);
1556 SS.Adopt(ULE->getQualifierLoc());
1557 CXXDependentScopeMemberExpr *DepExpr =
1558 CXXDependentScopeMemberExpr::Create(
1559 Context, DepThis, DepThisType, true, SourceLocation(),
1560 SS.getWithLocInContext(Context),
1561 ULE->getTemplateKeywordLoc(), 0,
1562 R.getLookupNameInfo(),
1563 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1564 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1566 Diag(R.getNameLoc(), diagnostic) << Name;
1569 // Do we really want to note all of these?
1570 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1571 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1573 // Return true if we are inside a default argument instantiation
1574 // and the found name refers to an instance member function, otherwise
1575 // the function calling DiagnoseEmptyLookup will try to create an
1576 // implicit member call and this is wrong for default argument.
1577 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1578 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1582 // Tell the callee to try to recover.
1589 // In Microsoft mode, if we are performing lookup from within a friend
1590 // function definition declared at class scope then we must set
1591 // DC to the lexical parent to be able to search into the parent
1593 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1594 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1595 DC->getLexicalParent()->isRecord())
1596 DC = DC->getLexicalParent();
1598 DC = DC->getParent();
1601 // We didn't find anything, so try to correct for a typo.
1602 TypoCorrection Corrected;
1603 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1605 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1606 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1607 R.setLookupName(Corrected.getCorrection());
1609 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1610 if (Corrected.isOverloaded()) {
1611 OverloadCandidateSet OCS(R.getNameLoc());
1612 OverloadCandidateSet::iterator Best;
1613 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1614 CDEnd = Corrected.end();
1615 CD != CDEnd; ++CD) {
1616 if (FunctionTemplateDecl *FTD =
1617 dyn_cast<FunctionTemplateDecl>(*CD))
1618 AddTemplateOverloadCandidate(
1619 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1621 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1622 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1623 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1626 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1628 ND = Best->Function;
1635 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1637 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1638 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1640 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1641 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1643 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1646 Diag(ND->getLocation(), diag::note_previous_decl)
1647 << CorrectedQuotedStr;
1649 // Tell the callee to try to recover.
1653 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1654 // FIXME: If we ended up with a typo for a type name or
1655 // Objective-C class name, we're in trouble because the parser
1656 // is in the wrong place to recover. Suggest the typo
1657 // correction, but don't make it a fix-it since we're not going
1658 // to recover well anyway.
1660 Diag(R.getNameLoc(), diagnostic_suggest)
1661 << Name << CorrectedQuotedStr;
1663 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1664 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1667 // Don't try to recover; it won't work.
1671 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1672 // because we aren't able to recover.
1674 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1676 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1677 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1684 // Emit a special diagnostic for failed member lookups.
1685 // FIXME: computing the declaration context might fail here (?)
1686 if (!SS.isEmpty()) {
1687 Diag(R.getNameLoc(), diag::err_no_member)
1688 << Name << computeDeclContext(SS, false)
1693 // Give up, we can't recover.
1694 Diag(R.getNameLoc(), diagnostic) << Name;
1698 ExprResult Sema::ActOnIdExpression(Scope *S,
1700 SourceLocation TemplateKWLoc,
1702 bool HasTrailingLParen,
1703 bool IsAddressOfOperand,
1704 CorrectionCandidateCallback *CCC) {
1705 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1706 "cannot be direct & operand and have a trailing lparen");
1711 TemplateArgumentListInfo TemplateArgsBuffer;
1713 // Decompose the UnqualifiedId into the following data.
1714 DeclarationNameInfo NameInfo;
1715 const TemplateArgumentListInfo *TemplateArgs;
1716 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1718 DeclarationName Name = NameInfo.getName();
1719 IdentifierInfo *II = Name.getAsIdentifierInfo();
1720 SourceLocation NameLoc = NameInfo.getLoc();
1722 // C++ [temp.dep.expr]p3:
1723 // An id-expression is type-dependent if it contains:
1724 // -- an identifier that was declared with a dependent type,
1725 // (note: handled after lookup)
1726 // -- a template-id that is dependent,
1727 // (note: handled in BuildTemplateIdExpr)
1728 // -- a conversion-function-id that specifies a dependent type,
1729 // -- a nested-name-specifier that contains a class-name that
1730 // names a dependent type.
1731 // Determine whether this is a member of an unknown specialization;
1732 // we need to handle these differently.
1733 bool DependentID = false;
1734 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1735 Name.getCXXNameType()->isDependentType()) {
1737 } else if (SS.isSet()) {
1738 if (DeclContext *DC = computeDeclContext(SS, false)) {
1739 if (RequireCompleteDeclContext(SS, DC))
1747 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1748 IsAddressOfOperand, TemplateArgs);
1750 // Perform the required lookup.
1751 LookupResult R(*this, NameInfo,
1752 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1753 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1755 // Lookup the template name again to correctly establish the context in
1756 // which it was found. This is really unfortunate as we already did the
1757 // lookup to determine that it was a template name in the first place. If
1758 // this becomes a performance hit, we can work harder to preserve those
1759 // results until we get here but it's likely not worth it.
1760 bool MemberOfUnknownSpecialization;
1761 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1762 MemberOfUnknownSpecialization);
1764 if (MemberOfUnknownSpecialization ||
1765 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1766 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1767 IsAddressOfOperand, TemplateArgs);
1769 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1770 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1772 // If the result might be in a dependent base class, this is a dependent
1774 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1775 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1776 IsAddressOfOperand, TemplateArgs);
1778 // If this reference is in an Objective-C method, then we need to do
1779 // some special Objective-C lookup, too.
1780 if (IvarLookupFollowUp) {
1781 ExprResult E(LookupInObjCMethod(R, S, II, true));
1785 if (Expr *Ex = E.takeAs<Expr>())
1790 if (R.isAmbiguous())
1793 // Determine whether this name might be a candidate for
1794 // argument-dependent lookup.
1795 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1797 if (R.empty() && !ADL) {
1798 // Otherwise, this could be an implicitly declared function reference (legal
1799 // in C90, extension in C99, forbidden in C++).
1800 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1801 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1802 if (D) R.addDecl(D);
1805 // If this name wasn't predeclared and if this is not a function
1806 // call, diagnose the problem.
1809 // In Microsoft mode, if we are inside a template class member function
1810 // and we can't resolve an identifier then assume the identifier is type
1811 // dependent. The goal is to postpone name lookup to instantiation time
1812 // to be able to search into type dependent base classes.
1813 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1814 isa<CXXMethodDecl>(CurContext))
1815 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1816 IsAddressOfOperand, TemplateArgs);
1818 CorrectionCandidateCallback DefaultValidator;
1819 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1822 assert(!R.empty() &&
1823 "DiagnoseEmptyLookup returned false but added no results");
1825 // If we found an Objective-C instance variable, let
1826 // LookupInObjCMethod build the appropriate expression to
1827 // reference the ivar.
1828 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1830 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1831 // In a hopelessly buggy code, Objective-C instance variable
1832 // lookup fails and no expression will be built to reference it.
1833 if (!E.isInvalid() && !E.get())
1840 // This is guaranteed from this point on.
1841 assert(!R.empty() || ADL);
1843 // Check whether this might be a C++ implicit instance member access.
1844 // C++ [class.mfct.non-static]p3:
1845 // When an id-expression that is not part of a class member access
1846 // syntax and not used to form a pointer to member is used in the
1847 // body of a non-static member function of class X, if name lookup
1848 // resolves the name in the id-expression to a non-static non-type
1849 // member of some class C, the id-expression is transformed into a
1850 // class member access expression using (*this) as the
1851 // postfix-expression to the left of the . operator.
1853 // But we don't actually need to do this for '&' operands if R
1854 // resolved to a function or overloaded function set, because the
1855 // expression is ill-formed if it actually works out to be a
1856 // non-static member function:
1858 // C++ [expr.ref]p4:
1859 // Otherwise, if E1.E2 refers to a non-static member function. . .
1860 // [t]he expression can be used only as the left-hand operand of a
1861 // member function call.
1863 // There are other safeguards against such uses, but it's important
1864 // to get this right here so that we don't end up making a
1865 // spuriously dependent expression if we're inside a dependent
1867 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1868 bool MightBeImplicitMember;
1869 if (!IsAddressOfOperand)
1870 MightBeImplicitMember = true;
1871 else if (!SS.isEmpty())
1872 MightBeImplicitMember = false;
1873 else if (R.isOverloadedResult())
1874 MightBeImplicitMember = false;
1875 else if (R.isUnresolvableResult())
1876 MightBeImplicitMember = true;
1878 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1879 isa<IndirectFieldDecl>(R.getFoundDecl());
1881 if (MightBeImplicitMember)
1882 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1886 if (TemplateArgs || TemplateKWLoc.isValid())
1887 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1889 return BuildDeclarationNameExpr(SS, R, ADL);
1892 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1893 /// declaration name, generally during template instantiation.
1894 /// There's a large number of things which don't need to be done along
1897 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1898 const DeclarationNameInfo &NameInfo,
1899 bool IsAddressOfOperand) {
1900 DeclContext *DC = computeDeclContext(SS, false);
1902 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1903 NameInfo, /*TemplateArgs=*/0);
1905 if (RequireCompleteDeclContext(SS, DC))
1908 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1909 LookupQualifiedName(R, DC);
1911 if (R.isAmbiguous())
1914 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1915 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1916 NameInfo, /*TemplateArgs=*/0);
1919 Diag(NameInfo.getLoc(), diag::err_no_member)
1920 << NameInfo.getName() << DC << SS.getRange();
1924 // Defend against this resolving to an implicit member access. We usually
1925 // won't get here if this might be a legitimate a class member (we end up in
1926 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
1927 // a pointer-to-member or in an unevaluated context in C++11.
1928 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
1929 return BuildPossibleImplicitMemberExpr(SS,
1930 /*TemplateKWLoc=*/SourceLocation(),
1931 R, /*TemplateArgs=*/0);
1933 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
1936 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1937 /// detected that we're currently inside an ObjC method. Perform some
1938 /// additional lookup.
1940 /// Ideally, most of this would be done by lookup, but there's
1941 /// actually quite a lot of extra work involved.
1943 /// Returns a null sentinel to indicate trivial success.
1945 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1946 IdentifierInfo *II, bool AllowBuiltinCreation) {
1947 SourceLocation Loc = Lookup.getNameLoc();
1948 ObjCMethodDecl *CurMethod = getCurMethodDecl();
1950 // There are two cases to handle here. 1) scoped lookup could have failed,
1951 // in which case we should look for an ivar. 2) scoped lookup could have
1952 // found a decl, but that decl is outside the current instance method (i.e.
1953 // a global variable). In these two cases, we do a lookup for an ivar with
1954 // this name, if the lookup sucedes, we replace it our current decl.
1956 // If we're in a class method, we don't normally want to look for
1957 // ivars. But if we don't find anything else, and there's an
1958 // ivar, that's an error.
1959 bool IsClassMethod = CurMethod->isClassMethod();
1963 LookForIvars = true;
1964 else if (IsClassMethod)
1965 LookForIvars = false;
1967 LookForIvars = (Lookup.isSingleResult() &&
1968 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1969 ObjCInterfaceDecl *IFace = 0;
1971 IFace = CurMethod->getClassInterface();
1972 ObjCInterfaceDecl *ClassDeclared;
1973 ObjCIvarDecl *IV = 0;
1974 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
1975 // Diagnose using an ivar in a class method.
1977 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1978 << IV->getDeclName());
1980 // If we're referencing an invalid decl, just return this as a silent
1981 // error node. The error diagnostic was already emitted on the decl.
1982 if (IV->isInvalidDecl())
1985 // Check if referencing a field with __attribute__((deprecated)).
1986 if (DiagnoseUseOfDecl(IV, Loc))
1989 // Diagnose the use of an ivar outside of the declaring class.
1990 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1991 !declaresSameEntity(ClassDeclared, IFace) &&
1992 !getLangOpts().DebuggerSupport)
1993 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1995 // FIXME: This should use a new expr for a direct reference, don't
1996 // turn this into Self->ivar, just return a BareIVarExpr or something.
1997 IdentifierInfo &II = Context.Idents.get("self");
1998 UnqualifiedId SelfName;
1999 SelfName.setIdentifier(&II, SourceLocation());
2000 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2001 CXXScopeSpec SelfScopeSpec;
2002 SourceLocation TemplateKWLoc;
2003 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2004 SelfName, false, false);
2005 if (SelfExpr.isInvalid())
2008 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2009 if (SelfExpr.isInvalid())
2012 MarkAnyDeclReferenced(Loc, IV);
2014 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2015 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
2016 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2018 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2023 if (getLangOpts().ObjCAutoRefCount) {
2024 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2025 DiagnosticsEngine::Level Level =
2026 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2027 if (Level != DiagnosticsEngine::Ignored)
2028 getCurFunction()->recordUseOfWeak(Result);
2030 if (CurContext->isClosure())
2031 Diag(Loc, diag::warn_implicitly_retains_self)
2032 << FixItHint::CreateInsertion(Loc, "self->");
2035 return Owned(Result);
2037 } else if (CurMethod->isInstanceMethod()) {
2038 // We should warn if a local variable hides an ivar.
2039 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2040 ObjCInterfaceDecl *ClassDeclared;
2041 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2042 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2043 declaresSameEntity(IFace, ClassDeclared))
2044 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2047 } else if (Lookup.isSingleResult() &&
2048 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2049 // If accessing a stand-alone ivar in a class method, this is an error.
2050 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2051 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2052 << IV->getDeclName());
2055 if (Lookup.empty() && II && AllowBuiltinCreation) {
2056 // FIXME. Consolidate this with similar code in LookupName.
2057 if (unsigned BuiltinID = II->getBuiltinID()) {
2058 if (!(getLangOpts().CPlusPlus &&
2059 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2060 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2061 S, Lookup.isForRedeclaration(),
2062 Lookup.getNameLoc());
2063 if (D) Lookup.addDecl(D);
2067 // Sentinel value saying that we didn't do anything special.
2068 return Owned((Expr*) 0);
2071 /// \brief Cast a base object to a member's actual type.
2073 /// Logically this happens in three phases:
2075 /// * First we cast from the base type to the naming class.
2076 /// The naming class is the class into which we were looking
2077 /// when we found the member; it's the qualifier type if a
2078 /// qualifier was provided, and otherwise it's the base type.
2080 /// * Next we cast from the naming class to the declaring class.
2081 /// If the member we found was brought into a class's scope by
2082 /// a using declaration, this is that class; otherwise it's
2083 /// the class declaring the member.
2085 /// * Finally we cast from the declaring class to the "true"
2086 /// declaring class of the member. This conversion does not
2087 /// obey access control.
2089 Sema::PerformObjectMemberConversion(Expr *From,
2090 NestedNameSpecifier *Qualifier,
2091 NamedDecl *FoundDecl,
2092 NamedDecl *Member) {
2093 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2097 QualType DestRecordType;
2099 QualType FromRecordType;
2100 QualType FromType = From->getType();
2101 bool PointerConversions = false;
2102 if (isa<FieldDecl>(Member)) {
2103 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2105 if (FromType->getAs<PointerType>()) {
2106 DestType = Context.getPointerType(DestRecordType);
2107 FromRecordType = FromType->getPointeeType();
2108 PointerConversions = true;
2110 DestType = DestRecordType;
2111 FromRecordType = FromType;
2113 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2114 if (Method->isStatic())
2117 DestType = Method->getThisType(Context);
2118 DestRecordType = DestType->getPointeeType();
2120 if (FromType->getAs<PointerType>()) {
2121 FromRecordType = FromType->getPointeeType();
2122 PointerConversions = true;
2124 FromRecordType = FromType;
2125 DestType = DestRecordType;
2128 // No conversion necessary.
2132 if (DestType->isDependentType() || FromType->isDependentType())
2135 // If the unqualified types are the same, no conversion is necessary.
2136 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2139 SourceRange FromRange = From->getSourceRange();
2140 SourceLocation FromLoc = FromRange.getBegin();
2142 ExprValueKind VK = From->getValueKind();
2144 // C++ [class.member.lookup]p8:
2145 // [...] Ambiguities can often be resolved by qualifying a name with its
2148 // If the member was a qualified name and the qualified referred to a
2149 // specific base subobject type, we'll cast to that intermediate type
2150 // first and then to the object in which the member is declared. That allows
2151 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2153 // class Base { public: int x; };
2154 // class Derived1 : public Base { };
2155 // class Derived2 : public Base { };
2156 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2158 // void VeryDerived::f() {
2159 // x = 17; // error: ambiguous base subobjects
2160 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2163 QualType QType = QualType(Qualifier->getAsType(), 0);
2164 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2165 assert(QType->isRecordType() && "lookup done with non-record type");
2167 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2169 // In C++98, the qualifier type doesn't actually have to be a base
2170 // type of the object type, in which case we just ignore it.
2171 // Otherwise build the appropriate casts.
2172 if (IsDerivedFrom(FromRecordType, QRecordType)) {
2173 CXXCastPath BasePath;
2174 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2175 FromLoc, FromRange, &BasePath))
2178 if (PointerConversions)
2179 QType = Context.getPointerType(QType);
2180 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2181 VK, &BasePath).take();
2184 FromRecordType = QRecordType;
2186 // If the qualifier type was the same as the destination type,
2188 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2193 bool IgnoreAccess = false;
2195 // If we actually found the member through a using declaration, cast
2196 // down to the using declaration's type.
2198 // Pointer equality is fine here because only one declaration of a
2199 // class ever has member declarations.
2200 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2201 assert(isa<UsingShadowDecl>(FoundDecl));
2202 QualType URecordType = Context.getTypeDeclType(
2203 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2205 // We only need to do this if the naming-class to declaring-class
2206 // conversion is non-trivial.
2207 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2208 assert(IsDerivedFrom(FromRecordType, URecordType));
2209 CXXCastPath BasePath;
2210 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2211 FromLoc, FromRange, &BasePath))
2214 QualType UType = URecordType;
2215 if (PointerConversions)
2216 UType = Context.getPointerType(UType);
2217 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2218 VK, &BasePath).take();
2220 FromRecordType = URecordType;
2223 // We don't do access control for the conversion from the
2224 // declaring class to the true declaring class.
2225 IgnoreAccess = true;
2228 CXXCastPath BasePath;
2229 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2230 FromLoc, FromRange, &BasePath,
2234 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2238 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2239 const LookupResult &R,
2240 bool HasTrailingLParen) {
2241 // Only when used directly as the postfix-expression of a call.
2242 if (!HasTrailingLParen)
2245 // Never if a scope specifier was provided.
2249 // Only in C++ or ObjC++.
2250 if (!getLangOpts().CPlusPlus)
2253 // Turn off ADL when we find certain kinds of declarations during
2255 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2258 // C++0x [basic.lookup.argdep]p3:
2259 // -- a declaration of a class member
2260 // Since using decls preserve this property, we check this on the
2262 if (D->isCXXClassMember())
2265 // C++0x [basic.lookup.argdep]p3:
2266 // -- a block-scope function declaration that is not a
2267 // using-declaration
2268 // NOTE: we also trigger this for function templates (in fact, we
2269 // don't check the decl type at all, since all other decl types
2270 // turn off ADL anyway).
2271 if (isa<UsingShadowDecl>(D))
2272 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2273 else if (D->getDeclContext()->isFunctionOrMethod())
2276 // C++0x [basic.lookup.argdep]p3:
2277 // -- a declaration that is neither a function or a function
2279 // And also for builtin functions.
2280 if (isa<FunctionDecl>(D)) {
2281 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2283 // But also builtin functions.
2284 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2286 } else if (!isa<FunctionTemplateDecl>(D))
2294 /// Diagnoses obvious problems with the use of the given declaration
2295 /// as an expression. This is only actually called for lookups that
2296 /// were not overloaded, and it doesn't promise that the declaration
2297 /// will in fact be used.
2298 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2299 if (isa<TypedefNameDecl>(D)) {
2300 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2304 if (isa<ObjCInterfaceDecl>(D)) {
2305 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2309 if (isa<NamespaceDecl>(D)) {
2310 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2318 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2321 // If this is a single, fully-resolved result and we don't need ADL,
2322 // just build an ordinary singleton decl ref.
2323 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2324 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2327 // We only need to check the declaration if there's exactly one
2328 // result, because in the overloaded case the results can only be
2329 // functions and function templates.
2330 if (R.isSingleResult() &&
2331 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2334 // Otherwise, just build an unresolved lookup expression. Suppress
2335 // any lookup-related diagnostics; we'll hash these out later, when
2336 // we've picked a target.
2337 R.suppressDiagnostics();
2339 UnresolvedLookupExpr *ULE
2340 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2341 SS.getWithLocInContext(Context),
2342 R.getLookupNameInfo(),
2343 NeedsADL, R.isOverloadedResult(),
2344 R.begin(), R.end());
2349 /// \brief Complete semantic analysis for a reference to the given declaration.
2351 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2352 const DeclarationNameInfo &NameInfo,
2354 assert(D && "Cannot refer to a NULL declaration");
2355 assert(!isa<FunctionTemplateDecl>(D) &&
2356 "Cannot refer unambiguously to a function template");
2358 SourceLocation Loc = NameInfo.getLoc();
2359 if (CheckDeclInExpr(*this, Loc, D))
2362 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2363 // Specifically diagnose references to class templates that are missing
2364 // a template argument list.
2365 Diag(Loc, diag::err_template_decl_ref)
2366 << Template << SS.getRange();
2367 Diag(Template->getLocation(), diag::note_template_decl_here);
2371 // Make sure that we're referring to a value.
2372 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2374 Diag(Loc, diag::err_ref_non_value)
2375 << D << SS.getRange();
2376 Diag(D->getLocation(), diag::note_declared_at);
2380 // Check whether this declaration can be used. Note that we suppress
2381 // this check when we're going to perform argument-dependent lookup
2382 // on this function name, because this might not be the function
2383 // that overload resolution actually selects.
2384 if (DiagnoseUseOfDecl(VD, Loc))
2387 // Only create DeclRefExpr's for valid Decl's.
2388 if (VD->isInvalidDecl())
2391 // Handle members of anonymous structs and unions. If we got here,
2392 // and the reference is to a class member indirect field, then this
2393 // must be the subject of a pointer-to-member expression.
2394 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2395 if (!indirectField->isCXXClassMember())
2396 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2400 QualType type = VD->getType();
2401 ExprValueKind valueKind = VK_RValue;
2403 switch (D->getKind()) {
2404 // Ignore all the non-ValueDecl kinds.
2405 #define ABSTRACT_DECL(kind)
2406 #define VALUE(type, base)
2407 #define DECL(type, base) \
2409 #include "clang/AST/DeclNodes.inc"
2410 llvm_unreachable("invalid value decl kind");
2412 // These shouldn't make it here.
2413 case Decl::ObjCAtDefsField:
2414 case Decl::ObjCIvar:
2415 llvm_unreachable("forming non-member reference to ivar?");
2417 // Enum constants are always r-values and never references.
2418 // Unresolved using declarations are dependent.
2419 case Decl::EnumConstant:
2420 case Decl::UnresolvedUsingValue:
2421 valueKind = VK_RValue;
2424 // Fields and indirect fields that got here must be for
2425 // pointer-to-member expressions; we just call them l-values for
2426 // internal consistency, because this subexpression doesn't really
2427 // exist in the high-level semantics.
2429 case Decl::IndirectField:
2430 assert(getLangOpts().CPlusPlus &&
2431 "building reference to field in C?");
2433 // These can't have reference type in well-formed programs, but
2434 // for internal consistency we do this anyway.
2435 type = type.getNonReferenceType();
2436 valueKind = VK_LValue;
2439 // Non-type template parameters are either l-values or r-values
2440 // depending on the type.
2441 case Decl::NonTypeTemplateParm: {
2442 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2443 type = reftype->getPointeeType();
2444 valueKind = VK_LValue; // even if the parameter is an r-value reference
2448 // For non-references, we need to strip qualifiers just in case
2449 // the template parameter was declared as 'const int' or whatever.
2450 valueKind = VK_RValue;
2451 type = type.getUnqualifiedType();
2456 // In C, "extern void blah;" is valid and is an r-value.
2457 if (!getLangOpts().CPlusPlus &&
2458 !type.hasQualifiers() &&
2459 type->isVoidType()) {
2460 valueKind = VK_RValue;
2465 case Decl::ImplicitParam:
2466 case Decl::ParmVar: {
2467 // These are always l-values.
2468 valueKind = VK_LValue;
2469 type = type.getNonReferenceType();
2471 // FIXME: Does the addition of const really only apply in
2472 // potentially-evaluated contexts? Since the variable isn't actually
2473 // captured in an unevaluated context, it seems that the answer is no.
2474 if (!isUnevaluatedContext()) {
2475 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2476 if (!CapturedType.isNull())
2477 type = CapturedType;
2483 case Decl::Function: {
2484 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2485 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2486 type = Context.BuiltinFnTy;
2487 valueKind = VK_RValue;
2492 const FunctionType *fty = type->castAs<FunctionType>();
2494 // If we're referring to a function with an __unknown_anytype
2495 // result type, make the entire expression __unknown_anytype.
2496 if (fty->getResultType() == Context.UnknownAnyTy) {
2497 type = Context.UnknownAnyTy;
2498 valueKind = VK_RValue;
2502 // Functions are l-values in C++.
2503 if (getLangOpts().CPlusPlus) {
2504 valueKind = VK_LValue;
2508 // C99 DR 316 says that, if a function type comes from a
2509 // function definition (without a prototype), that type is only
2510 // used for checking compatibility. Therefore, when referencing
2511 // the function, we pretend that we don't have the full function
2513 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2514 isa<FunctionProtoType>(fty))
2515 type = Context.getFunctionNoProtoType(fty->getResultType(),
2518 // Functions are r-values in C.
2519 valueKind = VK_RValue;
2523 case Decl::CXXMethod:
2524 // If we're referring to a method with an __unknown_anytype
2525 // result type, make the entire expression __unknown_anytype.
2526 // This should only be possible with a type written directly.
2527 if (const FunctionProtoType *proto
2528 = dyn_cast<FunctionProtoType>(VD->getType()))
2529 if (proto->getResultType() == Context.UnknownAnyTy) {
2530 type = Context.UnknownAnyTy;
2531 valueKind = VK_RValue;
2535 // C++ methods are l-values if static, r-values if non-static.
2536 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2537 valueKind = VK_LValue;
2542 case Decl::CXXConversion:
2543 case Decl::CXXDestructor:
2544 case Decl::CXXConstructor:
2545 valueKind = VK_RValue;
2549 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2553 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2554 PredefinedExpr::IdentType IT;
2557 default: llvm_unreachable("Unknown simple primary expr!");
2558 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2559 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2560 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2561 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2564 // Pre-defined identifiers are of type char[x], where x is the length of the
2567 Decl *currentDecl = getCurFunctionOrMethodDecl();
2568 if (!currentDecl && getCurBlock())
2569 currentDecl = getCurBlock()->TheDecl;
2571 Diag(Loc, diag::ext_predef_outside_function);
2572 currentDecl = Context.getTranslationUnitDecl();
2576 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2577 ResTy = Context.DependentTy;
2579 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2581 llvm::APInt LengthI(32, Length + 1);
2582 if (IT == PredefinedExpr::LFunction)
2583 ResTy = Context.WCharTy.withConst();
2585 ResTy = Context.CharTy.withConst();
2586 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2588 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2591 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2592 SmallString<16> CharBuffer;
2593 bool Invalid = false;
2594 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2598 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2600 if (Literal.hadError())
2604 if (Literal.isWide())
2605 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2606 else if (Literal.isUTF16())
2607 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2608 else if (Literal.isUTF32())
2609 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2610 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2611 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
2613 Ty = Context.CharTy; // 'x' -> char in C++
2615 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2616 if (Literal.isWide())
2617 Kind = CharacterLiteral::Wide;
2618 else if (Literal.isUTF16())
2619 Kind = CharacterLiteral::UTF16;
2620 else if (Literal.isUTF32())
2621 Kind = CharacterLiteral::UTF32;
2623 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2626 if (Literal.getUDSuffix().empty())
2629 // We're building a user-defined literal.
2630 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2631 SourceLocation UDSuffixLoc =
2632 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2634 // Make sure we're allowed user-defined literals here.
2636 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2638 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2639 // operator "" X (ch)
2640 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2641 llvm::makeArrayRef(&Lit, 1),
2645 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2646 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2647 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2648 Context.IntTy, Loc));
2651 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2652 QualType Ty, SourceLocation Loc) {
2653 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2655 using llvm::APFloat;
2656 APFloat Val(Format);
2658 APFloat::opStatus result = Literal.GetFloatValue(Val);
2660 // Overflow is always an error, but underflow is only an error if
2661 // we underflowed to zero (APFloat reports denormals as underflow).
2662 if ((result & APFloat::opOverflow) ||
2663 ((result & APFloat::opUnderflow) && Val.isZero())) {
2664 unsigned diagnostic;
2665 SmallString<20> buffer;
2666 if (result & APFloat::opOverflow) {
2667 diagnostic = diag::warn_float_overflow;
2668 APFloat::getLargest(Format).toString(buffer);
2670 diagnostic = diag::warn_float_underflow;
2671 APFloat::getSmallest(Format).toString(buffer);
2674 S.Diag(Loc, diagnostic)
2676 << StringRef(buffer.data(), buffer.size());
2679 bool isExact = (result == APFloat::opOK);
2680 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2683 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2684 // Fast path for a single digit (which is quite common). A single digit
2685 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2686 if (Tok.getLength() == 1) {
2687 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2688 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2691 SmallString<128> SpellingBuffer;
2692 // NumericLiteralParser wants to overread by one character. Add padding to
2693 // the buffer in case the token is copied to the buffer. If getSpelling()
2694 // returns a StringRef to the memory buffer, it should have a null char at
2695 // the EOF, so it is also safe.
2696 SpellingBuffer.resize(Tok.getLength() + 1);
2698 // Get the spelling of the token, which eliminates trigraphs, etc.
2699 bool Invalid = false;
2700 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2704 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2705 if (Literal.hadError)
2708 if (Literal.hasUDSuffix()) {
2709 // We're building a user-defined literal.
2710 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2711 SourceLocation UDSuffixLoc =
2712 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2714 // Make sure we're allowed user-defined literals here.
2716 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2719 if (Literal.isFloatingLiteral()) {
2720 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2721 // long double, the literal is treated as a call of the form
2722 // operator "" X (f L)
2723 CookedTy = Context.LongDoubleTy;
2725 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2726 // unsigned long long, the literal is treated as a call of the form
2727 // operator "" X (n ULL)
2728 CookedTy = Context.UnsignedLongLongTy;
2731 DeclarationName OpName =
2732 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2733 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2734 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2736 // Perform literal operator lookup to determine if we're building a raw
2737 // literal or a cooked one.
2738 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2739 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2740 /*AllowRawAndTemplate*/true)) {
2746 if (Literal.isFloatingLiteral()) {
2747 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2749 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2750 if (Literal.GetIntegerValue(ResultVal))
2751 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2752 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2755 return BuildLiteralOperatorCall(R, OpNameInfo,
2756 llvm::makeArrayRef(&Lit, 1),
2761 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2762 // literal is treated as a call of the form
2763 // operator "" X ("n")
2764 SourceLocation TokLoc = Tok.getLocation();
2765 unsigned Length = Literal.getUDSuffixOffset();
2766 QualType StrTy = Context.getConstantArrayType(
2767 Context.CharTy, llvm::APInt(32, Length + 1),
2768 ArrayType::Normal, 0);
2769 Expr *Lit = StringLiteral::Create(
2770 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2771 /*Pascal*/false, StrTy, &TokLoc, 1);
2772 return BuildLiteralOperatorCall(R, OpNameInfo,
2773 llvm::makeArrayRef(&Lit, 1), TokLoc);
2777 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2778 // template), L is treated as a call fo the form
2779 // operator "" X <'c1', 'c2', ... 'ck'>()
2780 // where n is the source character sequence c1 c2 ... ck.
2781 TemplateArgumentListInfo ExplicitArgs;
2782 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2783 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2784 llvm::APSInt Value(CharBits, CharIsUnsigned);
2785 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2786 Value = TokSpelling[I];
2787 TemplateArgument Arg(Context, Value, Context.CharTy);
2788 TemplateArgumentLocInfo ArgInfo;
2789 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2791 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2792 Tok.getLocation(), &ExplicitArgs);
2795 llvm_unreachable("unexpected literal operator lookup result");
2800 if (Literal.isFloatingLiteral()) {
2802 if (Literal.isFloat)
2803 Ty = Context.FloatTy;
2804 else if (!Literal.isLong)
2805 Ty = Context.DoubleTy;
2807 Ty = Context.LongDoubleTy;
2809 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2811 if (Ty == Context.DoubleTy) {
2812 if (getLangOpts().SinglePrecisionConstants) {
2813 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2814 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2815 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2816 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2819 } else if (!Literal.isIntegerLiteral()) {
2824 // 'long long' is a C99 or C++11 feature.
2825 if (!getLangOpts().C99 && Literal.isLongLong) {
2826 if (getLangOpts().CPlusPlus)
2827 Diag(Tok.getLocation(),
2828 getLangOpts().CPlusPlus0x ?
2829 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2831 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2834 // Get the value in the widest-possible width.
2835 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2836 // The microsoft literal suffix extensions support 128-bit literals, which
2837 // may be wider than [u]intmax_t.
2838 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2840 llvm::APInt ResultVal(MaxWidth, 0);
2842 if (Literal.GetIntegerValue(ResultVal)) {
2843 // If this value didn't fit into uintmax_t, warn and force to ull.
2844 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2845 Ty = Context.UnsignedLongLongTy;
2846 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2847 "long long is not intmax_t?");
2849 // If this value fits into a ULL, try to figure out what else it fits into
2850 // according to the rules of C99 6.4.4.1p5.
2852 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2853 // be an unsigned int.
2854 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2856 // Check from smallest to largest, picking the smallest type we can.
2858 if (!Literal.isLong && !Literal.isLongLong) {
2859 // Are int/unsigned possibilities?
2860 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2862 // Does it fit in a unsigned int?
2863 if (ResultVal.isIntN(IntSize)) {
2864 // Does it fit in a signed int?
2865 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2867 else if (AllowUnsigned)
2868 Ty = Context.UnsignedIntTy;
2873 // Are long/unsigned long possibilities?
2874 if (Ty.isNull() && !Literal.isLongLong) {
2875 unsigned LongSize = Context.getTargetInfo().getLongWidth();
2877 // Does it fit in a unsigned long?
2878 if (ResultVal.isIntN(LongSize)) {
2879 // Does it fit in a signed long?
2880 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2881 Ty = Context.LongTy;
2882 else if (AllowUnsigned)
2883 Ty = Context.UnsignedLongTy;
2888 // Check long long if needed.
2890 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2892 // Does it fit in a unsigned long long?
2893 if (ResultVal.isIntN(LongLongSize)) {
2894 // Does it fit in a signed long long?
2895 // To be compatible with MSVC, hex integer literals ending with the
2896 // LL or i64 suffix are always signed in Microsoft mode.
2897 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2898 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
2899 Ty = Context.LongLongTy;
2900 else if (AllowUnsigned)
2901 Ty = Context.UnsignedLongLongTy;
2902 Width = LongLongSize;
2906 // If it doesn't fit in unsigned long long, and we're using Microsoft
2907 // extensions, then its a 128-bit integer literal.
2908 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2909 if (Literal.isUnsigned)
2910 Ty = Context.UnsignedInt128Ty;
2912 Ty = Context.Int128Ty;
2916 // If we still couldn't decide a type, we probably have something that
2917 // does not fit in a signed long long, but has no U suffix.
2919 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2920 Ty = Context.UnsignedLongLongTy;
2921 Width = Context.getTargetInfo().getLongLongWidth();
2924 if (ResultVal.getBitWidth() != Width)
2925 ResultVal = ResultVal.trunc(Width);
2927 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2930 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2931 if (Literal.isImaginary)
2932 Res = new (Context) ImaginaryLiteral(Res,
2933 Context.getComplexType(Res->getType()));
2938 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2939 assert((E != 0) && "ActOnParenExpr() missing expr");
2940 return Owned(new (Context) ParenExpr(L, R, E));
2943 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2945 SourceRange ArgRange) {
2946 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2947 // scalar or vector data type argument..."
2948 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2949 // type (C99 6.2.5p18) or void.
2950 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2951 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2956 assert((T->isVoidType() || !T->isIncompleteType()) &&
2957 "Scalar types should always be complete");
2961 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2963 SourceRange ArgRange,
2964 UnaryExprOrTypeTrait TraitKind) {
2966 if (T->isFunctionType()) {
2967 // alignof(function) is allowed as an extension.
2968 if (TraitKind == UETT_SizeOf)
2969 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2973 // Allow sizeof(void)/alignof(void) as an extension.
2974 if (T->isVoidType()) {
2975 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2982 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2984 SourceRange ArgRange,
2985 UnaryExprOrTypeTrait TraitKind) {
2986 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2987 // runtime doesn't allow it.
2988 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
2989 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2990 << T << (TraitKind == UETT_SizeOf)
2998 /// \brief Check the constrains on expression operands to unary type expression
2999 /// and type traits.
3001 /// Completes any types necessary and validates the constraints on the operand
3002 /// expression. The logic mostly mirrors the type-based overload, but may modify
3003 /// the expression as it completes the type for that expression through template
3004 /// instantiation, etc.
3005 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3006 UnaryExprOrTypeTrait ExprKind) {
3007 QualType ExprTy = E->getType();
3009 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3010 // the result is the size of the referenced type."
3011 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3012 // result shall be the alignment of the referenced type."
3013 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3014 ExprTy = Ref->getPointeeType();
3016 if (ExprKind == UETT_VecStep)
3017 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3018 E->getSourceRange());
3020 // Whitelist some types as extensions
3021 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3022 E->getSourceRange(), ExprKind))
3025 if (RequireCompleteExprType(E,
3026 diag::err_sizeof_alignof_incomplete_type,
3027 ExprKind, E->getSourceRange()))
3030 // Completeing the expression's type may have changed it.
3031 ExprTy = E->getType();
3032 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3033 ExprTy = Ref->getPointeeType();
3035 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3036 E->getSourceRange(), ExprKind))
3039 if (ExprKind == UETT_SizeOf) {
3040 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3041 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3042 QualType OType = PVD->getOriginalType();
3043 QualType Type = PVD->getType();
3044 if (Type->isPointerType() && OType->isArrayType()) {
3045 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3047 Diag(PVD->getLocation(), diag::note_declared_at);
3056 /// \brief Check the constraints on operands to unary expression and type
3059 /// This will complete any types necessary, and validate the various constraints
3060 /// on those operands.
3062 /// The UsualUnaryConversions() function is *not* called by this routine.
3063 /// C99 6.3.2.1p[2-4] all state:
3064 /// Except when it is the operand of the sizeof operator ...
3066 /// C++ [expr.sizeof]p4
3067 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3068 /// standard conversions are not applied to the operand of sizeof.
3070 /// This policy is followed for all of the unary trait expressions.
3071 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3072 SourceLocation OpLoc,
3073 SourceRange ExprRange,
3074 UnaryExprOrTypeTrait ExprKind) {
3075 if (ExprType->isDependentType())
3078 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3079 // the result is the size of the referenced type."
3080 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3081 // result shall be the alignment of the referenced type."
3082 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3083 ExprType = Ref->getPointeeType();
3085 if (ExprKind == UETT_VecStep)
3086 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3088 // Whitelist some types as extensions
3089 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3093 if (RequireCompleteType(OpLoc, ExprType,
3094 diag::err_sizeof_alignof_incomplete_type,
3095 ExprKind, ExprRange))
3098 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3105 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3106 E = E->IgnoreParens();
3108 // alignof decl is always ok.
3109 if (isa<DeclRefExpr>(E))
3112 // Cannot know anything else if the expression is dependent.
3113 if (E->isTypeDependent())
3116 if (E->getBitField()) {
3117 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3118 << 1 << E->getSourceRange();
3122 // Alignment of a field access is always okay, so long as it isn't a
3124 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3125 if (isa<FieldDecl>(ME->getMemberDecl()))
3128 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3131 bool Sema::CheckVecStepExpr(Expr *E) {
3132 E = E->IgnoreParens();
3134 // Cannot know anything else if the expression is dependent.
3135 if (E->isTypeDependent())
3138 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3141 /// \brief Build a sizeof or alignof expression given a type operand.
3143 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3144 SourceLocation OpLoc,
3145 UnaryExprOrTypeTrait ExprKind,
3150 QualType T = TInfo->getType();
3152 if (!T->isDependentType() &&
3153 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3156 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3157 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3158 Context.getSizeType(),
3159 OpLoc, R.getEnd()));
3162 /// \brief Build a sizeof or alignof expression given an expression
3165 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3166 UnaryExprOrTypeTrait ExprKind) {
3167 ExprResult PE = CheckPlaceholderExpr(E);
3173 // Verify that the operand is valid.
3174 bool isInvalid = false;
3175 if (E->isTypeDependent()) {
3176 // Delay type-checking for type-dependent expressions.
3177 } else if (ExprKind == UETT_AlignOf) {
3178 isInvalid = CheckAlignOfExpr(*this, E);
3179 } else if (ExprKind == UETT_VecStep) {
3180 isInvalid = CheckVecStepExpr(E);
3181 } else if (E->getBitField()) { // C99 6.5.3.4p1.
3182 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3185 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3191 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3192 PE = TranformToPotentiallyEvaluated(E);
3193 if (PE.isInvalid()) return ExprError();
3197 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3198 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3199 ExprKind, E, Context.getSizeType(), OpLoc,
3200 E->getSourceRange().getEnd()));
3203 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3204 /// expr and the same for @c alignof and @c __alignof
3205 /// Note that the ArgRange is invalid if isType is false.
3207 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3208 UnaryExprOrTypeTrait ExprKind, bool IsType,
3209 void *TyOrEx, const SourceRange &ArgRange) {
3210 // If error parsing type, ignore.
3211 if (TyOrEx == 0) return ExprError();
3214 TypeSourceInfo *TInfo;
3215 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3216 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3219 Expr *ArgEx = (Expr *)TyOrEx;
3220 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3224 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3226 if (V.get()->isTypeDependent())
3227 return S.Context.DependentTy;
3229 // _Real and _Imag are only l-values for normal l-values.
3230 if (V.get()->getObjectKind() != OK_Ordinary) {
3231 V = S.DefaultLvalueConversion(V.take());
3236 // These operators return the element type of a complex type.
3237 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3238 return CT->getElementType();
3240 // Otherwise they pass through real integer and floating point types here.
3241 if (V.get()->getType()->isArithmeticType())
3242 return V.get()->getType();
3244 // Test for placeholders.
3245 ExprResult PR = S.CheckPlaceholderExpr(V.get());
3246 if (PR.isInvalid()) return QualType();
3247 if (PR.get() != V.get()) {
3249 return CheckRealImagOperand(S, V, Loc, IsReal);
3252 // Reject anything else.
3253 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3254 << (IsReal ? "__real" : "__imag");
3261 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3262 tok::TokenKind Kind, Expr *Input) {
3263 UnaryOperatorKind Opc;
3265 default: llvm_unreachable("Unknown unary op!");
3266 case tok::plusplus: Opc = UO_PostInc; break;
3267 case tok::minusminus: Opc = UO_PostDec; break;
3270 // Since this might is a postfix expression, get rid of ParenListExprs.
3271 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3272 if (Result.isInvalid()) return ExprError();
3273 Input = Result.take();
3275 return BuildUnaryOp(S, OpLoc, Opc, Input);
3278 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3280 /// \return true on error
3281 static bool checkArithmeticOnObjCPointer(Sema &S,
3282 SourceLocation opLoc,
3284 assert(op->getType()->isObjCObjectPointerType());
3285 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3288 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3289 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3290 << op->getSourceRange();
3295 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3296 Expr *Idx, SourceLocation RLoc) {
3297 // Since this might be a postfix expression, get rid of ParenListExprs.
3298 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3299 if (Result.isInvalid()) return ExprError();
3300 Base = Result.take();
3302 Expr *LHSExp = Base, *RHSExp = Idx;
3304 if (getLangOpts().CPlusPlus &&
3305 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3306 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3307 Context.DependentTy,
3308 VK_LValue, OK_Ordinary,
3312 if (getLangOpts().CPlusPlus &&
3313 (LHSExp->getType()->isRecordType() ||
3314 LHSExp->getType()->isEnumeralType() ||
3315 RHSExp->getType()->isRecordType() ||
3316 RHSExp->getType()->isEnumeralType()) &&
3317 !LHSExp->getType()->isObjCObjectPointerType()) {
3318 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3321 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3325 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3326 Expr *Idx, SourceLocation RLoc) {
3327 Expr *LHSExp = Base;
3330 // Perform default conversions.
3331 if (!LHSExp->getType()->getAs<VectorType>()) {
3332 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3333 if (Result.isInvalid())
3335 LHSExp = Result.take();
3337 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3338 if (Result.isInvalid())
3340 RHSExp = Result.take();
3342 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3343 ExprValueKind VK = VK_LValue;
3344 ExprObjectKind OK = OK_Ordinary;
3346 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3347 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3348 // in the subscript position. As a result, we need to derive the array base
3349 // and index from the expression types.
3350 Expr *BaseExpr, *IndexExpr;
3351 QualType ResultType;
3352 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3355 ResultType = Context.DependentTy;
3356 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3359 ResultType = PTy->getPointeeType();
3360 } else if (const ObjCObjectPointerType *PTy =
3361 LHSTy->getAs<ObjCObjectPointerType>()) {
3365 // Use custom logic if this should be the pseudo-object subscript
3367 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3368 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3370 ResultType = PTy->getPointeeType();
3371 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3372 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3373 << ResultType << BaseExpr->getSourceRange();
3376 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3377 // Handle the uncommon case of "123[Ptr]".
3380 ResultType = PTy->getPointeeType();
3381 } else if (const ObjCObjectPointerType *PTy =
3382 RHSTy->getAs<ObjCObjectPointerType>()) {
3383 // Handle the uncommon case of "123[Ptr]".
3386 ResultType = PTy->getPointeeType();
3387 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3388 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3389 << ResultType << BaseExpr->getSourceRange();
3392 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3393 BaseExpr = LHSExp; // vectors: V[123]
3395 VK = LHSExp->getValueKind();
3396 if (VK != VK_RValue)
3397 OK = OK_VectorComponent;
3399 // FIXME: need to deal with const...
3400 ResultType = VTy->getElementType();
3401 } else if (LHSTy->isArrayType()) {
3402 // If we see an array that wasn't promoted by
3403 // DefaultFunctionArrayLvalueConversion, it must be an array that
3404 // wasn't promoted because of the C90 rule that doesn't
3405 // allow promoting non-lvalue arrays. Warn, then
3406 // force the promotion here.
3407 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3408 LHSExp->getSourceRange();
3409 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3410 CK_ArrayToPointerDecay).take();
3411 LHSTy = LHSExp->getType();
3415 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3416 } else if (RHSTy->isArrayType()) {
3417 // Same as previous, except for 123[f().a] case
3418 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3419 RHSExp->getSourceRange();
3420 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3421 CK_ArrayToPointerDecay).take();
3422 RHSTy = RHSExp->getType();
3426 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3428 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3429 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3432 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3433 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3434 << IndexExpr->getSourceRange());
3436 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3437 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3438 && !IndexExpr->isTypeDependent())
3439 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3441 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3442 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3443 // type. Note that Functions are not objects, and that (in C99 parlance)
3444 // incomplete types are not object types.
3445 if (ResultType->isFunctionType()) {
3446 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3447 << ResultType << BaseExpr->getSourceRange();
3451 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3452 // GNU extension: subscripting on pointer to void
3453 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3454 << BaseExpr->getSourceRange();
3456 // C forbids expressions of unqualified void type from being l-values.
3457 // See IsCForbiddenLValueType.
3458 if (!ResultType.hasQualifiers()) VK = VK_RValue;
3459 } else if (!ResultType->isDependentType() &&
3460 RequireCompleteType(LLoc, ResultType,
3461 diag::err_subscript_incomplete_type, BaseExpr))
3464 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3465 !ResultType.isCForbiddenLValueType());
3467 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3468 ResultType, VK, OK, RLoc));
3471 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3473 ParmVarDecl *Param) {
3474 if (Param->hasUnparsedDefaultArg()) {
3476 diag::err_use_of_default_argument_to_function_declared_later) <<
3477 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3478 Diag(UnparsedDefaultArgLocs[Param],
3479 diag::note_default_argument_declared_here);
3483 if (Param->hasUninstantiatedDefaultArg()) {
3484 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3486 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3489 // Instantiate the expression.
3490 MultiLevelTemplateArgumentList ArgList
3491 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3493 std::pair<const TemplateArgument *, unsigned> Innermost
3494 = ArgList.getInnermost();
3495 InstantiatingTemplate Inst(*this, CallLoc, Param,
3496 ArrayRef<TemplateArgument>(Innermost.first,
3503 // C++ [dcl.fct.default]p5:
3504 // The names in the [default argument] expression are bound, and
3505 // the semantic constraints are checked, at the point where the
3506 // default argument expression appears.
3507 ContextRAII SavedContext(*this, FD);
3508 LocalInstantiationScope Local(*this);
3509 Result = SubstExpr(UninstExpr, ArgList);
3511 if (Result.isInvalid())
3514 // Check the expression as an initializer for the parameter.
3515 InitializedEntity Entity
3516 = InitializedEntity::InitializeParameter(Context, Param);
3517 InitializationKind Kind
3518 = InitializationKind::CreateCopy(Param->getLocation(),
3519 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3520 Expr *ResultE = Result.takeAs<Expr>();
3522 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3523 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3524 if (Result.isInvalid())
3527 Expr *Arg = Result.takeAs<Expr>();
3528 CheckImplicitConversions(Arg, Param->getOuterLocStart());
3529 // Build the default argument expression.
3530 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3533 // If the default expression creates temporaries, we need to
3534 // push them to the current stack of expression temporaries so they'll
3535 // be properly destroyed.
3536 // FIXME: We should really be rebuilding the default argument with new
3537 // bound temporaries; see the comment in PR5810.
3538 // We don't need to do that with block decls, though, because
3539 // blocks in default argument expression can never capture anything.
3540 if (isa<ExprWithCleanups>(Param->getInit())) {
3541 // Set the "needs cleanups" bit regardless of whether there are
3542 // any explicit objects.
3543 ExprNeedsCleanups = true;
3545 // Append all the objects to the cleanup list. Right now, this
3546 // should always be a no-op, because blocks in default argument
3547 // expressions should never be able to capture anything.
3548 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3549 "default argument expression has capturing blocks?");
3552 // We already type-checked the argument, so we know it works.
3553 // Just mark all of the declarations in this potentially-evaluated expression
3554 // as being "referenced".
3555 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3556 /*SkipLocalVariables=*/true);
3557 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3561 Sema::VariadicCallType
3562 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3564 if (Proto && Proto->isVariadic()) {
3565 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3566 return VariadicConstructor;
3567 else if (Fn && Fn->getType()->isBlockPointerType())
3568 return VariadicBlock;
3570 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3571 if (Method->isInstance())
3572 return VariadicMethod;
3574 return VariadicFunction;
3576 return VariadicDoesNotApply;
3579 /// ConvertArgumentsForCall - Converts the arguments specified in
3580 /// Args/NumArgs to the parameter types of the function FDecl with
3581 /// function prototype Proto. Call is the call expression itself, and
3582 /// Fn is the function expression. For a C++ member function, this
3583 /// routine does not attempt to convert the object argument. Returns
3584 /// true if the call is ill-formed.
3586 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3587 FunctionDecl *FDecl,
3588 const FunctionProtoType *Proto,
3589 Expr **Args, unsigned NumArgs,
3590 SourceLocation RParenLoc,
3591 bool IsExecConfig) {
3592 // Bail out early if calling a builtin with custom typechecking.
3593 // We don't need to do this in the
3595 if (unsigned ID = FDecl->getBuiltinID())
3596 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3599 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3600 // assignment, to the types of the corresponding parameter, ...
3601 unsigned NumArgsInProto = Proto->getNumArgs();
3602 bool Invalid = false;
3603 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3604 unsigned FnKind = Fn->getType()->isBlockPointerType()
3606 : (IsExecConfig ? 3 /* kernel function (exec config) */
3607 : 0 /* function */);
3609 // If too few arguments are available (and we don't have default
3610 // arguments for the remaining parameters), don't make the call.
3611 if (NumArgs < NumArgsInProto) {
3612 if (NumArgs < MinArgs) {
3613 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3614 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3615 ? diag::err_typecheck_call_too_few_args_one
3616 : diag::err_typecheck_call_too_few_args_at_least_one)
3618 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3620 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3621 ? diag::err_typecheck_call_too_few_args
3622 : diag::err_typecheck_call_too_few_args_at_least)
3624 << MinArgs << NumArgs << Fn->getSourceRange();
3626 // Emit the location of the prototype.
3627 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3628 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3633 Call->setNumArgs(Context, NumArgsInProto);
3636 // If too many are passed and not variadic, error on the extras and drop
3638 if (NumArgs > NumArgsInProto) {
3639 if (!Proto->isVariadic()) {
3640 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3641 Diag(Args[NumArgsInProto]->getLocStart(),
3642 MinArgs == NumArgsInProto
3643 ? diag::err_typecheck_call_too_many_args_one
3644 : diag::err_typecheck_call_too_many_args_at_most_one)
3646 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3647 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3648 Args[NumArgs-1]->getLocEnd());
3650 Diag(Args[NumArgsInProto]->getLocStart(),
3651 MinArgs == NumArgsInProto
3652 ? diag::err_typecheck_call_too_many_args
3653 : diag::err_typecheck_call_too_many_args_at_most)
3655 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3656 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3657 Args[NumArgs-1]->getLocEnd());
3659 // Emit the location of the prototype.
3660 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3661 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3664 // This deletes the extra arguments.
3665 Call->setNumArgs(Context, NumArgsInProto);
3669 SmallVector<Expr *, 8> AllArgs;
3670 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3672 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3673 Proto, 0, Args, NumArgs, AllArgs, CallType);
3676 unsigned TotalNumArgs = AllArgs.size();
3677 for (unsigned i = 0; i < TotalNumArgs; ++i)
3678 Call->setArg(i, AllArgs[i]);
3683 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3684 FunctionDecl *FDecl,
3685 const FunctionProtoType *Proto,
3686 unsigned FirstProtoArg,
3687 Expr **Args, unsigned NumArgs,
3688 SmallVector<Expr *, 8> &AllArgs,
3689 VariadicCallType CallType,
3690 bool AllowExplicit) {
3691 unsigned NumArgsInProto = Proto->getNumArgs();
3692 unsigned NumArgsToCheck = NumArgs;
3693 bool Invalid = false;
3694 if (NumArgs != NumArgsInProto)
3695 // Use default arguments for missing arguments
3696 NumArgsToCheck = NumArgsInProto;
3698 // Continue to check argument types (even if we have too few/many args).
3699 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3700 QualType ProtoArgType = Proto->getArgType(i);
3704 if (ArgIx < NumArgs) {
3705 Arg = Args[ArgIx++];
3707 if (RequireCompleteType(Arg->getLocStart(),
3709 diag::err_call_incomplete_argument, Arg))
3712 // Pass the argument
3714 if (FDecl && i < FDecl->getNumParams())
3715 Param = FDecl->getParamDecl(i);
3717 // Strip the unbridged-cast placeholder expression off, if applicable.
3718 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3719 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3720 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3721 Arg = stripARCUnbridgedCast(Arg);
3723 InitializedEntity Entity =
3724 Param? InitializedEntity::InitializeParameter(Context, Param)
3725 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3726 Proto->isArgConsumed(i));
3727 ExprResult ArgE = PerformCopyInitialization(Entity,
3730 /*TopLevelOfInitList=*/false,
3732 if (ArgE.isInvalid())
3735 Arg = ArgE.takeAs<Expr>();
3737 Param = FDecl->getParamDecl(i);
3739 ExprResult ArgExpr =
3740 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3741 if (ArgExpr.isInvalid())
3744 Arg = ArgExpr.takeAs<Expr>();
3747 // Check for array bounds violations for each argument to the call. This
3748 // check only triggers warnings when the argument isn't a more complex Expr
3749 // with its own checking, such as a BinaryOperator.
3750 CheckArrayAccess(Arg);
3752 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3753 CheckStaticArrayArgument(CallLoc, Param, Arg);
3755 AllArgs.push_back(Arg);
3758 // If this is a variadic call, handle args passed through "...".
3759 if (CallType != VariadicDoesNotApply) {
3760 // Assume that extern "C" functions with variadic arguments that
3761 // return __unknown_anytype aren't *really* variadic.
3762 if (Proto->getResultType() == Context.UnknownAnyTy &&
3763 FDecl && FDecl->isExternC()) {
3764 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3766 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3767 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3769 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3770 Invalid |= arg.isInvalid();
3771 AllArgs.push_back(arg.take());
3774 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3776 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3777 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3779 Invalid |= Arg.isInvalid();
3780 AllArgs.push_back(Arg.take());
3784 // Check for array bounds violations.
3785 for (unsigned i = ArgIx; i != NumArgs; ++i)
3786 CheckArrayAccess(Args[i]);
3791 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3792 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3793 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3794 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3795 << ATL->getLocalSourceRange();
3798 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3799 /// array parameter, check that it is non-null, and that if it is formed by
3800 /// array-to-pointer decay, the underlying array is sufficiently large.
3802 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3803 /// array type derivation, then for each call to the function, the value of the
3804 /// corresponding actual argument shall provide access to the first element of
3805 /// an array with at least as many elements as specified by the size expression.
3807 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3809 const Expr *ArgExpr) {
3810 // Static array parameters are not supported in C++.
3811 if (!Param || getLangOpts().CPlusPlus)
3814 QualType OrigTy = Param->getOriginalType();
3816 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3817 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3820 if (ArgExpr->isNullPointerConstant(Context,
3821 Expr::NPC_NeverValueDependent)) {
3822 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3823 DiagnoseCalleeStaticArrayParam(*this, Param);
3827 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3831 const ConstantArrayType *ArgCAT =
3832 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3836 if (ArgCAT->getSize().ult(CAT->getSize())) {
3837 Diag(CallLoc, diag::warn_static_array_too_small)
3838 << ArgExpr->getSourceRange()
3839 << (unsigned) ArgCAT->getSize().getZExtValue()
3840 << (unsigned) CAT->getSize().getZExtValue();
3841 DiagnoseCalleeStaticArrayParam(*this, Param);
3845 /// Given a function expression of unknown-any type, try to rebuild it
3846 /// to have a function type.
3847 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3849 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3850 /// This provides the location of the left/right parens and a list of comma
3853 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3854 MultiExprArg ArgExprs, SourceLocation RParenLoc,
3855 Expr *ExecConfig, bool IsExecConfig) {
3856 // Since this might be a postfix expression, get rid of ParenListExprs.
3857 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3858 if (Result.isInvalid()) return ExprError();
3861 if (getLangOpts().CPlusPlus) {
3862 // If this is a pseudo-destructor expression, build the call immediately.
3863 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3864 if (!ArgExprs.empty()) {
3865 // Pseudo-destructor calls should not have any arguments.
3866 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3867 << FixItHint::CreateRemoval(
3868 SourceRange(ArgExprs[0]->getLocStart(),
3869 ArgExprs.back()->getLocEnd()));
3872 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3873 Context.VoidTy, VK_RValue,
3877 // Determine whether this is a dependent call inside a C++ template,
3878 // in which case we won't do any semantic analysis now.
3879 // FIXME: Will need to cache the results of name lookup (including ADL) in
3881 bool Dependent = false;
3882 if (Fn->isTypeDependent())
3884 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
3889 return Owned(new (Context) CUDAKernelCallExpr(
3890 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
3891 Context.DependentTy, VK_RValue, RParenLoc));
3893 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
3894 Context.DependentTy, VK_RValue,
3899 // Determine whether this is a call to an object (C++ [over.call.object]).
3900 if (Fn->getType()->isRecordType())
3901 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3903 ArgExprs.size(), RParenLoc));
3905 if (Fn->getType() == Context.UnknownAnyTy) {
3906 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3907 if (result.isInvalid()) return ExprError();
3911 if (Fn->getType() == Context.BoundMemberTy) {
3912 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3913 ArgExprs.size(), RParenLoc);
3917 // Check for overloaded calls. This can happen even in C due to extensions.
3918 if (Fn->getType() == Context.OverloadTy) {
3919 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3921 // We aren't supposed to apply this logic for if there's an '&' involved.
3922 if (!find.HasFormOfMemberPointer) {
3923 OverloadExpr *ovl = find.Expression;
3924 if (isa<UnresolvedLookupExpr>(ovl)) {
3925 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3926 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3927 ArgExprs.size(), RParenLoc, ExecConfig);
3929 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3930 ArgExprs.size(), RParenLoc);
3935 // If we're directly calling a function, get the appropriate declaration.
3936 if (Fn->getType() == Context.UnknownAnyTy) {
3937 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3938 if (result.isInvalid()) return ExprError();
3942 Expr *NakedFn = Fn->IgnoreParens();
3944 NamedDecl *NDecl = 0;
3945 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3946 if (UnOp->getOpcode() == UO_AddrOf)
3947 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3949 if (isa<DeclRefExpr>(NakedFn))
3950 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3951 else if (isa<MemberExpr>(NakedFn))
3952 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3954 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3955 ArgExprs.size(), RParenLoc, ExecConfig,
3960 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3961 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3962 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3964 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3965 << "cudaConfigureCall");
3966 QualType ConfigQTy = ConfigDecl->getType();
3968 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3969 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
3970 MarkFunctionReferenced(LLLLoc, ConfigDecl);
3972 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3973 /*IsExecConfig=*/true);
3976 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3978 /// __builtin_astype( value, dst type )
3980 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3981 SourceLocation BuiltinLoc,
3982 SourceLocation RParenLoc) {
3983 ExprValueKind VK = VK_RValue;
3984 ExprObjectKind OK = OK_Ordinary;
3985 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3986 QualType SrcTy = E->getType();
3987 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3988 return ExprError(Diag(BuiltinLoc,
3989 diag::err_invalid_astype_of_different_size)
3992 << E->getSourceRange());
3993 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3997 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3998 /// i.e. an expression not of \p OverloadTy. The expression should
3999 /// unary-convert to an expression of function-pointer or
4000 /// block-pointer type.
4002 /// \param NDecl the declaration being called, if available
4004 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4005 SourceLocation LParenLoc,
4006 Expr **Args, unsigned NumArgs,
4007 SourceLocation RParenLoc,
4008 Expr *Config, bool IsExecConfig) {
4009 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4010 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4012 // Promote the function operand.
4013 // We special-case function promotion here because we only allow promoting
4014 // builtin functions to function pointers in the callee of a call.
4017 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4018 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4019 CK_BuiltinFnToFnPtr).take();
4021 Result = UsualUnaryConversions(Fn);
4023 if (Result.isInvalid())
4027 // Make the call expr early, before semantic checks. This guarantees cleanup
4028 // of arguments and function on error.
4031 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4032 cast<CallExpr>(Config),
4033 llvm::makeArrayRef(Args,NumArgs),
4038 TheCall = new (Context) CallExpr(Context, Fn,
4039 llvm::makeArrayRef(Args, NumArgs),
4044 // Bail out early if calling a builtin with custom typechecking.
4045 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4046 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4049 const FunctionType *FuncT;
4050 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4051 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4052 // have type pointer to function".
4053 FuncT = PT->getPointeeType()->getAs<FunctionType>();
4055 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4056 << Fn->getType() << Fn->getSourceRange());
4057 } else if (const BlockPointerType *BPT =
4058 Fn->getType()->getAs<BlockPointerType>()) {
4059 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4061 // Handle calls to expressions of unknown-any type.
4062 if (Fn->getType() == Context.UnknownAnyTy) {
4063 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4064 if (rewrite.isInvalid()) return ExprError();
4065 Fn = rewrite.take();
4066 TheCall->setCallee(Fn);
4070 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4071 << Fn->getType() << Fn->getSourceRange());
4074 if (getLangOpts().CUDA) {
4076 // CUDA: Kernel calls must be to global functions
4077 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4078 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4079 << FDecl->getName() << Fn->getSourceRange());
4081 // CUDA: Kernel function must have 'void' return type
4082 if (!FuncT->getResultType()->isVoidType())
4083 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4084 << Fn->getType() << Fn->getSourceRange());
4086 // CUDA: Calls to global functions must be configured
4087 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4088 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4089 << FDecl->getName() << Fn->getSourceRange());
4093 // Check for a valid return type
4094 if (CheckCallReturnType(FuncT->getResultType(),
4095 Fn->getLocStart(), TheCall,
4099 // We know the result type of the call, set it.
4100 TheCall->setType(FuncT->getCallResultType(Context));
4101 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4103 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4105 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4106 RParenLoc, IsExecConfig))
4109 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4112 // Check if we have too few/too many template arguments, based
4113 // on our knowledge of the function definition.
4114 const FunctionDecl *Def = 0;
4115 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4116 Proto = Def->getType()->getAs<FunctionProtoType>();
4117 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4118 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4119 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4122 // If the function we're calling isn't a function prototype, but we have
4123 // a function prototype from a prior declaratiom, use that prototype.
4124 if (!FDecl->hasPrototype())
4125 Proto = FDecl->getType()->getAs<FunctionProtoType>();
4128 // Promote the arguments (C99 6.5.2.2p6).
4129 for (unsigned i = 0; i != NumArgs; i++) {
4130 Expr *Arg = Args[i];
4132 if (Proto && i < Proto->getNumArgs()) {
4133 InitializedEntity Entity
4134 = InitializedEntity::InitializeParameter(Context,
4135 Proto->getArgType(i),
4136 Proto->isArgConsumed(i));
4137 ExprResult ArgE = PerformCopyInitialization(Entity,
4140 if (ArgE.isInvalid())
4143 Arg = ArgE.takeAs<Expr>();
4146 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4148 if (ArgE.isInvalid())
4151 Arg = ArgE.takeAs<Expr>();
4154 if (RequireCompleteType(Arg->getLocStart(),
4156 diag::err_call_incomplete_argument, Arg))
4159 TheCall->setArg(i, Arg);
4163 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4164 if (!Method->isStatic())
4165 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4166 << Fn->getSourceRange());
4168 // Check for sentinels
4170 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4172 // Do special checking on direct calls to functions.
4174 if (CheckFunctionCall(FDecl, TheCall, Proto))
4178 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4180 if (CheckBlockCall(NDecl, TheCall, Proto))
4184 return MaybeBindToTemporary(TheCall);
4188 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4189 SourceLocation RParenLoc, Expr *InitExpr) {
4190 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4191 // FIXME: put back this assert when initializers are worked out.
4192 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4194 TypeSourceInfo *TInfo;
4195 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4197 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4199 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4203 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4204 SourceLocation RParenLoc, Expr *LiteralExpr) {
4205 QualType literalType = TInfo->getType();
4207 if (literalType->isArrayType()) {
4208 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4209 diag::err_illegal_decl_array_incomplete_type,
4210 SourceRange(LParenLoc,
4211 LiteralExpr->getSourceRange().getEnd())))
4213 if (literalType->isVariableArrayType())
4214 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4215 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4216 } else if (!literalType->isDependentType() &&
4217 RequireCompleteType(LParenLoc, literalType,
4218 diag::err_typecheck_decl_incomplete_type,
4219 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4222 InitializedEntity Entity
4223 = InitializedEntity::InitializeTemporary(literalType);
4224 InitializationKind Kind
4225 = InitializationKind::CreateCStyleCast(LParenLoc,
4226 SourceRange(LParenLoc, RParenLoc),
4228 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4229 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4231 if (Result.isInvalid())
4233 LiteralExpr = Result.get();
4235 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4236 if (isFileScope) { // 6.5.2.5p3
4237 if (CheckForConstantInitializer(LiteralExpr, literalType))
4241 // In C, compound literals are l-values for some reason.
4242 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4244 return MaybeBindToTemporary(
4245 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4246 VK, LiteralExpr, isFileScope));
4250 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4251 SourceLocation RBraceLoc) {
4252 // Immediately handle non-overload placeholders. Overloads can be
4253 // resolved contextually, but everything else here can't.
4254 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4255 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4256 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4258 // Ignore failures; dropping the entire initializer list because
4259 // of one failure would be terrible for indexing/etc.
4260 if (result.isInvalid()) continue;
4262 InitArgList[I] = result.take();
4266 // Semantic analysis for initializers is done by ActOnDeclarator() and
4267 // CheckInitializer() - it requires knowledge of the object being intialized.
4269 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4271 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4275 /// Do an explicit extend of the given block pointer if we're in ARC.
4276 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4277 assert(E.get()->getType()->isBlockPointerType());
4278 assert(E.get()->isRValue());
4280 // Only do this in an r-value context.
4281 if (!S.getLangOpts().ObjCAutoRefCount) return;
4283 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4284 CK_ARCExtendBlockObject, E.get(),
4285 /*base path*/ 0, VK_RValue);
4286 S.ExprNeedsCleanups = true;
4289 /// Prepare a conversion of the given expression to an ObjC object
4291 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4292 QualType type = E.get()->getType();
4293 if (type->isObjCObjectPointerType()) {
4295 } else if (type->isBlockPointerType()) {
4296 maybeExtendBlockObject(*this, E);
4297 return CK_BlockPointerToObjCPointerCast;
4299 assert(type->isPointerType());
4300 return CK_CPointerToObjCPointerCast;
4304 /// Prepares for a scalar cast, performing all the necessary stages
4305 /// except the final cast and returning the kind required.
4306 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4307 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4308 // Also, callers should have filtered out the invalid cases with
4309 // pointers. Everything else should be possible.
4311 QualType SrcTy = Src.get()->getType();
4312 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4315 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4316 case Type::STK_MemberPointer:
4317 llvm_unreachable("member pointer type in C");
4319 case Type::STK_CPointer:
4320 case Type::STK_BlockPointer:
4321 case Type::STK_ObjCObjectPointer:
4322 switch (DestTy->getScalarTypeKind()) {
4323 case Type::STK_CPointer:
4325 case Type::STK_BlockPointer:
4326 return (SrcKind == Type::STK_BlockPointer
4327 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4328 case Type::STK_ObjCObjectPointer:
4329 if (SrcKind == Type::STK_ObjCObjectPointer)
4331 if (SrcKind == Type::STK_CPointer)
4332 return CK_CPointerToObjCPointerCast;
4333 maybeExtendBlockObject(*this, Src);
4334 return CK_BlockPointerToObjCPointerCast;
4335 case Type::STK_Bool:
4336 return CK_PointerToBoolean;
4337 case Type::STK_Integral:
4338 return CK_PointerToIntegral;
4339 case Type::STK_Floating:
4340 case Type::STK_FloatingComplex:
4341 case Type::STK_IntegralComplex:
4342 case Type::STK_MemberPointer:
4343 llvm_unreachable("illegal cast from pointer");
4345 llvm_unreachable("Should have returned before this");
4347 case Type::STK_Bool: // casting from bool is like casting from an integer
4348 case Type::STK_Integral:
4349 switch (DestTy->getScalarTypeKind()) {
4350 case Type::STK_CPointer:
4351 case Type::STK_ObjCObjectPointer:
4352 case Type::STK_BlockPointer:
4353 if (Src.get()->isNullPointerConstant(Context,
4354 Expr::NPC_ValueDependentIsNull))
4355 return CK_NullToPointer;
4356 return CK_IntegralToPointer;
4357 case Type::STK_Bool:
4358 return CK_IntegralToBoolean;
4359 case Type::STK_Integral:
4360 return CK_IntegralCast;
4361 case Type::STK_Floating:
4362 return CK_IntegralToFloating;
4363 case Type::STK_IntegralComplex:
4364 Src = ImpCastExprToType(Src.take(),
4365 DestTy->castAs<ComplexType>()->getElementType(),
4367 return CK_IntegralRealToComplex;
4368 case Type::STK_FloatingComplex:
4369 Src = ImpCastExprToType(Src.take(),
4370 DestTy->castAs<ComplexType>()->getElementType(),
4371 CK_IntegralToFloating);
4372 return CK_FloatingRealToComplex;
4373 case Type::STK_MemberPointer:
4374 llvm_unreachable("member pointer type in C");
4376 llvm_unreachable("Should have returned before this");
4378 case Type::STK_Floating:
4379 switch (DestTy->getScalarTypeKind()) {
4380 case Type::STK_Floating:
4381 return CK_FloatingCast;
4382 case Type::STK_Bool:
4383 return CK_FloatingToBoolean;
4384 case Type::STK_Integral:
4385 return CK_FloatingToIntegral;
4386 case Type::STK_FloatingComplex:
4387 Src = ImpCastExprToType(Src.take(),
4388 DestTy->castAs<ComplexType>()->getElementType(),
4390 return CK_FloatingRealToComplex;
4391 case Type::STK_IntegralComplex:
4392 Src = ImpCastExprToType(Src.take(),
4393 DestTy->castAs<ComplexType>()->getElementType(),
4394 CK_FloatingToIntegral);
4395 return CK_IntegralRealToComplex;
4396 case Type::STK_CPointer:
4397 case Type::STK_ObjCObjectPointer:
4398 case Type::STK_BlockPointer:
4399 llvm_unreachable("valid float->pointer cast?");
4400 case Type::STK_MemberPointer:
4401 llvm_unreachable("member pointer type in C");
4403 llvm_unreachable("Should have returned before this");
4405 case Type::STK_FloatingComplex:
4406 switch (DestTy->getScalarTypeKind()) {
4407 case Type::STK_FloatingComplex:
4408 return CK_FloatingComplexCast;
4409 case Type::STK_IntegralComplex:
4410 return CK_FloatingComplexToIntegralComplex;
4411 case Type::STK_Floating: {
4412 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4413 if (Context.hasSameType(ET, DestTy))
4414 return CK_FloatingComplexToReal;
4415 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4416 return CK_FloatingCast;
4418 case Type::STK_Bool:
4419 return CK_FloatingComplexToBoolean;
4420 case Type::STK_Integral:
4421 Src = ImpCastExprToType(Src.take(),
4422 SrcTy->castAs<ComplexType>()->getElementType(),
4423 CK_FloatingComplexToReal);
4424 return CK_FloatingToIntegral;
4425 case Type::STK_CPointer:
4426 case Type::STK_ObjCObjectPointer:
4427 case Type::STK_BlockPointer:
4428 llvm_unreachable("valid complex float->pointer cast?");
4429 case Type::STK_MemberPointer:
4430 llvm_unreachable("member pointer type in C");
4432 llvm_unreachable("Should have returned before this");
4434 case Type::STK_IntegralComplex:
4435 switch (DestTy->getScalarTypeKind()) {
4436 case Type::STK_FloatingComplex:
4437 return CK_IntegralComplexToFloatingComplex;
4438 case Type::STK_IntegralComplex:
4439 return CK_IntegralComplexCast;
4440 case Type::STK_Integral: {
4441 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4442 if (Context.hasSameType(ET, DestTy))
4443 return CK_IntegralComplexToReal;
4444 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4445 return CK_IntegralCast;
4447 case Type::STK_Bool:
4448 return CK_IntegralComplexToBoolean;
4449 case Type::STK_Floating:
4450 Src = ImpCastExprToType(Src.take(),
4451 SrcTy->castAs<ComplexType>()->getElementType(),
4452 CK_IntegralComplexToReal);
4453 return CK_IntegralToFloating;
4454 case Type::STK_CPointer:
4455 case Type::STK_ObjCObjectPointer:
4456 case Type::STK_BlockPointer:
4457 llvm_unreachable("valid complex int->pointer cast?");
4458 case Type::STK_MemberPointer:
4459 llvm_unreachable("member pointer type in C");
4461 llvm_unreachable("Should have returned before this");
4464 llvm_unreachable("Unhandled scalar cast");
4467 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4469 assert(VectorTy->isVectorType() && "Not a vector type!");
4471 if (Ty->isVectorType() || Ty->isIntegerType()) {
4472 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4473 return Diag(R.getBegin(),
4474 Ty->isVectorType() ?
4475 diag::err_invalid_conversion_between_vectors :
4476 diag::err_invalid_conversion_between_vector_and_integer)
4477 << VectorTy << Ty << R;
4479 return Diag(R.getBegin(),
4480 diag::err_invalid_conversion_between_vector_and_scalar)
4481 << VectorTy << Ty << R;
4487 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4488 Expr *CastExpr, CastKind &Kind) {
4489 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4491 QualType SrcTy = CastExpr->getType();
4493 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4494 // an ExtVectorType.
4495 // In OpenCL, casts between vectors of different types are not allowed.
4496 // (See OpenCL 6.2).
4497 if (SrcTy->isVectorType()) {
4498 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4499 || (getLangOpts().OpenCL &&
4500 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4501 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4502 << DestTy << SrcTy << R;
4506 return Owned(CastExpr);
4509 // All non-pointer scalars can be cast to ExtVector type. The appropriate
4510 // conversion will take place first from scalar to elt type, and then
4511 // splat from elt type to vector.
4512 if (SrcTy->isPointerType())
4513 return Diag(R.getBegin(),
4514 diag::err_invalid_conversion_between_vector_and_scalar)
4515 << DestTy << SrcTy << R;
4517 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4518 ExprResult CastExprRes = Owned(CastExpr);
4519 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4520 if (CastExprRes.isInvalid())
4522 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4524 Kind = CK_VectorSplat;
4525 return Owned(CastExpr);
4529 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4530 Declarator &D, ParsedType &Ty,
4531 SourceLocation RParenLoc, Expr *CastExpr) {
4532 assert(!D.isInvalidType() && (CastExpr != 0) &&
4533 "ActOnCastExpr(): missing type or expr");
4535 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4536 if (D.isInvalidType())
4539 if (getLangOpts().CPlusPlus) {
4540 // Check that there are no default arguments (C++ only).
4541 CheckExtraCXXDefaultArguments(D);
4544 checkUnusedDeclAttributes(D);
4546 QualType castType = castTInfo->getType();
4547 Ty = CreateParsedType(castType, castTInfo);
4549 bool isVectorLiteral = false;
4551 // Check for an altivec or OpenCL literal,
4552 // i.e. all the elements are integer constants.
4553 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4554 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4555 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4556 && castType->isVectorType() && (PE || PLE)) {
4557 if (PLE && PLE->getNumExprs() == 0) {
4558 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4561 if (PE || PLE->getNumExprs() == 1) {
4562 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4563 if (!E->getType()->isVectorType())
4564 isVectorLiteral = true;
4567 isVectorLiteral = true;
4570 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4571 // then handle it as such.
4572 if (isVectorLiteral)
4573 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4575 // If the Expr being casted is a ParenListExpr, handle it specially.
4576 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4577 // sequence of BinOp comma operators.
4578 if (isa<ParenListExpr>(CastExpr)) {
4579 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4580 if (Result.isInvalid()) return ExprError();
4581 CastExpr = Result.take();
4584 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4587 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4588 SourceLocation RParenLoc, Expr *E,
4589 TypeSourceInfo *TInfo) {
4590 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4591 "Expected paren or paren list expression");
4596 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4597 exprs = PE->getExprs();
4598 numExprs = PE->getNumExprs();
4600 subExpr = cast<ParenExpr>(E)->getSubExpr();
4605 QualType Ty = TInfo->getType();
4606 assert(Ty->isVectorType() && "Expected vector type");
4608 SmallVector<Expr *, 8> initExprs;
4609 const VectorType *VTy = Ty->getAs<VectorType>();
4610 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4612 // '(...)' form of vector initialization in AltiVec: the number of
4613 // initializers must be one or must match the size of the vector.
4614 // If a single value is specified in the initializer then it will be
4615 // replicated to all the components of the vector
4616 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4617 // The number of initializers must be one or must match the size of the
4618 // vector. If a single value is specified in the initializer then it will
4619 // be replicated to all the components of the vector
4620 if (numExprs == 1) {
4621 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4622 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4623 if (Literal.isInvalid())
4625 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4626 PrepareScalarCast(Literal, ElemTy));
4627 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4629 else if (numExprs < numElems) {
4630 Diag(E->getExprLoc(),
4631 diag::err_incorrect_number_of_vector_initializers);
4635 initExprs.append(exprs, exprs + numExprs);
4638 // For OpenCL, when the number of initializers is a single value,
4639 // it will be replicated to all components of the vector.
4640 if (getLangOpts().OpenCL &&
4641 VTy->getVectorKind() == VectorType::GenericVector &&
4643 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4644 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4645 if (Literal.isInvalid())
4647 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4648 PrepareScalarCast(Literal, ElemTy));
4649 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4652 initExprs.append(exprs, exprs + numExprs);
4654 // FIXME: This means that pretty-printing the final AST will produce curly
4655 // braces instead of the original commas.
4656 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4657 initExprs, RParenLoc);
4659 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4662 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4663 /// the ParenListExpr into a sequence of comma binary operators.
4665 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4666 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4668 return Owned(OrigExpr);
4670 ExprResult Result(E->getExpr(0));
4672 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4673 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4676 if (Result.isInvalid()) return ExprError();
4678 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4681 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4684 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4685 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
4689 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4690 /// constant and the other is not a pointer. Returns true if a diagnostic is
4692 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4693 SourceLocation QuestionLoc) {
4694 Expr *NullExpr = LHSExpr;
4695 Expr *NonPointerExpr = RHSExpr;
4696 Expr::NullPointerConstantKind NullKind =
4697 NullExpr->isNullPointerConstant(Context,
4698 Expr::NPC_ValueDependentIsNotNull);
4700 if (NullKind == Expr::NPCK_NotNull) {
4702 NonPointerExpr = LHSExpr;
4704 NullExpr->isNullPointerConstant(Context,
4705 Expr::NPC_ValueDependentIsNotNull);
4708 if (NullKind == Expr::NPCK_NotNull)
4711 if (NullKind == Expr::NPCK_ZeroExpression)
4714 if (NullKind == Expr::NPCK_ZeroLiteral) {
4715 // In this case, check to make sure that we got here from a "NULL"
4716 // string in the source code.
4717 NullExpr = NullExpr->IgnoreParenImpCasts();
4718 SourceLocation loc = NullExpr->getExprLoc();
4719 if (!findMacroSpelling(loc, "NULL"))
4723 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4724 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4725 << NonPointerExpr->getType() << DiagType
4726 << NonPointerExpr->getSourceRange();
4730 /// \brief Return false if the condition expression is valid, true otherwise.
4731 static bool checkCondition(Sema &S, Expr *Cond) {
4732 QualType CondTy = Cond->getType();
4735 if (CondTy->isScalarType()) return false;
4737 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4738 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4741 // Emit the proper error message.
4742 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4743 diag::err_typecheck_cond_expect_scalar :
4744 diag::err_typecheck_cond_expect_scalar_or_vector)
4749 /// \brief Return false if the two expressions can be converted to a vector,
4751 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4754 // Both operands should be of scalar type.
4755 if (!LHS.get()->getType()->isScalarType()) {
4756 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4760 if (!RHS.get()->getType()->isScalarType()) {
4761 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4766 // Implicity convert these scalars to the type of the condition.
4767 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4768 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4772 /// \brief Handle when one or both operands are void type.
4773 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4775 Expr *LHSExpr = LHS.get();
4776 Expr *RHSExpr = RHS.get();
4778 if (!LHSExpr->getType()->isVoidType())
4779 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4780 << RHSExpr->getSourceRange();
4781 if (!RHSExpr->getType()->isVoidType())
4782 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4783 << LHSExpr->getSourceRange();
4784 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4785 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4786 return S.Context.VoidTy;
4789 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4791 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4792 QualType PointerTy) {
4793 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4794 !NullExpr.get()->isNullPointerConstant(S.Context,
4795 Expr::NPC_ValueDependentIsNull))
4798 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4802 /// \brief Checks compatibility between two pointers and return the resulting
4804 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4806 SourceLocation Loc) {
4807 QualType LHSTy = LHS.get()->getType();
4808 QualType RHSTy = RHS.get()->getType();
4810 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4811 // Two identical pointers types are always compatible.
4815 QualType lhptee, rhptee;
4817 // Get the pointee types.
4818 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4819 lhptee = LHSBTy->getPointeeType();
4820 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4822 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4823 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4826 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4827 // differently qualified versions of compatible types, the result type is
4828 // a pointer to an appropriately qualified version of the composite
4831 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4832 // clause doesn't make sense for our extensions. E.g. address space 2 should
4833 // be incompatible with address space 3: they may live on different devices or
4835 Qualifiers lhQual = lhptee.getQualifiers();
4836 Qualifiers rhQual = rhptee.getQualifiers();
4838 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4839 lhQual.removeCVRQualifiers();
4840 rhQual.removeCVRQualifiers();
4842 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4843 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4845 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4847 if (CompositeTy.isNull()) {
4848 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4849 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4850 << RHS.get()->getSourceRange();
4851 // In this situation, we assume void* type. No especially good
4852 // reason, but this is what gcc does, and we do have to pick
4853 // to get a consistent AST.
4854 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4855 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4856 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4860 // The pointer types are compatible.
4861 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4862 ResultTy = S.Context.getPointerType(ResultTy);
4864 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4865 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4869 /// \brief Return the resulting type when the operands are both block pointers.
4870 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4873 SourceLocation Loc) {
4874 QualType LHSTy = LHS.get()->getType();
4875 QualType RHSTy = RHS.get()->getType();
4877 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4878 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4879 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4880 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4881 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4884 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4885 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4886 << RHS.get()->getSourceRange();
4890 // We have 2 block pointer types.
4891 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4894 /// \brief Return the resulting type when the operands are both pointers.
4896 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4898 SourceLocation Loc) {
4899 // get the pointer types
4900 QualType LHSTy = LHS.get()->getType();
4901 QualType RHSTy = RHS.get()->getType();
4903 // get the "pointed to" types
4904 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4905 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4907 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4908 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4909 // Figure out necessary qualifiers (C99 6.5.15p6)
4910 QualType destPointee
4911 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4912 QualType destType = S.Context.getPointerType(destPointee);
4913 // Add qualifiers if necessary.
4914 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4915 // Promote to void*.
4916 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4919 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4920 QualType destPointee
4921 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4922 QualType destType = S.Context.getPointerType(destPointee);
4923 // Add qualifiers if necessary.
4924 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4925 // Promote to void*.
4926 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4930 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4933 /// \brief Return false if the first expression is not an integer and the second
4934 /// expression is not a pointer, true otherwise.
4935 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4936 Expr* PointerExpr, SourceLocation Loc,
4937 bool IsIntFirstExpr) {
4938 if (!PointerExpr->getType()->isPointerType() ||
4939 !Int.get()->getType()->isIntegerType())
4942 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4943 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4945 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4946 << Expr1->getType() << Expr2->getType()
4947 << Expr1->getSourceRange() << Expr2->getSourceRange();
4948 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4949 CK_IntegralToPointer);
4953 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4954 /// In that case, LHS = cond.
4956 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4957 ExprResult &RHS, ExprValueKind &VK,
4959 SourceLocation QuestionLoc) {
4961 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4962 if (!LHSResult.isUsable()) return QualType();
4965 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4966 if (!RHSResult.isUsable()) return QualType();
4969 // C++ is sufficiently different to merit its own checker.
4970 if (getLangOpts().CPlusPlus)
4971 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4976 Cond = UsualUnaryConversions(Cond.take());
4977 if (Cond.isInvalid())
4979 LHS = UsualUnaryConversions(LHS.take());
4980 if (LHS.isInvalid())
4982 RHS = UsualUnaryConversions(RHS.take());
4983 if (RHS.isInvalid())
4986 QualType CondTy = Cond.get()->getType();
4987 QualType LHSTy = LHS.get()->getType();
4988 QualType RHSTy = RHS.get()->getType();
4990 // first, check the condition.
4991 if (checkCondition(*this, Cond.get()))
4994 // Now check the two expressions.
4995 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4996 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4998 // OpenCL: If the condition is a vector, and both operands are scalar,
4999 // attempt to implicity convert them to the vector type to act like the
5001 if (getLangOpts().OpenCL && CondTy->isVectorType())
5002 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5005 // If both operands have arithmetic type, do the usual arithmetic conversions
5006 // to find a common type: C99 6.5.15p3,5.
5007 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5008 UsualArithmeticConversions(LHS, RHS);
5009 if (LHS.isInvalid() || RHS.isInvalid())
5011 return LHS.get()->getType();
5014 // If both operands are the same structure or union type, the result is that
5016 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5017 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5018 if (LHSRT->getDecl() == RHSRT->getDecl())
5019 // "If both the operands have structure or union type, the result has
5020 // that type." This implies that CV qualifiers are dropped.
5021 return LHSTy.getUnqualifiedType();
5022 // FIXME: Type of conditional expression must be complete in C mode.
5025 // C99 6.5.15p5: "If both operands have void type, the result has void type."
5026 // The following || allows only one side to be void (a GCC-ism).
5027 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5028 return checkConditionalVoidType(*this, LHS, RHS);
5031 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5032 // the type of the other operand."
5033 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5034 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5036 // All objective-c pointer type analysis is done here.
5037 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5039 if (LHS.isInvalid() || RHS.isInvalid())
5041 if (!compositeType.isNull())
5042 return compositeType;
5045 // Handle block pointer types.
5046 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5047 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5050 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5051 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5052 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5055 // GCC compatibility: soften pointer/integer mismatch. Note that
5056 // null pointers have been filtered out by this point.
5057 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5058 /*isIntFirstExpr=*/true))
5060 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5061 /*isIntFirstExpr=*/false))
5064 // Emit a better diagnostic if one of the expressions is a null pointer
5065 // constant and the other is not a pointer type. In this case, the user most
5066 // likely forgot to take the address of the other expression.
5067 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5070 // Otherwise, the operands are not compatible.
5071 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5072 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5073 << RHS.get()->getSourceRange();
5077 /// FindCompositeObjCPointerType - Helper method to find composite type of
5078 /// two objective-c pointer types of the two input expressions.
5079 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5080 SourceLocation QuestionLoc) {
5081 QualType LHSTy = LHS.get()->getType();
5082 QualType RHSTy = RHS.get()->getType();
5084 // Handle things like Class and struct objc_class*. Here we case the result
5085 // to the pseudo-builtin, because that will be implicitly cast back to the
5086 // redefinition type if an attempt is made to access its fields.
5087 if (LHSTy->isObjCClassType() &&
5088 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5089 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5092 if (RHSTy->isObjCClassType() &&
5093 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5094 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5097 // And the same for struct objc_object* / id
5098 if (LHSTy->isObjCIdType() &&
5099 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5100 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5103 if (RHSTy->isObjCIdType() &&
5104 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5105 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5108 // And the same for struct objc_selector* / SEL
5109 if (Context.isObjCSelType(LHSTy) &&
5110 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5111 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5114 if (Context.isObjCSelType(RHSTy) &&
5115 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5116 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5119 // Check constraints for Objective-C object pointers types.
5120 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5122 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5123 // Two identical object pointer types are always compatible.
5126 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5127 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5128 QualType compositeType = LHSTy;
5130 // If both operands are interfaces and either operand can be
5131 // assigned to the other, use that type as the composite
5132 // type. This allows
5133 // xxx ? (A*) a : (B*) b
5134 // where B is a subclass of A.
5136 // Additionally, as for assignment, if either type is 'id'
5137 // allow silent coercion. Finally, if the types are
5138 // incompatible then make sure to use 'id' as the composite
5139 // type so the result is acceptable for sending messages to.
5141 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5142 // It could return the composite type.
5143 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5144 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5145 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5146 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5147 } else if ((LHSTy->isObjCQualifiedIdType() ||
5148 RHSTy->isObjCQualifiedIdType()) &&
5149 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5150 // Need to handle "id<xx>" explicitly.
5151 // GCC allows qualified id and any Objective-C type to devolve to
5152 // id. Currently localizing to here until clear this should be
5153 // part of ObjCQualifiedIdTypesAreCompatible.
5154 compositeType = Context.getObjCIdType();
5155 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5156 compositeType = Context.getObjCIdType();
5157 } else if (!(compositeType =
5158 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5161 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5163 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5164 QualType incompatTy = Context.getObjCIdType();
5165 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5166 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5169 // The object pointer types are compatible.
5170 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5171 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5172 return compositeType;
5174 // Check Objective-C object pointer types and 'void *'
5175 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5176 if (getLangOpts().ObjCAutoRefCount) {
5177 // ARC forbids the implicit conversion of object pointers to 'void *',
5178 // so these types are not compatible.
5179 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5180 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5184 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5185 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5186 QualType destPointee
5187 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5188 QualType destType = Context.getPointerType(destPointee);
5189 // Add qualifiers if necessary.
5190 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5191 // Promote to void*.
5192 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5195 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5196 if (getLangOpts().ObjCAutoRefCount) {
5197 // ARC forbids the implicit conversion of object pointers to 'void *',
5198 // so these types are not compatible.
5199 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5200 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5204 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5205 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5206 QualType destPointee
5207 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5208 QualType destType = Context.getPointerType(destPointee);
5209 // Add qualifiers if necessary.
5210 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5211 // Promote to void*.
5212 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5218 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5219 /// ParenRange in parentheses.
5220 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5221 const PartialDiagnostic &Note,
5222 SourceRange ParenRange) {
5223 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5224 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5226 Self.Diag(Loc, Note)
5227 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5228 << FixItHint::CreateInsertion(EndLoc, ")");
5230 // We can't display the parentheses, so just show the bare note.
5231 Self.Diag(Loc, Note) << ParenRange;
5235 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5236 return Opc >= BO_Mul && Opc <= BO_Shr;
5239 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5240 /// expression, either using a built-in or overloaded operator,
5241 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5243 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5245 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5246 E = E->IgnoreImpCasts();
5247 E = E->IgnoreConversionOperator();
5248 E = E->IgnoreImpCasts();
5250 // Built-in binary operator.
5251 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5252 if (IsArithmeticOp(OP->getOpcode())) {
5253 *Opcode = OP->getOpcode();
5254 *RHSExprs = OP->getRHS();
5259 // Overloaded operator.
5260 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5261 if (Call->getNumArgs() != 2)
5264 // Make sure this is really a binary operator that is safe to pass into
5265 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5266 OverloadedOperatorKind OO = Call->getOperator();
5267 if (OO < OO_Plus || OO > OO_Arrow)
5270 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5271 if (IsArithmeticOp(OpKind)) {
5273 *RHSExprs = Call->getArg(1);
5281 static bool IsLogicOp(BinaryOperatorKind Opc) {
5282 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5285 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5286 /// or is a logical expression such as (x==y) which has int type, but is
5287 /// commonly interpreted as boolean.
5288 static bool ExprLooksBoolean(Expr *E) {
5289 E = E->IgnoreParenImpCasts();
5291 if (E->getType()->isBooleanType())
5293 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5294 return IsLogicOp(OP->getOpcode());
5295 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5296 return OP->getOpcode() == UO_LNot;
5301 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5302 /// and binary operator are mixed in a way that suggests the programmer assumed
5303 /// the conditional operator has higher precedence, for example:
5304 /// "int x = a + someBinaryCondition ? 1 : 2".
5305 static void DiagnoseConditionalPrecedence(Sema &Self,
5306 SourceLocation OpLoc,
5310 BinaryOperatorKind CondOpcode;
5313 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5315 if (!ExprLooksBoolean(CondRHS))
5318 // The condition is an arithmetic binary expression, with a right-
5319 // hand side that looks boolean, so warn.
5321 Self.Diag(OpLoc, diag::warn_precedence_conditional)
5322 << Condition->getSourceRange()
5323 << BinaryOperator::getOpcodeStr(CondOpcode);
5325 SuggestParentheses(Self, OpLoc,
5326 Self.PDiag(diag::note_precedence_silence)
5327 << BinaryOperator::getOpcodeStr(CondOpcode),
5328 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5330 SuggestParentheses(Self, OpLoc,
5331 Self.PDiag(diag::note_precedence_conditional_first),
5332 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5335 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5336 /// in the case of a the GNU conditional expr extension.
5337 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5338 SourceLocation ColonLoc,
5339 Expr *CondExpr, Expr *LHSExpr,
5341 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5342 // was the condition.
5343 OpaqueValueExpr *opaqueValue = 0;
5344 Expr *commonExpr = 0;
5346 commonExpr = CondExpr;
5348 // We usually want to apply unary conversions *before* saving, except
5349 // in the special case of a C++ l-value conditional.
5350 if (!(getLangOpts().CPlusPlus
5351 && !commonExpr->isTypeDependent()
5352 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5353 && commonExpr->isGLValue()
5354 && commonExpr->isOrdinaryOrBitFieldObject()
5355 && RHSExpr->isOrdinaryOrBitFieldObject()
5356 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5357 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5358 if (commonRes.isInvalid())
5360 commonExpr = commonRes.take();
5363 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5364 commonExpr->getType(),
5365 commonExpr->getValueKind(),
5366 commonExpr->getObjectKind(),
5368 LHSExpr = CondExpr = opaqueValue;
5371 ExprValueKind VK = VK_RValue;
5372 ExprObjectKind OK = OK_Ordinary;
5373 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5374 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5375 VK, OK, QuestionLoc);
5376 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5380 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5384 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5385 LHS.take(), ColonLoc,
5386 RHS.take(), result, VK, OK));
5388 return Owned(new (Context)
5389 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5390 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5394 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5395 // being closely modeled after the C99 spec:-). The odd characteristic of this
5396 // routine is it effectively iqnores the qualifiers on the top level pointee.
5397 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5398 // FIXME: add a couple examples in this comment.
5399 static Sema::AssignConvertType
5400 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5401 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5402 assert(RHSType.isCanonical() && "RHS not canonicalized!");
5404 // get the "pointed to" type (ignoring qualifiers at the top level)
5405 const Type *lhptee, *rhptee;
5406 Qualifiers lhq, rhq;
5407 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5408 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5410 Sema::AssignConvertType ConvTy = Sema::Compatible;
5412 // C99 6.5.16.1p1: This following citation is common to constraints
5413 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5414 // qualifiers of the type *pointed to* by the right;
5417 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5418 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5419 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5420 // Ignore lifetime for further calculation.
5421 lhq.removeObjCLifetime();
5422 rhq.removeObjCLifetime();
5425 if (!lhq.compatiblyIncludes(rhq)) {
5426 // Treat address-space mismatches as fatal. TODO: address subspaces
5427 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5428 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5430 // It's okay to add or remove GC or lifetime qualifiers when converting to
5432 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5433 .compatiblyIncludes(
5434 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5435 && (lhptee->isVoidType() || rhptee->isVoidType()))
5438 // Treat lifetime mismatches as fatal.
5439 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5440 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5442 // For GCC compatibility, other qualifier mismatches are treated
5443 // as still compatible in C.
5444 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5447 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5448 // incomplete type and the other is a pointer to a qualified or unqualified
5449 // version of void...
5450 if (lhptee->isVoidType()) {
5451 if (rhptee->isIncompleteOrObjectType())
5454 // As an extension, we allow cast to/from void* to function pointer.
5455 assert(rhptee->isFunctionType());
5456 return Sema::FunctionVoidPointer;
5459 if (rhptee->isVoidType()) {
5460 if (lhptee->isIncompleteOrObjectType())
5463 // As an extension, we allow cast to/from void* to function pointer.
5464 assert(lhptee->isFunctionType());
5465 return Sema::FunctionVoidPointer;
5468 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5469 // unqualified versions of compatible types, ...
5470 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5471 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5472 // Check if the pointee types are compatible ignoring the sign.
5473 // We explicitly check for char so that we catch "char" vs
5474 // "unsigned char" on systems where "char" is unsigned.
5475 if (lhptee->isCharType())
5476 ltrans = S.Context.UnsignedCharTy;
5477 else if (lhptee->hasSignedIntegerRepresentation())
5478 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5480 if (rhptee->isCharType())
5481 rtrans = S.Context.UnsignedCharTy;
5482 else if (rhptee->hasSignedIntegerRepresentation())
5483 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5485 if (ltrans == rtrans) {
5486 // Types are compatible ignoring the sign. Qualifier incompatibility
5487 // takes priority over sign incompatibility because the sign
5488 // warning can be disabled.
5489 if (ConvTy != Sema::Compatible)
5492 return Sema::IncompatiblePointerSign;
5495 // If we are a multi-level pointer, it's possible that our issue is simply
5496 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5497 // the eventual target type is the same and the pointers have the same
5498 // level of indirection, this must be the issue.
5499 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5501 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5502 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5503 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5505 if (lhptee == rhptee)
5506 return Sema::IncompatibleNestedPointerQualifiers;
5509 // General pointer incompatibility takes priority over qualifiers.
5510 return Sema::IncompatiblePointer;
5512 if (!S.getLangOpts().CPlusPlus &&
5513 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5514 return Sema::IncompatiblePointer;
5518 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5519 /// block pointer types are compatible or whether a block and normal pointer
5520 /// are compatible. It is more restrict than comparing two function pointer
5522 static Sema::AssignConvertType
5523 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5525 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5526 assert(RHSType.isCanonical() && "RHS not canonicalized!");
5528 QualType lhptee, rhptee;
5530 // get the "pointed to" type (ignoring qualifiers at the top level)
5531 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5532 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5534 // In C++, the types have to match exactly.
5535 if (S.getLangOpts().CPlusPlus)
5536 return Sema::IncompatibleBlockPointer;
5538 Sema::AssignConvertType ConvTy = Sema::Compatible;
5540 // For blocks we enforce that qualifiers are identical.
5541 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5542 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5544 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5545 return Sema::IncompatibleBlockPointer;
5550 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5551 /// for assignment compatibility.
5552 static Sema::AssignConvertType
5553 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5555 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5556 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5558 if (LHSType->isObjCBuiltinType()) {
5559 // Class is not compatible with ObjC object pointers.
5560 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5561 !RHSType->isObjCQualifiedClassType())
5562 return Sema::IncompatiblePointer;
5563 return Sema::Compatible;
5565 if (RHSType->isObjCBuiltinType()) {
5566 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5567 !LHSType->isObjCQualifiedClassType())
5568 return Sema::IncompatiblePointer;
5569 return Sema::Compatible;
5571 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5572 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5574 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5575 // make an exception for id<P>
5576 !LHSType->isObjCQualifiedIdType())
5577 return Sema::CompatiblePointerDiscardsQualifiers;
5579 if (S.Context.typesAreCompatible(LHSType, RHSType))
5580 return Sema::Compatible;
5581 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5582 return Sema::IncompatibleObjCQualifiedId;
5583 return Sema::IncompatiblePointer;
5586 Sema::AssignConvertType
5587 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5588 QualType LHSType, QualType RHSType) {
5589 // Fake up an opaque expression. We don't actually care about what
5590 // cast operations are required, so if CheckAssignmentConstraints
5591 // adds casts to this they'll be wasted, but fortunately that doesn't
5592 // usually happen on valid code.
5593 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5594 ExprResult RHSPtr = &RHSExpr;
5595 CastKind K = CK_Invalid;
5597 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5600 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5601 /// has code to accommodate several GCC extensions when type checking
5602 /// pointers. Here are some objectionable examples that GCC considers warnings:
5606 /// struct foo *pfoo;
5608 /// pint = pshort; // warning: assignment from incompatible pointer type
5609 /// a = pint; // warning: assignment makes integer from pointer without a cast
5610 /// pint = a; // warning: assignment makes pointer from integer without a cast
5611 /// pint = pfoo; // warning: assignment from incompatible pointer type
5613 /// As a result, the code for dealing with pointers is more complex than the
5614 /// C99 spec dictates.
5616 /// Sets 'Kind' for any result kind except Incompatible.
5617 Sema::AssignConvertType
5618 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5620 QualType RHSType = RHS.get()->getType();
5621 QualType OrigLHSType = LHSType;
5623 // Get canonical types. We're not formatting these types, just comparing
5625 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5626 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5629 // Common case: no conversion required.
5630 if (LHSType == RHSType) {
5635 // If we have an atomic type, try a non-atomic assignment, then just add an
5636 // atomic qualification step.
5637 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5638 Sema::AssignConvertType result =
5639 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5640 if (result != Compatible)
5642 if (Kind != CK_NoOp)
5643 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5644 Kind = CK_NonAtomicToAtomic;
5648 // If the left-hand side is a reference type, then we are in a
5649 // (rare!) case where we've allowed the use of references in C,
5650 // e.g., as a parameter type in a built-in function. In this case,
5651 // just make sure that the type referenced is compatible with the
5652 // right-hand side type. The caller is responsible for adjusting
5653 // LHSType so that the resulting expression does not have reference
5655 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5656 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5657 Kind = CK_LValueBitCast;
5660 return Incompatible;
5663 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5664 // to the same ExtVector type.
5665 if (LHSType->isExtVectorType()) {
5666 if (RHSType->isExtVectorType())
5667 return Incompatible;
5668 if (RHSType->isArithmeticType()) {
5669 // CK_VectorSplat does T -> vector T, so first cast to the
5671 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5672 if (elType != RHSType) {
5673 Kind = PrepareScalarCast(RHS, elType);
5674 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5676 Kind = CK_VectorSplat;
5681 // Conversions to or from vector type.
5682 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5683 if (LHSType->isVectorType() && RHSType->isVectorType()) {
5684 // Allow assignments of an AltiVec vector type to an equivalent GCC
5685 // vector type and vice versa
5686 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5691 // If we are allowing lax vector conversions, and LHS and RHS are both
5692 // vectors, the total size only needs to be the same. This is a bitcast;
5693 // no bits are changed but the result type is different.
5694 if (getLangOpts().LaxVectorConversions &&
5695 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5697 return IncompatibleVectors;
5700 return Incompatible;
5703 // Arithmetic conversions.
5704 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5705 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5706 Kind = PrepareScalarCast(RHS, LHSType);
5710 // Conversions to normal pointers.
5711 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5713 if (isa<PointerType>(RHSType)) {
5715 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5719 if (RHSType->isIntegerType()) {
5720 Kind = CK_IntegralToPointer; // FIXME: null?
5721 return IntToPointer;
5724 // C pointers are not compatible with ObjC object pointers,
5725 // with two exceptions:
5726 if (isa<ObjCObjectPointerType>(RHSType)) {
5727 // - conversions to void*
5728 if (LHSPointer->getPointeeType()->isVoidType()) {
5733 // - conversions from 'Class' to the redefinition type
5734 if (RHSType->isObjCClassType() &&
5735 Context.hasSameType(LHSType,
5736 Context.getObjCClassRedefinitionType())) {
5742 return IncompatiblePointer;
5746 if (RHSType->getAs<BlockPointerType>()) {
5747 if (LHSPointer->getPointeeType()->isVoidType()) {
5753 return Incompatible;
5756 // Conversions to block pointers.
5757 if (isa<BlockPointerType>(LHSType)) {
5759 if (RHSType->isBlockPointerType()) {
5761 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5764 // int or null -> T^
5765 if (RHSType->isIntegerType()) {
5766 Kind = CK_IntegralToPointer; // FIXME: null
5767 return IntToBlockPointer;
5771 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5772 Kind = CK_AnyPointerToBlockPointerCast;
5777 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5778 if (RHSPT->getPointeeType()->isVoidType()) {
5779 Kind = CK_AnyPointerToBlockPointerCast;
5783 return Incompatible;
5786 // Conversions to Objective-C pointers.
5787 if (isa<ObjCObjectPointerType>(LHSType)) {
5789 if (RHSType->isObjCObjectPointerType()) {
5791 Sema::AssignConvertType result =
5792 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5793 if (getLangOpts().ObjCAutoRefCount &&
5794 result == Compatible &&
5795 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5796 result = IncompatibleObjCWeakRef;
5800 // int or null -> A*
5801 if (RHSType->isIntegerType()) {
5802 Kind = CK_IntegralToPointer; // FIXME: null
5803 return IntToPointer;
5806 // In general, C pointers are not compatible with ObjC object pointers,
5807 // with two exceptions:
5808 if (isa<PointerType>(RHSType)) {
5809 Kind = CK_CPointerToObjCPointerCast;
5811 // - conversions from 'void*'
5812 if (RHSType->isVoidPointerType()) {
5816 // - conversions to 'Class' from its redefinition type
5817 if (LHSType->isObjCClassType() &&
5818 Context.hasSameType(RHSType,
5819 Context.getObjCClassRedefinitionType())) {
5823 return IncompatiblePointer;
5827 if (RHSType->isBlockPointerType()) {
5828 maybeExtendBlockObject(*this, RHS);
5829 Kind = CK_BlockPointerToObjCPointerCast;
5833 return Incompatible;
5836 // Conversions from pointers that are not covered by the above.
5837 if (isa<PointerType>(RHSType)) {
5839 if (LHSType == Context.BoolTy) {
5840 Kind = CK_PointerToBoolean;
5845 if (LHSType->isIntegerType()) {
5846 Kind = CK_PointerToIntegral;
5847 return PointerToInt;
5850 return Incompatible;
5853 // Conversions from Objective-C pointers that are not covered by the above.
5854 if (isa<ObjCObjectPointerType>(RHSType)) {
5856 if (LHSType == Context.BoolTy) {
5857 Kind = CK_PointerToBoolean;
5862 if (LHSType->isIntegerType()) {
5863 Kind = CK_PointerToIntegral;
5864 return PointerToInt;
5867 return Incompatible;
5870 // struct A -> struct B
5871 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5872 if (Context.typesAreCompatible(LHSType, RHSType)) {
5878 return Incompatible;
5881 /// \brief Constructs a transparent union from an expression that is
5882 /// used to initialize the transparent union.
5883 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5884 ExprResult &EResult, QualType UnionType,
5886 // Build an initializer list that designates the appropriate member
5887 // of the transparent union.
5888 Expr *E = EResult.take();
5889 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5890 E, SourceLocation());
5891 Initializer->setType(UnionType);
5892 Initializer->setInitializedFieldInUnion(Field);
5894 // Build a compound literal constructing a value of the transparent
5895 // union type from this initializer list.
5896 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5898 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5899 VK_RValue, Initializer, false));
5902 Sema::AssignConvertType
5903 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5905 QualType RHSType = RHS.get()->getType();
5907 // If the ArgType is a Union type, we want to handle a potential
5908 // transparent_union GCC extension.
5909 const RecordType *UT = ArgType->getAsUnionType();
5910 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5911 return Incompatible;
5913 // The field to initialize within the transparent union.
5914 RecordDecl *UD = UT->getDecl();
5915 FieldDecl *InitField = 0;
5916 // It's compatible if the expression matches any of the fields.
5917 for (RecordDecl::field_iterator it = UD->field_begin(),
5918 itend = UD->field_end();
5919 it != itend; ++it) {
5920 if (it->getType()->isPointerType()) {
5921 // If the transparent union contains a pointer type, we allow:
5923 // 2) null pointer constant
5924 if (RHSType->isPointerType())
5925 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5926 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5931 if (RHS.get()->isNullPointerConstant(Context,
5932 Expr::NPC_ValueDependentIsNull)) {
5933 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5940 CastKind Kind = CK_Invalid;
5941 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5943 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5950 return Incompatible;
5952 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5956 Sema::AssignConvertType
5957 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5959 if (getLangOpts().CPlusPlus) {
5960 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5961 // C++ 5.17p3: If the left operand is not of class type, the
5962 // expression is implicitly converted (C++ 4) to the
5963 // cv-unqualified type of the left operand.
5966 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5969 ImplicitConversionSequence ICS =
5970 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5971 /*SuppressUserConversions=*/false,
5972 /*AllowExplicit=*/false,
5973 /*InOverloadResolution=*/false,
5975 /*AllowObjCWritebackConversion=*/false);
5976 if (ICS.isFailure())
5977 return Incompatible;
5978 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5981 if (Res.isInvalid())
5982 return Incompatible;
5983 Sema::AssignConvertType result = Compatible;
5984 if (getLangOpts().ObjCAutoRefCount &&
5985 !CheckObjCARCUnavailableWeakConversion(LHSType,
5986 RHS.get()->getType()))
5987 result = IncompatibleObjCWeakRef;
5992 // FIXME: Currently, we fall through and treat C++ classes like C
5994 // FIXME: We also fall through for atomics; not sure what should
5995 // happen there, though.
5998 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5999 // a null pointer constant.
6000 if ((LHSType->isPointerType() ||
6001 LHSType->isObjCObjectPointerType() ||
6002 LHSType->isBlockPointerType())
6003 && RHS.get()->isNullPointerConstant(Context,
6004 Expr::NPC_ValueDependentIsNull)) {
6005 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6009 // This check seems unnatural, however it is necessary to ensure the proper
6010 // conversion of functions/arrays. If the conversion were done for all
6011 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6012 // expressions that suppress this implicit conversion (&, sizeof).
6014 // Suppress this for references: C++ 8.5.3p5.
6015 if (!LHSType->isReferenceType()) {
6016 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6017 if (RHS.isInvalid())
6018 return Incompatible;
6021 CastKind Kind = CK_Invalid;
6022 Sema::AssignConvertType result =
6023 CheckAssignmentConstraints(LHSType, RHS, Kind);
6025 // C99 6.5.16.1p2: The value of the right operand is converted to the
6026 // type of the assignment expression.
6027 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6028 // so that we can use references in built-in functions even in C.
6029 // The getNonReferenceType() call makes sure that the resulting expression
6030 // does not have reference type.
6031 if (result != Incompatible && RHS.get()->getType() != LHSType)
6032 RHS = ImpCastExprToType(RHS.take(),
6033 LHSType.getNonLValueExprType(Context), Kind);
6037 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6039 Diag(Loc, diag::err_typecheck_invalid_operands)
6040 << LHS.get()->getType() << RHS.get()->getType()
6041 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6045 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6046 SourceLocation Loc, bool IsCompAssign) {
6047 if (!IsCompAssign) {
6048 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6049 if (LHS.isInvalid())
6052 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6053 if (RHS.isInvalid())
6056 // For conversion purposes, we ignore any qualifiers.
6057 // For example, "const float" and "float" are equivalent.
6059 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6061 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6063 // If the vector types are identical, return.
6064 if (LHSType == RHSType)
6067 // Handle the case of equivalent AltiVec and GCC vector types
6068 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6069 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6070 if (LHSType->isExtVectorType()) {
6071 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6076 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6080 if (getLangOpts().LaxVectorConversions &&
6081 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6082 // If we are allowing lax vector conversions, and LHS and RHS are both
6083 // vectors, the total size only needs to be the same. This is a
6084 // bitcast; no bits are changed but the result type is different.
6085 // FIXME: Should we really be allowing this?
6086 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6090 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6091 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6092 bool swapped = false;
6093 if (RHSType->isExtVectorType() && !IsCompAssign) {
6095 std::swap(RHS, LHS);
6096 std::swap(RHSType, LHSType);
6099 // Handle the case of an ext vector and scalar.
6100 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6101 QualType EltTy = LV->getElementType();
6102 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6103 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6105 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6107 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6108 if (swapped) std::swap(RHS, LHS);
6112 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6113 RHSType->isRealFloatingType()) {
6114 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6116 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6118 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6119 if (swapped) std::swap(RHS, LHS);
6125 // Vectors of different size or scalar and non-ext-vector are errors.
6126 if (swapped) std::swap(RHS, LHS);
6127 Diag(Loc, diag::err_typecheck_vector_not_convertable)
6128 << LHS.get()->getType() << RHS.get()->getType()
6129 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6133 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6134 // expression. These are mainly cases where the null pointer is used as an
6135 // integer instead of a pointer.
6136 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6137 SourceLocation Loc, bool IsCompare) {
6138 // The canonical way to check for a GNU null is with isNullPointerConstant,
6139 // but we use a bit of a hack here for speed; this is a relatively
6140 // hot path, and isNullPointerConstant is slow.
6141 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6142 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6144 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6146 // Avoid analyzing cases where the result will either be invalid (and
6147 // diagnosed as such) or entirely valid and not something to warn about.
6148 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6149 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6152 // Comparison operations would not make sense with a null pointer no matter
6153 // what the other expression is.
6155 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6156 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6157 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6161 // The rest of the operations only make sense with a null pointer
6162 // if the other expression is a pointer.
6163 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6164 NonNullType->canDecayToPointerType())
6167 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6168 << LHSNull /* LHS is NULL */ << NonNullType
6169 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6172 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6174 bool IsCompAssign, bool IsDiv) {
6175 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6177 if (LHS.get()->getType()->isVectorType() ||
6178 RHS.get()->getType()->isVectorType())
6179 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6181 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6182 if (LHS.isInvalid() || RHS.isInvalid())
6186 if (compType.isNull() || !compType->isArithmeticType())
6187 return InvalidOperands(Loc, LHS, RHS);
6189 // Check for division by zero.
6191 RHS.get()->isNullPointerConstant(Context,
6192 Expr::NPC_ValueDependentIsNotNull))
6193 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6194 << RHS.get()->getSourceRange());
6199 QualType Sema::CheckRemainderOperands(
6200 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6201 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6203 if (LHS.get()->getType()->isVectorType() ||
6204 RHS.get()->getType()->isVectorType()) {
6205 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6206 RHS.get()->getType()->hasIntegerRepresentation())
6207 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6208 return InvalidOperands(Loc, LHS, RHS);
6211 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6212 if (LHS.isInvalid() || RHS.isInvalid())
6215 if (compType.isNull() || !compType->isIntegerType())
6216 return InvalidOperands(Loc, LHS, RHS);
6218 // Check for remainder by zero.
6219 if (RHS.get()->isNullPointerConstant(Context,
6220 Expr::NPC_ValueDependentIsNotNull))
6221 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6222 << RHS.get()->getSourceRange());
6227 /// \brief Diagnose invalid arithmetic on two void pointers.
6228 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6229 Expr *LHSExpr, Expr *RHSExpr) {
6230 S.Diag(Loc, S.getLangOpts().CPlusPlus
6231 ? diag::err_typecheck_pointer_arith_void_type
6232 : diag::ext_gnu_void_ptr)
6233 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6234 << RHSExpr->getSourceRange();
6237 /// \brief Diagnose invalid arithmetic on a void pointer.
6238 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6240 S.Diag(Loc, S.getLangOpts().CPlusPlus
6241 ? diag::err_typecheck_pointer_arith_void_type
6242 : diag::ext_gnu_void_ptr)
6243 << 0 /* one pointer */ << Pointer->getSourceRange();
6246 /// \brief Diagnose invalid arithmetic on two function pointers.
6247 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6248 Expr *LHS, Expr *RHS) {
6249 assert(LHS->getType()->isAnyPointerType());
6250 assert(RHS->getType()->isAnyPointerType());
6251 S.Diag(Loc, S.getLangOpts().CPlusPlus
6252 ? diag::err_typecheck_pointer_arith_function_type
6253 : diag::ext_gnu_ptr_func_arith)
6254 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6255 // We only show the second type if it differs from the first.
6256 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6258 << RHS->getType()->getPointeeType()
6259 << LHS->getSourceRange() << RHS->getSourceRange();
6262 /// \brief Diagnose invalid arithmetic on a function pointer.
6263 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6265 assert(Pointer->getType()->isAnyPointerType());
6266 S.Diag(Loc, S.getLangOpts().CPlusPlus
6267 ? diag::err_typecheck_pointer_arith_function_type
6268 : diag::ext_gnu_ptr_func_arith)
6269 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6270 << 0 /* one pointer, so only one type */
6271 << Pointer->getSourceRange();
6274 /// \brief Emit error if Operand is incomplete pointer type
6276 /// \returns True if pointer has incomplete type
6277 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6279 assert(Operand->getType()->isAnyPointerType() &&
6280 !Operand->getType()->isDependentType());
6281 QualType PointeeTy = Operand->getType()->getPointeeType();
6282 return S.RequireCompleteType(Loc, PointeeTy,
6283 diag::err_typecheck_arithmetic_incomplete_type,
6284 PointeeTy, Operand->getSourceRange());
6287 /// \brief Check the validity of an arithmetic pointer operand.
6289 /// If the operand has pointer type, this code will check for pointer types
6290 /// which are invalid in arithmetic operations. These will be diagnosed
6291 /// appropriately, including whether or not the use is supported as an
6294 /// \returns True when the operand is valid to use (even if as an extension).
6295 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6297 if (!Operand->getType()->isAnyPointerType()) return true;
6299 QualType PointeeTy = Operand->getType()->getPointeeType();
6300 if (PointeeTy->isVoidType()) {
6301 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6302 return !S.getLangOpts().CPlusPlus;
6304 if (PointeeTy->isFunctionType()) {
6305 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6306 return !S.getLangOpts().CPlusPlus;
6309 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6314 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6317 /// This routine will diagnose any invalid arithmetic on pointer operands much
6318 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6319 /// for emitting a single diagnostic even for operations where both LHS and RHS
6320 /// are (potentially problematic) pointers.
6322 /// \returns True when the operand is valid to use (even if as an extension).
6323 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6324 Expr *LHSExpr, Expr *RHSExpr) {
6325 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6326 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6327 if (!isLHSPointer && !isRHSPointer) return true;
6329 QualType LHSPointeeTy, RHSPointeeTy;
6330 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6331 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6333 // Check for arithmetic on pointers to incomplete types.
6334 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6335 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6336 if (isLHSVoidPtr || isRHSVoidPtr) {
6337 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6338 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6339 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6341 return !S.getLangOpts().CPlusPlus;
6344 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6345 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6346 if (isLHSFuncPtr || isRHSFuncPtr) {
6347 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6348 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6350 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6352 return !S.getLangOpts().CPlusPlus;
6355 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6357 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6363 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6365 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6366 Expr *LHSExpr, Expr *RHSExpr) {
6367 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6368 Expr* IndexExpr = RHSExpr;
6370 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6371 IndexExpr = LHSExpr;
6374 bool IsStringPlusInt = StrExpr &&
6375 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6376 if (!IsStringPlusInt)
6380 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6381 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6382 if (index.isNonNegative() &&
6383 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6384 index.isUnsigned()))
6388 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6389 Self.Diag(OpLoc, diag::warn_string_plus_int)
6390 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6392 // Only print a fixit for "str" + int, not for int + "str".
6393 if (IndexExpr == RHSExpr) {
6394 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6395 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6396 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6397 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6398 << FixItHint::CreateInsertion(EndLoc, "]");
6400 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6403 /// \brief Emit error when two pointers are incompatible.
6404 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6405 Expr *LHSExpr, Expr *RHSExpr) {
6406 assert(LHSExpr->getType()->isAnyPointerType());
6407 assert(RHSExpr->getType()->isAnyPointerType());
6408 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6409 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6410 << RHSExpr->getSourceRange();
6413 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6414 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6415 QualType* CompLHSTy) {
6416 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6418 if (LHS.get()->getType()->isVectorType() ||
6419 RHS.get()->getType()->isVectorType()) {
6420 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6421 if (CompLHSTy) *CompLHSTy = compType;
6425 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6426 if (LHS.isInvalid() || RHS.isInvalid())
6429 // Diagnose "string literal" '+' int.
6431 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6433 // handle the common case first (both operands are arithmetic).
6434 if (!compType.isNull() && compType->isArithmeticType()) {
6435 if (CompLHSTy) *CompLHSTy = compType;
6439 // Type-checking. Ultimately the pointer's going to be in PExp;
6440 // note that we bias towards the LHS being the pointer.
6441 Expr *PExp = LHS.get(), *IExp = RHS.get();
6444 if (PExp->getType()->isPointerType()) {
6445 isObjCPointer = false;
6446 } else if (PExp->getType()->isObjCObjectPointerType()) {
6447 isObjCPointer = true;
6449 std::swap(PExp, IExp);
6450 if (PExp->getType()->isPointerType()) {
6451 isObjCPointer = false;
6452 } else if (PExp->getType()->isObjCObjectPointerType()) {
6453 isObjCPointer = true;
6455 return InvalidOperands(Loc, LHS, RHS);
6458 assert(PExp->getType()->isAnyPointerType());
6460 if (!IExp->getType()->isIntegerType())
6461 return InvalidOperands(Loc, LHS, RHS);
6463 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6466 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6469 // Check array bounds for pointer arithemtic
6470 CheckArrayAccess(PExp, IExp);
6473 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6474 if (LHSTy.isNull()) {
6475 LHSTy = LHS.get()->getType();
6476 if (LHSTy->isPromotableIntegerType())
6477 LHSTy = Context.getPromotedIntegerType(LHSTy);
6482 return PExp->getType();
6486 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6488 QualType* CompLHSTy) {
6489 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6491 if (LHS.get()->getType()->isVectorType() ||
6492 RHS.get()->getType()->isVectorType()) {
6493 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6494 if (CompLHSTy) *CompLHSTy = compType;
6498 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6499 if (LHS.isInvalid() || RHS.isInvalid())
6502 // Enforce type constraints: C99 6.5.6p3.
6504 // Handle the common case first (both operands are arithmetic).
6505 if (!compType.isNull() && compType->isArithmeticType()) {
6506 if (CompLHSTy) *CompLHSTy = compType;
6510 // Either ptr - int or ptr - ptr.
6511 if (LHS.get()->getType()->isAnyPointerType()) {
6512 QualType lpointee = LHS.get()->getType()->getPointeeType();
6514 // Diagnose bad cases where we step over interface counts.
6515 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6516 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6519 // The result type of a pointer-int computation is the pointer type.
6520 if (RHS.get()->getType()->isIntegerType()) {
6521 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6524 // Check array bounds for pointer arithemtic
6525 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6526 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6528 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6529 return LHS.get()->getType();
6532 // Handle pointer-pointer subtractions.
6533 if (const PointerType *RHSPTy
6534 = RHS.get()->getType()->getAs<PointerType>()) {
6535 QualType rpointee = RHSPTy->getPointeeType();
6537 if (getLangOpts().CPlusPlus) {
6538 // Pointee types must be the same: C++ [expr.add]
6539 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6540 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6543 // Pointee types must be compatible C99 6.5.6p3
6544 if (!Context.typesAreCompatible(
6545 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6546 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6547 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6552 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6553 LHS.get(), RHS.get()))
6556 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6557 return Context.getPointerDiffType();
6561 return InvalidOperands(Loc, LHS, RHS);
6564 static bool isScopedEnumerationType(QualType T) {
6565 if (const EnumType *ET = dyn_cast<EnumType>(T))
6566 return ET->getDecl()->isScoped();
6570 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6571 SourceLocation Loc, unsigned Opc,
6574 // Check right/shifter operand
6575 if (RHS.get()->isValueDependent() ||
6576 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6579 if (Right.isNegative()) {
6580 S.DiagRuntimeBehavior(Loc, RHS.get(),
6581 S.PDiag(diag::warn_shift_negative)
6582 << RHS.get()->getSourceRange());
6585 llvm::APInt LeftBits(Right.getBitWidth(),
6586 S.Context.getTypeSize(LHS.get()->getType()));
6587 if (Right.uge(LeftBits)) {
6588 S.DiagRuntimeBehavior(Loc, RHS.get(),
6589 S.PDiag(diag::warn_shift_gt_typewidth)
6590 << RHS.get()->getSourceRange());
6596 // When left shifting an ICE which is signed, we can check for overflow which
6597 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6598 // integers have defined behavior modulo one more than the maximum value
6599 // representable in the result type, so never warn for those.
6601 if (LHS.get()->isValueDependent() ||
6602 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6603 LHSType->hasUnsignedIntegerRepresentation())
6605 llvm::APInt ResultBits =
6606 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6607 if (LeftBits.uge(ResultBits))
6609 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6610 Result = Result.shl(Right);
6612 // Print the bit representation of the signed integer as an unsigned
6613 // hexadecimal number.
6614 SmallString<40> HexResult;
6615 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6617 // If we are only missing a sign bit, this is less likely to result in actual
6618 // bugs -- if the result is cast back to an unsigned type, it will have the
6619 // expected value. Thus we place this behind a different warning that can be
6620 // turned off separately if needed.
6621 if (LeftBits == ResultBits - 1) {
6622 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6623 << HexResult.str() << LHSType
6624 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6628 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6629 << HexResult.str() << Result.getMinSignedBits() << LHSType
6630 << Left.getBitWidth() << LHS.get()->getSourceRange()
6631 << RHS.get()->getSourceRange();
6635 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6636 SourceLocation Loc, unsigned Opc,
6637 bool IsCompAssign) {
6638 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6640 // C99 6.5.7p2: Each of the operands shall have integer type.
6641 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6642 !RHS.get()->getType()->hasIntegerRepresentation())
6643 return InvalidOperands(Loc, LHS, RHS);
6645 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6646 // hasIntegerRepresentation() above instead of this.
6647 if (isScopedEnumerationType(LHS.get()->getType()) ||
6648 isScopedEnumerationType(RHS.get()->getType())) {
6649 return InvalidOperands(Loc, LHS, RHS);
6652 // Vector shifts promote their scalar inputs to vector type.
6653 if (LHS.get()->getType()->isVectorType() ||
6654 RHS.get()->getType()->isVectorType())
6655 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6657 // Shifts don't perform usual arithmetic conversions, they just do integer
6658 // promotions on each operand. C99 6.5.7p3
6660 // For the LHS, do usual unary conversions, but then reset them away
6661 // if this is a compound assignment.
6662 ExprResult OldLHS = LHS;
6663 LHS = UsualUnaryConversions(LHS.take());
6664 if (LHS.isInvalid())
6666 QualType LHSType = LHS.get()->getType();
6667 if (IsCompAssign) LHS = OldLHS;
6669 // The RHS is simpler.
6670 RHS = UsualUnaryConversions(RHS.take());
6671 if (RHS.isInvalid())
6674 // Sanity-check shift operands
6675 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6677 // "The type of the result is that of the promoted left operand."
6681 static bool IsWithinTemplateSpecialization(Decl *D) {
6682 if (DeclContext *DC = D->getDeclContext()) {
6683 if (isa<ClassTemplateSpecializationDecl>(DC))
6685 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6686 return FD->isFunctionTemplateSpecialization();
6691 /// If two different enums are compared, raise a warning.
6692 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6694 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6695 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6697 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6700 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6704 // Ignore anonymous enums.
6705 if (!LHSEnumType->getDecl()->getIdentifier())
6707 if (!RHSEnumType->getDecl()->getIdentifier())
6710 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6713 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6714 << LHSStrippedType << RHSStrippedType
6715 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6718 /// \brief Diagnose bad pointer comparisons.
6719 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6720 ExprResult &LHS, ExprResult &RHS,
6722 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6723 : diag::ext_typecheck_comparison_of_distinct_pointers)
6724 << LHS.get()->getType() << RHS.get()->getType()
6725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6728 /// \brief Returns false if the pointers are converted to a composite type,
6730 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6731 ExprResult &LHS, ExprResult &RHS) {
6732 // C++ [expr.rel]p2:
6733 // [...] Pointer conversions (4.10) and qualification
6734 // conversions (4.4) are performed on pointer operands (or on
6735 // a pointer operand and a null pointer constant) to bring
6736 // them to their composite pointer type. [...]
6738 // C++ [expr.eq]p1 uses the same notion for (in)equality
6739 // comparisons of pointers.
6742 // In addition, pointers to members can be compared, or a pointer to
6743 // member and a null pointer constant. Pointer to member conversions
6744 // (4.11) and qualification conversions (4.4) are performed to bring
6745 // them to a common type. If one operand is a null pointer constant,
6746 // the common type is the type of the other operand. Otherwise, the
6747 // common type is a pointer to member type similar (4.4) to the type
6748 // of one of the operands, with a cv-qualification signature (4.4)
6749 // that is the union of the cv-qualification signatures of the operand
6752 QualType LHSType = LHS.get()->getType();
6753 QualType RHSType = RHS.get()->getType();
6754 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6755 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6757 bool NonStandardCompositeType = false;
6758 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6759 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6761 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6765 if (NonStandardCompositeType)
6766 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6767 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6768 << RHS.get()->getSourceRange();
6770 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6771 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6775 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6779 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6780 : diag::ext_typecheck_comparison_of_fptr_to_void)
6781 << LHS.get()->getType() << RHS.get()->getType()
6782 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6785 static bool isObjCObjectLiteral(ExprResult &E) {
6786 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
6787 case Stmt::ObjCArrayLiteralClass:
6788 case Stmt::ObjCDictionaryLiteralClass:
6789 case Stmt::ObjCStringLiteralClass:
6790 case Stmt::ObjCBoxedExprClass:
6793 // Note that ObjCBoolLiteral is NOT an object literal!
6798 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6799 // Get the LHS object's interface type.
6800 QualType Type = LHS->getType();
6801 QualType InterfaceType;
6802 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6803 InterfaceType = PTy->getPointeeType();
6804 if (const ObjCObjectType *iQFaceTy =
6805 InterfaceType->getAsObjCQualifiedInterfaceType())
6806 InterfaceType = iQFaceTy->getBaseType();
6808 // If this is not actually an Objective-C object, bail out.
6812 // If the RHS isn't an Objective-C object, bail out.
6813 if (!RHS->getType()->isObjCObjectPointerType())
6816 // Try to find the -isEqual: method.
6817 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6818 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6822 if (Type->isObjCIdType()) {
6823 // For 'id', just check the global pool.
6824 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6825 /*receiverId=*/true,
6829 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6830 cast<ObjCObjectPointerType>(Type),
6838 QualType T = Method->param_begin()[0]->getType();
6839 if (!T->isObjCObjectPointerType())
6842 QualType R = Method->getResultType();
6843 if (!R->isScalarType())
6849 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6850 ExprResult &LHS, ExprResult &RHS,
6851 BinaryOperator::Opcode Opc){
6854 if (isObjCObjectLiteral(LHS)) {
6855 Literal = LHS.get();
6858 Literal = RHS.get();
6862 // Don't warn on comparisons against nil.
6863 Other = Other->IgnoreParenCasts();
6864 if (Other->isNullPointerConstant(S.getASTContext(),
6865 Expr::NPC_ValueDependentIsNotNull))
6868 // This should be kept in sync with warn_objc_literal_comparison.
6869 // LK_String should always be last, since it has its own warning flag.
6878 Literal = Literal->IgnoreParenImpCasts();
6879 switch (Literal->getStmtClass()) {
6880 case Stmt::ObjCStringLiteralClass:
6882 LiteralKind = LK_String;
6884 case Stmt::ObjCArrayLiteralClass:
6886 LiteralKind = LK_Array;
6888 case Stmt::ObjCDictionaryLiteralClass:
6889 // "dictionary literal"
6890 LiteralKind = LK_Dictionary;
6892 case Stmt::ObjCBoxedExprClass: {
6893 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6894 switch (Inner->getStmtClass()) {
6895 case Stmt::IntegerLiteralClass:
6896 case Stmt::FloatingLiteralClass:
6897 case Stmt::CharacterLiteralClass:
6898 case Stmt::ObjCBoolLiteralExprClass:
6899 case Stmt::CXXBoolLiteralExprClass:
6900 // "numeric literal"
6901 LiteralKind = LK_Numeric;
6903 case Stmt::ImplicitCastExprClass: {
6904 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6905 // Boolean literals can be represented by implicit casts.
6906 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6907 LiteralKind = LK_Numeric;
6913 // "boxed expression"
6914 LiteralKind = LK_Boxed;
6920 llvm_unreachable("Unknown Objective-C object literal kind");
6923 if (LiteralKind == LK_String)
6924 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6925 << Literal->getSourceRange();
6927 S.Diag(Loc, diag::warn_objc_literal_comparison)
6928 << LiteralKind << Literal->getSourceRange();
6930 if (BinaryOperator::isEqualityOp(Opc) &&
6931 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6932 SourceLocation Start = LHS.get()->getLocStart();
6933 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6934 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
6936 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6937 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6938 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6939 << FixItHint::CreateInsertion(End, "]");
6943 // C99 6.5.8, C++ [expr.rel]
6944 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6945 SourceLocation Loc, unsigned OpaqueOpc,
6946 bool IsRelational) {
6947 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6949 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6951 // Handle vector comparisons separately.
6952 if (LHS.get()->getType()->isVectorType() ||
6953 RHS.get()->getType()->isVectorType())
6954 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6956 QualType LHSType = LHS.get()->getType();
6957 QualType RHSType = RHS.get()->getType();
6959 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6960 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6962 checkEnumComparison(*this, Loc, LHS, RHS);
6964 if (!LHSType->hasFloatingRepresentation() &&
6965 !(LHSType->isBlockPointerType() && IsRelational) &&
6966 !LHS.get()->getLocStart().isMacroID() &&
6967 !RHS.get()->getLocStart().isMacroID()) {
6968 // For non-floating point types, check for self-comparisons of the form
6969 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6970 // often indicate logic errors in the program.
6972 // NOTE: Don't warn about comparison expressions resulting from macro
6973 // expansion. Also don't warn about comparisons which are only self
6974 // comparisons within a template specialization. The warnings should catch
6975 // obvious cases in the definition of the template anyways. The idea is to
6976 // warn when the typed comparison operator will always evaluate to the same
6978 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6979 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6980 if (DRL->getDecl() == DRR->getDecl() &&
6981 !IsWithinTemplateSpecialization(DRL->getDecl())) {
6982 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6987 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6988 !DRL->getDecl()->getType()->isReferenceType() &&
6989 !DRR->getDecl()->getType()->isReferenceType()) {
6990 // what is it always going to eval to?
6991 char always_evals_to;
6993 case BO_EQ: // e.g. array1 == array2
6994 always_evals_to = 0; // false
6996 case BO_NE: // e.g. array1 != array2
6997 always_evals_to = 1; // true
7000 // best we can say is 'a constant'
7001 always_evals_to = 2; // e.g. array1 <= array2
7004 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7006 << always_evals_to);
7011 if (isa<CastExpr>(LHSStripped))
7012 LHSStripped = LHSStripped->IgnoreParenCasts();
7013 if (isa<CastExpr>(RHSStripped))
7014 RHSStripped = RHSStripped->IgnoreParenCasts();
7016 // Warn about comparisons against a string constant (unless the other
7017 // operand is null), the user probably wants strcmp.
7018 Expr *literalString = 0;
7019 Expr *literalStringStripped = 0;
7020 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7021 !RHSStripped->isNullPointerConstant(Context,
7022 Expr::NPC_ValueDependentIsNull)) {
7023 literalString = LHS.get();
7024 literalStringStripped = LHSStripped;
7025 } else if ((isa<StringLiteral>(RHSStripped) ||
7026 isa<ObjCEncodeExpr>(RHSStripped)) &&
7027 !LHSStripped->isNullPointerConstant(Context,
7028 Expr::NPC_ValueDependentIsNull)) {
7029 literalString = RHS.get();
7030 literalStringStripped = RHSStripped;
7033 if (literalString) {
7034 std::string resultComparison;
7036 case BO_LT: resultComparison = ") < 0"; break;
7037 case BO_GT: resultComparison = ") > 0"; break;
7038 case BO_LE: resultComparison = ") <= 0"; break;
7039 case BO_GE: resultComparison = ") >= 0"; break;
7040 case BO_EQ: resultComparison = ") == 0"; break;
7041 case BO_NE: resultComparison = ") != 0"; break;
7042 default: llvm_unreachable("Invalid comparison operator");
7045 DiagRuntimeBehavior(Loc, 0,
7046 PDiag(diag::warn_stringcompare)
7047 << isa<ObjCEncodeExpr>(literalStringStripped)
7048 << literalString->getSourceRange());
7052 // C99 6.5.8p3 / C99 6.5.9p4
7053 if (LHS.get()->getType()->isArithmeticType() &&
7054 RHS.get()->getType()->isArithmeticType()) {
7055 UsualArithmeticConversions(LHS, RHS);
7056 if (LHS.isInvalid() || RHS.isInvalid())
7060 LHS = UsualUnaryConversions(LHS.take());
7061 if (LHS.isInvalid())
7064 RHS = UsualUnaryConversions(RHS.take());
7065 if (RHS.isInvalid())
7069 LHSType = LHS.get()->getType();
7070 RHSType = RHS.get()->getType();
7072 // The result of comparisons is 'bool' in C++, 'int' in C.
7073 QualType ResultTy = Context.getLogicalOperationType();
7076 if (LHSType->isRealType() && RHSType->isRealType())
7079 // Check for comparisons of floating point operands using != and ==.
7080 if (LHSType->hasFloatingRepresentation())
7081 CheckFloatComparison(Loc, LHS.get(), RHS.get());
7083 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7087 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7088 Expr::NPC_ValueDependentIsNull);
7089 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7090 Expr::NPC_ValueDependentIsNull);
7092 // All of the following pointer-related warnings are GCC extensions, except
7093 // when handling null pointer constants.
7094 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7095 QualType LCanPointeeTy =
7096 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7097 QualType RCanPointeeTy =
7098 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7100 if (getLangOpts().CPlusPlus) {
7101 if (LCanPointeeTy == RCanPointeeTy)
7103 if (!IsRelational &&
7104 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7105 // Valid unless comparison between non-null pointer and function pointer
7106 // This is a gcc extension compatibility comparison.
7107 // In a SFINAE context, we treat this as a hard error to maintain
7108 // conformance with the C++ standard.
7109 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7110 && !LHSIsNull && !RHSIsNull) {
7111 diagnoseFunctionPointerToVoidComparison(
7112 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
7114 if (isSFINAEContext())
7117 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7122 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7127 // C99 6.5.9p2 and C99 6.5.8p2
7128 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7129 RCanPointeeTy.getUnqualifiedType())) {
7130 // Valid unless a relational comparison of function pointers
7131 if (IsRelational && LCanPointeeTy->isFunctionType()) {
7132 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7133 << LHSType << RHSType << LHS.get()->getSourceRange()
7134 << RHS.get()->getSourceRange();
7136 } else if (!IsRelational &&
7137 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7138 // Valid unless comparison between non-null pointer and function pointer
7139 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7140 && !LHSIsNull && !RHSIsNull)
7141 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7145 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7147 if (LCanPointeeTy != RCanPointeeTy) {
7148 if (LHSIsNull && !RHSIsNull)
7149 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7151 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7156 if (getLangOpts().CPlusPlus) {
7157 // Comparison of nullptr_t with itself.
7158 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7161 // Comparison of pointers with null pointer constants and equality
7162 // comparisons of member pointers to null pointer constants.
7164 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7166 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7167 RHS = ImpCastExprToType(RHS.take(), LHSType,
7168 LHSType->isMemberPointerType()
7169 ? CK_NullToMemberPointer
7170 : CK_NullToPointer);
7174 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7176 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7177 LHS = ImpCastExprToType(LHS.take(), RHSType,
7178 RHSType->isMemberPointerType()
7179 ? CK_NullToMemberPointer
7180 : CK_NullToPointer);
7184 // Comparison of member pointers.
7185 if (!IsRelational &&
7186 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7187 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7193 // Handle scoped enumeration types specifically, since they don't promote
7195 if (LHS.get()->getType()->isEnumeralType() &&
7196 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7197 RHS.get()->getType()))
7201 // Handle block pointer types.
7202 if (!IsRelational && LHSType->isBlockPointerType() &&
7203 RHSType->isBlockPointerType()) {
7204 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7205 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7207 if (!LHSIsNull && !RHSIsNull &&
7208 !Context.typesAreCompatible(lpointee, rpointee)) {
7209 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7210 << LHSType << RHSType << LHS.get()->getSourceRange()
7211 << RHS.get()->getSourceRange();
7213 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7217 // Allow block pointers to be compared with null pointer constants.
7219 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7220 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7221 if (!LHSIsNull && !RHSIsNull) {
7222 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7223 ->getPointeeType()->isVoidType())
7224 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7225 ->getPointeeType()->isVoidType())))
7226 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7227 << LHSType << RHSType << LHS.get()->getSourceRange()
7228 << RHS.get()->getSourceRange();
7230 if (LHSIsNull && !RHSIsNull)
7231 LHS = ImpCastExprToType(LHS.take(), RHSType,
7232 RHSType->isPointerType() ? CK_BitCast
7233 : CK_AnyPointerToBlockPointerCast);
7235 RHS = ImpCastExprToType(RHS.take(), LHSType,
7236 LHSType->isPointerType() ? CK_BitCast
7237 : CK_AnyPointerToBlockPointerCast);
7241 if (LHSType->isObjCObjectPointerType() ||
7242 RHSType->isObjCObjectPointerType()) {
7243 const PointerType *LPT = LHSType->getAs<PointerType>();
7244 const PointerType *RPT = RHSType->getAs<PointerType>();
7246 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7247 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7249 if (!LPtrToVoid && !RPtrToVoid &&
7250 !Context.typesAreCompatible(LHSType, RHSType)) {
7251 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7254 if (LHSIsNull && !RHSIsNull)
7255 LHS = ImpCastExprToType(LHS.take(), RHSType,
7256 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7258 RHS = ImpCastExprToType(RHS.take(), LHSType,
7259 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7262 if (LHSType->isObjCObjectPointerType() &&
7263 RHSType->isObjCObjectPointerType()) {
7264 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7265 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7267 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7268 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7270 if (LHSIsNull && !RHSIsNull)
7271 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7273 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7277 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7278 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7279 unsigned DiagID = 0;
7280 bool isError = false;
7281 if (LangOpts.DebuggerSupport) {
7282 // Under a debugger, allow the comparison of pointers to integers,
7283 // since users tend to want to compare addresses.
7284 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7285 (RHSIsNull && RHSType->isIntegerType())) {
7286 if (IsRelational && !getLangOpts().CPlusPlus)
7287 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7288 } else if (IsRelational && !getLangOpts().CPlusPlus)
7289 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7290 else if (getLangOpts().CPlusPlus) {
7291 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7294 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7298 << LHSType << RHSType << LHS.get()->getSourceRange()
7299 << RHS.get()->getSourceRange();
7304 if (LHSType->isIntegerType())
7305 LHS = ImpCastExprToType(LHS.take(), RHSType,
7306 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7308 RHS = ImpCastExprToType(RHS.take(), LHSType,
7309 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7313 // Handle block pointers.
7314 if (!IsRelational && RHSIsNull
7315 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7316 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7319 if (!IsRelational && LHSIsNull
7320 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7321 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7325 return InvalidOperands(Loc, LHS, RHS);
7329 // Return a signed type that is of identical size and number of elements.
7330 // For floating point vectors, return an integer type of identical size
7331 // and number of elements.
7332 QualType Sema::GetSignedVectorType(QualType V) {
7333 const VectorType *VTy = V->getAs<VectorType>();
7334 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7335 if (TypeSize == Context.getTypeSize(Context.CharTy))
7336 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7337 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7338 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7339 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7340 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7341 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7342 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7343 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7344 "Unhandled vector element size in vector compare");
7345 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7348 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7349 /// operates on extended vector types. Instead of producing an IntTy result,
7350 /// like a scalar comparison, a vector comparison produces a vector of integer
7352 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7354 bool IsRelational) {
7355 // Check to make sure we're operating on vectors of the same type and width,
7356 // Allowing one side to be a scalar of element type.
7357 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7361 QualType LHSType = LHS.get()->getType();
7363 // If AltiVec, the comparison results in a numeric type, i.e.
7364 // bool for C++, int for C
7365 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7366 return Context.getLogicalOperationType();
7368 // For non-floating point types, check for self-comparisons of the form
7369 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7370 // often indicate logic errors in the program.
7371 if (!LHSType->hasFloatingRepresentation()) {
7372 if (DeclRefExpr* DRL
7373 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7374 if (DeclRefExpr* DRR
7375 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7376 if (DRL->getDecl() == DRR->getDecl())
7377 DiagRuntimeBehavior(Loc, 0,
7378 PDiag(diag::warn_comparison_always)
7380 << 2 // "a constant"
7384 // Check for comparisons of floating point operands using != and ==.
7385 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7386 assert (RHS.get()->getType()->hasFloatingRepresentation());
7387 CheckFloatComparison(Loc, LHS.get(), RHS.get());
7390 // Return a signed type for the vector.
7391 return GetSignedVectorType(LHSType);
7394 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7395 SourceLocation Loc) {
7396 // Ensure that either both operands are of the same vector type, or
7397 // one operand is of a vector type and the other is of its element type.
7398 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7399 if (vType.isNull() || vType->isFloatingType())
7400 return InvalidOperands(Loc, LHS, RHS);
7402 return GetSignedVectorType(LHS.get()->getType());
7405 inline QualType Sema::CheckBitwiseOperands(
7406 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7407 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7409 if (LHS.get()->getType()->isVectorType() ||
7410 RHS.get()->getType()->isVectorType()) {
7411 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7412 RHS.get()->getType()->hasIntegerRepresentation())
7413 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7415 return InvalidOperands(Loc, LHS, RHS);
7418 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7419 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7421 if (LHSResult.isInvalid() || RHSResult.isInvalid())
7423 LHS = LHSResult.take();
7424 RHS = RHSResult.take();
7426 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7428 return InvalidOperands(Loc, LHS, RHS);
7431 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7432 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7434 // Check vector operands differently.
7435 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7436 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7438 // Diagnose cases where the user write a logical and/or but probably meant a
7439 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7441 if (LHS.get()->getType()->isIntegerType() &&
7442 !LHS.get()->getType()->isBooleanType() &&
7443 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7444 // Don't warn in macros or template instantiations.
7445 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7446 // If the RHS can be constant folded, and if it constant folds to something
7447 // that isn't 0 or 1 (which indicate a potential logical operation that
7448 // happened to fold to true/false) then warn.
7449 // Parens on the RHS are ignored.
7450 llvm::APSInt Result;
7451 if (RHS.get()->EvaluateAsInt(Result, Context))
7452 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7453 (Result != 0 && Result != 1)) {
7454 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7455 << RHS.get()->getSourceRange()
7456 << (Opc == BO_LAnd ? "&&" : "||");
7457 // Suggest replacing the logical operator with the bitwise version
7458 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7459 << (Opc == BO_LAnd ? "&" : "|")
7460 << FixItHint::CreateReplacement(SourceRange(
7461 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7463 Opc == BO_LAnd ? "&" : "|");
7465 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7466 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7467 << FixItHint::CreateRemoval(
7469 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7470 0, getSourceManager(),
7472 RHS.get()->getLocEnd()));
7476 if (!Context.getLangOpts().CPlusPlus) {
7477 LHS = UsualUnaryConversions(LHS.take());
7478 if (LHS.isInvalid())
7481 RHS = UsualUnaryConversions(RHS.take());
7482 if (RHS.isInvalid())
7485 if (!LHS.get()->getType()->isScalarType() ||
7486 !RHS.get()->getType()->isScalarType())
7487 return InvalidOperands(Loc, LHS, RHS);
7489 return Context.IntTy;
7492 // The following is safe because we only use this method for
7493 // non-overloadable operands.
7495 // C++ [expr.log.and]p1
7496 // C++ [expr.log.or]p1
7497 // The operands are both contextually converted to type bool.
7498 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7499 if (LHSRes.isInvalid())
7500 return InvalidOperands(Loc, LHS, RHS);
7503 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7504 if (RHSRes.isInvalid())
7505 return InvalidOperands(Loc, LHS, RHS);
7508 // C++ [expr.log.and]p2
7509 // C++ [expr.log.or]p2
7510 // The result is a bool.
7511 return Context.BoolTy;
7514 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7515 /// is a read-only property; return true if so. A readonly property expression
7516 /// depends on various declarations and thus must be treated specially.
7518 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7519 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7520 if (!PropExpr) return false;
7521 if (PropExpr->isImplicitProperty()) return false;
7523 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7524 QualType BaseType = PropExpr->isSuperReceiver() ?
7525 PropExpr->getSuperReceiverType() :
7526 PropExpr->getBase()->getType();
7528 if (const ObjCObjectPointerType *OPT =
7529 BaseType->getAsObjCInterfacePointerType())
7530 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7531 if (S.isPropertyReadonly(PDecl, IFace))
7536 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7537 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7538 if (!ME) return false;
7539 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7540 ObjCMessageExpr *Base =
7541 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7542 if (!Base) return false;
7543 return Base->getMethodDecl() != 0;
7546 /// Is the given expression (which must be 'const') a reference to a
7547 /// variable which was originally non-const, but which has become
7548 /// 'const' due to being captured within a block?
7549 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7550 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7551 assert(E->isLValue() && E->getType().isConstQualified());
7552 E = E->IgnoreParens();
7554 // Must be a reference to a declaration from an enclosing scope.
7555 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7556 if (!DRE) return NCCK_None;
7557 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7559 // The declaration must be a variable which is not declared 'const'.
7560 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7561 if (!var) return NCCK_None;
7562 if (var->getType().isConstQualified()) return NCCK_None;
7563 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7565 // Decide whether the first capture was for a block or a lambda.
7566 DeclContext *DC = S.CurContext;
7567 while (DC->getParent() != var->getDeclContext())
7568 DC = DC->getParent();
7569 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7572 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7573 /// emit an error and return true. If so, return false.
7574 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7575 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7576 SourceLocation OrigLoc = Loc;
7577 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7579 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7580 IsLV = Expr::MLV_ReadonlyProperty;
7581 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7582 IsLV = Expr::MLV_InvalidMessageExpression;
7583 if (IsLV == Expr::MLV_Valid)
7587 bool NeedType = false;
7588 switch (IsLV) { // C99 6.5.16p2
7589 case Expr::MLV_ConstQualified:
7590 Diag = diag::err_typecheck_assign_const;
7592 // Use a specialized diagnostic when we're assigning to an object
7593 // from an enclosing function or block.
7594 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7595 if (NCCK == NCCK_Block)
7596 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7598 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7602 // In ARC, use some specialized diagnostics for occasions where we
7603 // infer 'const'. These are always pseudo-strong variables.
7604 if (S.getLangOpts().ObjCAutoRefCount) {
7605 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7606 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7607 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7609 // Use the normal diagnostic if it's pseudo-__strong but the
7610 // user actually wrote 'const'.
7611 if (var->isARCPseudoStrong() &&
7612 (!var->getTypeSourceInfo() ||
7613 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7614 // There are two pseudo-strong cases:
7616 ObjCMethodDecl *method = S.getCurMethodDecl();
7617 if (method && var == method->getSelfDecl())
7618 Diag = method->isClassMethod()
7619 ? diag::err_typecheck_arc_assign_self_class_method
7620 : diag::err_typecheck_arc_assign_self;
7622 // - fast enumeration variables
7624 Diag = diag::err_typecheck_arr_assign_enumeration;
7628 Assign = SourceRange(OrigLoc, OrigLoc);
7629 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7630 // We need to preserve the AST regardless, so migration tool
7638 case Expr::MLV_ArrayType:
7639 case Expr::MLV_ArrayTemporary:
7640 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7643 case Expr::MLV_NotObjectType:
7644 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7647 case Expr::MLV_LValueCast:
7648 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7650 case Expr::MLV_Valid:
7651 llvm_unreachable("did not take early return for MLV_Valid");
7652 case Expr::MLV_InvalidExpression:
7653 case Expr::MLV_MemberFunction:
7654 case Expr::MLV_ClassTemporary:
7655 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7657 case Expr::MLV_IncompleteType:
7658 case Expr::MLV_IncompleteVoidType:
7659 return S.RequireCompleteType(Loc, E->getType(),
7660 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7661 case Expr::MLV_DuplicateVectorComponents:
7662 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7664 case Expr::MLV_ReadonlyProperty:
7665 case Expr::MLV_NoSetterProperty:
7666 llvm_unreachable("readonly properties should be processed differently");
7667 case Expr::MLV_InvalidMessageExpression:
7668 Diag = diag::error_readonly_message_assignment;
7670 case Expr::MLV_SubObjCPropertySetting:
7671 Diag = diag::error_no_subobject_property_setting;
7677 Assign = SourceRange(OrigLoc, OrigLoc);
7679 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7681 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7685 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7689 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7690 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7691 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7692 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7693 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7696 // Objective-C instance variables
7697 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7698 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7699 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7700 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7701 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7702 if (RL && RR && RL->getDecl() == RR->getDecl())
7703 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7708 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7710 QualType CompoundType) {
7711 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7713 // Verify that LHS is a modifiable lvalue, and emit error if not.
7714 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7717 QualType LHSType = LHSExpr->getType();
7718 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7720 AssignConvertType ConvTy;
7721 if (CompoundType.isNull()) {
7722 Expr *RHSCheck = RHS.get();
7724 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7726 QualType LHSTy(LHSType);
7727 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7728 if (RHS.isInvalid())
7730 // Special case of NSObject attributes on c-style pointer types.
7731 if (ConvTy == IncompatiblePointer &&
7732 ((Context.isObjCNSObjectType(LHSType) &&
7733 RHSType->isObjCObjectPointerType()) ||
7734 (Context.isObjCNSObjectType(RHSType) &&
7735 LHSType->isObjCObjectPointerType())))
7736 ConvTy = Compatible;
7738 if (ConvTy == Compatible &&
7739 LHSType->isObjCObjectType())
7740 Diag(Loc, diag::err_objc_object_assignment)
7743 // If the RHS is a unary plus or minus, check to see if they = and + are
7744 // right next to each other. If so, the user may have typo'd "x =+ 4"
7745 // instead of "x += 4".
7746 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7747 RHSCheck = ICE->getSubExpr();
7748 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7749 if ((UO->getOpcode() == UO_Plus ||
7750 UO->getOpcode() == UO_Minus) &&
7751 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7752 // Only if the two operators are exactly adjacent.
7753 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7754 // And there is a space or other character before the subexpr of the
7755 // unary +/-. We don't want to warn on "x=-1".
7756 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7757 UO->getSubExpr()->getLocStart().isFileID()) {
7758 Diag(Loc, diag::warn_not_compound_assign)
7759 << (UO->getOpcode() == UO_Plus ? "+" : "-")
7760 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7764 if (ConvTy == Compatible) {
7765 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7766 // Warn about retain cycles where a block captures the LHS, but
7767 // not if the LHS is a simple variable into which the block is
7768 // being stored...unless that variable can be captured by reference!
7769 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7770 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7771 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7772 checkRetainCycles(LHSExpr, RHS.get());
7774 // It is safe to assign a weak reference into a strong variable.
7775 // Although this code can still have problems:
7776 // id x = self.weakProp;
7777 // id y = self.weakProp;
7778 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7779 // paths through the function. This should be revisited if
7780 // -Wrepeated-use-of-weak is made flow-sensitive.
7781 DiagnosticsEngine::Level Level =
7782 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7783 RHS.get()->getLocStart());
7784 if (Level != DiagnosticsEngine::Ignored)
7785 getCurFunction()->markSafeWeakUse(RHS.get());
7787 } else if (getLangOpts().ObjCAutoRefCount) {
7788 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7792 // Compound assignment "x += y"
7793 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7796 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7797 RHS.get(), AA_Assigning))
7800 CheckForNullPointerDereference(*this, LHSExpr);
7802 // C99 6.5.16p3: The type of an assignment expression is the type of the
7803 // left operand unless the left operand has qualified type, in which case
7804 // it is the unqualified version of the type of the left operand.
7805 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7806 // is converted to the type of the assignment expression (above).
7807 // C++ 5.17p1: the type of the assignment expression is that of its left
7809 return (getLangOpts().CPlusPlus
7810 ? LHSType : LHSType.getUnqualifiedType());
7814 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7815 SourceLocation Loc) {
7816 LHS = S.CheckPlaceholderExpr(LHS.take());
7817 RHS = S.CheckPlaceholderExpr(RHS.take());
7818 if (LHS.isInvalid() || RHS.isInvalid())
7821 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7822 // operands, but not unary promotions.
7823 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7825 // So we treat the LHS as a ignored value, and in C++ we allow the
7826 // containing site to determine what should be done with the RHS.
7827 LHS = S.IgnoredValueConversions(LHS.take());
7828 if (LHS.isInvalid())
7831 S.DiagnoseUnusedExprResult(LHS.get());
7833 if (!S.getLangOpts().CPlusPlus) {
7834 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7835 if (RHS.isInvalid())
7837 if (!RHS.get()->getType()->isVoidType())
7838 S.RequireCompleteType(Loc, RHS.get()->getType(),
7839 diag::err_incomplete_type);
7842 return RHS.get()->getType();
7845 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7846 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7847 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7849 SourceLocation OpLoc,
7850 bool IsInc, bool IsPrefix) {
7851 if (Op->isTypeDependent())
7852 return S.Context.DependentTy;
7854 QualType ResType = Op->getType();
7855 // Atomic types can be used for increment / decrement where the non-atomic
7856 // versions can, so ignore the _Atomic() specifier for the purpose of
7858 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7859 ResType = ResAtomicType->getValueType();
7861 assert(!ResType.isNull() && "no type for increment/decrement expression");
7863 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
7864 // Decrement of bool is not allowed.
7866 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7869 // Increment of bool sets it to true, but is deprecated.
7870 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7871 } else if (ResType->isRealType()) {
7873 } else if (ResType->isPointerType()) {
7874 // C99 6.5.2.4p2, 6.5.6p2
7875 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7877 } else if (ResType->isObjCObjectPointerType()) {
7878 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7879 // Otherwise, we just need a complete type.
7880 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7881 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7883 } else if (ResType->isAnyComplexType()) {
7884 // C99 does not support ++/-- on complex types, we allow as an extension.
7885 S.Diag(OpLoc, diag::ext_integer_increment_complex)
7886 << ResType << Op->getSourceRange();
7887 } else if (ResType->isPlaceholderType()) {
7888 ExprResult PR = S.CheckPlaceholderExpr(Op);
7889 if (PR.isInvalid()) return QualType();
7890 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7892 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
7893 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7895 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7896 << ResType << int(IsInc) << Op->getSourceRange();
7899 // At this point, we know we have a real, complex or pointer type.
7900 // Now make sure the operand is a modifiable lvalue.
7901 if (CheckForModifiableLvalue(Op, OpLoc, S))
7903 // In C++, a prefix increment is the same type as the operand. Otherwise
7904 // (in C or with postfix), the increment is the unqualified type of the
7906 if (IsPrefix && S.getLangOpts().CPlusPlus) {
7911 return ResType.getUnqualifiedType();
7916 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7917 /// This routine allows us to typecheck complex/recursive expressions
7918 /// where the declaration is needed for type checking. We only need to
7919 /// handle cases when the expression references a function designator
7920 /// or is an lvalue. Here are some examples:
7922 /// - &*****f => f for f a function designator.
7924 /// - &s.zz[1].yy -> s, if zz is an array
7925 /// - *(x + 1) -> x, if x is an array
7926 /// - &"123"[2] -> 0
7927 /// - & __real__ x -> x
7928 static ValueDecl *getPrimaryDecl(Expr *E) {
7929 switch (E->getStmtClass()) {
7930 case Stmt::DeclRefExprClass:
7931 return cast<DeclRefExpr>(E)->getDecl();
7932 case Stmt::MemberExprClass:
7933 // If this is an arrow operator, the address is an offset from
7934 // the base's value, so the object the base refers to is
7936 if (cast<MemberExpr>(E)->isArrow())
7938 // Otherwise, the expression refers to a part of the base
7939 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7940 case Stmt::ArraySubscriptExprClass: {
7941 // FIXME: This code shouldn't be necessary! We should catch the implicit
7942 // promotion of register arrays earlier.
7943 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7944 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7945 if (ICE->getSubExpr()->getType()->isArrayType())
7946 return getPrimaryDecl(ICE->getSubExpr());
7950 case Stmt::UnaryOperatorClass: {
7951 UnaryOperator *UO = cast<UnaryOperator>(E);
7953 switch(UO->getOpcode()) {
7957 return getPrimaryDecl(UO->getSubExpr());
7962 case Stmt::ParenExprClass:
7963 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7964 case Stmt::ImplicitCastExprClass:
7965 // If the result of an implicit cast is an l-value, we care about
7966 // the sub-expression; otherwise, the result here doesn't matter.
7967 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7976 AO_Vector_Element = 1,
7977 AO_Property_Expansion = 2,
7978 AO_Register_Variable = 3,
7982 /// \brief Diagnose invalid operand for address of operations.
7984 /// \param Type The type of operand which cannot have its address taken.
7985 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7986 Expr *E, unsigned Type) {
7987 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7990 /// CheckAddressOfOperand - The operand of & must be either a function
7991 /// designator or an lvalue designating an object. If it is an lvalue, the
7992 /// object cannot be declared with storage class register or be a bit field.
7993 /// Note: The usual conversions are *not* applied to the operand of the &
7994 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7995 /// In C++, the operand might be an overloaded function name, in which case
7996 /// we allow the '&' but retain the overloaded-function type.
7997 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
7998 SourceLocation OpLoc) {
7999 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8000 if (PTy->getKind() == BuiltinType::Overload) {
8001 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8002 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8003 << OrigOp.get()->getSourceRange();
8007 return S.Context.OverloadTy;
8010 if (PTy->getKind() == BuiltinType::UnknownAny)
8011 return S.Context.UnknownAnyTy;
8013 if (PTy->getKind() == BuiltinType::BoundMember) {
8014 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8015 << OrigOp.get()->getSourceRange();
8019 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8020 if (OrigOp.isInvalid()) return QualType();
8023 if (OrigOp.get()->isTypeDependent())
8024 return S.Context.DependentTy;
8026 assert(!OrigOp.get()->getType()->isPlaceholderType());
8028 // Make sure to ignore parentheses in subsequent checks
8029 Expr *op = OrigOp.get()->IgnoreParens();
8031 if (S.getLangOpts().C99) {
8032 // Implement C99-only parts of addressof rules.
8033 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8034 if (uOp->getOpcode() == UO_Deref)
8035 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8036 // (assuming the deref expression is valid).
8037 return uOp->getSubExpr()->getType();
8039 // Technically, there should be a check for array subscript
8040 // expressions here, but the result of one is always an lvalue anyway.
8042 ValueDecl *dcl = getPrimaryDecl(op);
8043 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8044 unsigned AddressOfError = AO_No_Error;
8046 if (lval == Expr::LV_ClassTemporary) {
8047 bool sfinae = S.isSFINAEContext();
8048 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8049 : diag::ext_typecheck_addrof_class_temporary)
8050 << op->getType() << op->getSourceRange();
8053 } else if (isa<ObjCSelectorExpr>(op)) {
8054 return S.Context.getPointerType(op->getType());
8055 } else if (lval == Expr::LV_MemberFunction) {
8056 // If it's an instance method, make a member pointer.
8057 // The expression must have exactly the form &A::foo.
8059 // If the underlying expression isn't a decl ref, give up.
8060 if (!isa<DeclRefExpr>(op)) {
8061 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8062 << OrigOp.get()->getSourceRange();
8065 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8066 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8068 // The id-expression was parenthesized.
8069 if (OrigOp.get() != DRE) {
8070 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8071 << OrigOp.get()->getSourceRange();
8073 // The method was named without a qualifier.
8074 } else if (!DRE->getQualifier()) {
8075 if (MD->getParent()->getName().empty())
8076 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8077 << op->getSourceRange();
8079 SmallString<32> Str;
8080 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8081 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8082 << op->getSourceRange()
8083 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8087 return S.Context.getMemberPointerType(op->getType(),
8088 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8089 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8091 // The operand must be either an l-value or a function designator
8092 if (!op->getType()->isFunctionType()) {
8093 // Use a special diagnostic for loads from property references.
8094 if (isa<PseudoObjectExpr>(op)) {
8095 AddressOfError = AO_Property_Expansion;
8097 // FIXME: emit more specific diag...
8098 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8099 << op->getSourceRange();
8103 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8104 // The operand cannot be a bit-field
8105 AddressOfError = AO_Bit_Field;
8106 } else if (op->getObjectKind() == OK_VectorComponent) {
8107 // The operand cannot be an element of a vector
8108 AddressOfError = AO_Vector_Element;
8109 } else if (dcl) { // C99 6.5.3.2p1
8110 // We have an lvalue with a decl. Make sure the decl is not declared
8111 // with the register storage-class specifier.
8112 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8113 // in C++ it is not error to take address of a register
8114 // variable (c++03 7.1.1P3)
8115 if (vd->getStorageClass() == SC_Register &&
8116 !S.getLangOpts().CPlusPlus) {
8117 AddressOfError = AO_Register_Variable;
8119 } else if (isa<FunctionTemplateDecl>(dcl)) {
8120 return S.Context.OverloadTy;
8121 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8122 // Okay: we can take the address of a field.
8123 // Could be a pointer to member, though, if there is an explicit
8124 // scope qualifier for the class.
8125 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8126 DeclContext *Ctx = dcl->getDeclContext();
8127 if (Ctx && Ctx->isRecord()) {
8128 if (dcl->getType()->isReferenceType()) {
8130 diag::err_cannot_form_pointer_to_member_of_reference_type)
8131 << dcl->getDeclName() << dcl->getType();
8135 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8136 Ctx = Ctx->getParent();
8137 return S.Context.getMemberPointerType(op->getType(),
8138 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8141 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8142 llvm_unreachable("Unknown/unexpected decl type");
8145 if (AddressOfError != AO_No_Error) {
8146 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8150 if (lval == Expr::LV_IncompleteVoidType) {
8151 // Taking the address of a void variable is technically illegal, but we
8152 // allow it in cases which are otherwise valid.
8153 // Example: "extern void x; void* y = &x;".
8154 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8157 // If the operand has type "type", the result has type "pointer to type".
8158 if (op->getType()->isObjCObjectType())
8159 return S.Context.getObjCObjectPointerType(op->getType());
8160 return S.Context.getPointerType(op->getType());
8163 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8164 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8165 SourceLocation OpLoc) {
8166 if (Op->isTypeDependent())
8167 return S.Context.DependentTy;
8169 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8170 if (ConvResult.isInvalid())
8172 Op = ConvResult.take();
8173 QualType OpTy = Op->getType();
8176 if (isa<CXXReinterpretCastExpr>(Op)) {
8177 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8178 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8179 Op->getSourceRange());
8182 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8183 // is an incomplete type or void. It would be possible to warn about
8184 // dereferencing a void pointer, but it's completely well-defined, and such a
8185 // warning is unlikely to catch any mistakes.
8186 if (const PointerType *PT = OpTy->getAs<PointerType>())
8187 Result = PT->getPointeeType();
8188 else if (const ObjCObjectPointerType *OPT =
8189 OpTy->getAs<ObjCObjectPointerType>())
8190 Result = OPT->getPointeeType();
8192 ExprResult PR = S.CheckPlaceholderExpr(Op);
8193 if (PR.isInvalid()) return QualType();
8194 if (PR.take() != Op)
8195 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8198 if (Result.isNull()) {
8199 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8200 << OpTy << Op->getSourceRange();
8204 // Dereferences are usually l-values...
8207 // ...except that certain expressions are never l-values in C.
8208 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8214 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8215 tok::TokenKind Kind) {
8216 BinaryOperatorKind Opc;
8218 default: llvm_unreachable("Unknown binop!");
8219 case tok::periodstar: Opc = BO_PtrMemD; break;
8220 case tok::arrowstar: Opc = BO_PtrMemI; break;
8221 case tok::star: Opc = BO_Mul; break;
8222 case tok::slash: Opc = BO_Div; break;
8223 case tok::percent: Opc = BO_Rem; break;
8224 case tok::plus: Opc = BO_Add; break;
8225 case tok::minus: Opc = BO_Sub; break;
8226 case tok::lessless: Opc = BO_Shl; break;
8227 case tok::greatergreater: Opc = BO_Shr; break;
8228 case tok::lessequal: Opc = BO_LE; break;
8229 case tok::less: Opc = BO_LT; break;
8230 case tok::greaterequal: Opc = BO_GE; break;
8231 case tok::greater: Opc = BO_GT; break;
8232 case tok::exclaimequal: Opc = BO_NE; break;
8233 case tok::equalequal: Opc = BO_EQ; break;
8234 case tok::amp: Opc = BO_And; break;
8235 case tok::caret: Opc = BO_Xor; break;
8236 case tok::pipe: Opc = BO_Or; break;
8237 case tok::ampamp: Opc = BO_LAnd; break;
8238 case tok::pipepipe: Opc = BO_LOr; break;
8239 case tok::equal: Opc = BO_Assign; break;
8240 case tok::starequal: Opc = BO_MulAssign; break;
8241 case tok::slashequal: Opc = BO_DivAssign; break;
8242 case tok::percentequal: Opc = BO_RemAssign; break;
8243 case tok::plusequal: Opc = BO_AddAssign; break;
8244 case tok::minusequal: Opc = BO_SubAssign; break;
8245 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8246 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8247 case tok::ampequal: Opc = BO_AndAssign; break;
8248 case tok::caretequal: Opc = BO_XorAssign; break;
8249 case tok::pipeequal: Opc = BO_OrAssign; break;
8250 case tok::comma: Opc = BO_Comma; break;
8255 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8256 tok::TokenKind Kind) {
8257 UnaryOperatorKind Opc;
8259 default: llvm_unreachable("Unknown unary op!");
8260 case tok::plusplus: Opc = UO_PreInc; break;
8261 case tok::minusminus: Opc = UO_PreDec; break;
8262 case tok::amp: Opc = UO_AddrOf; break;
8263 case tok::star: Opc = UO_Deref; break;
8264 case tok::plus: Opc = UO_Plus; break;
8265 case tok::minus: Opc = UO_Minus; break;
8266 case tok::tilde: Opc = UO_Not; break;
8267 case tok::exclaim: Opc = UO_LNot; break;
8268 case tok::kw___real: Opc = UO_Real; break;
8269 case tok::kw___imag: Opc = UO_Imag; break;
8270 case tok::kw___extension__: Opc = UO_Extension; break;
8275 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8276 /// This warning is only emitted for builtin assignment operations. It is also
8277 /// suppressed in the event of macro expansions.
8278 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8279 SourceLocation OpLoc) {
8280 if (!S.ActiveTemplateInstantiations.empty())
8282 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8284 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8285 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8286 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8287 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8288 if (!LHSDeclRef || !RHSDeclRef ||
8289 LHSDeclRef->getLocation().isMacroID() ||
8290 RHSDeclRef->getLocation().isMacroID())
8292 const ValueDecl *LHSDecl =
8293 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8294 const ValueDecl *RHSDecl =
8295 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8296 if (LHSDecl != RHSDecl)
8298 if (LHSDecl->getType().isVolatileQualified())
8300 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8301 if (RefTy->getPointeeType().isVolatileQualified())
8304 S.Diag(OpLoc, diag::warn_self_assignment)
8305 << LHSDeclRef->getType()
8306 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8309 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8310 /// operator @p Opc at location @c TokLoc. This routine only supports
8311 /// built-in operations; ActOnBinOp handles overloaded operators.
8312 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8313 BinaryOperatorKind Opc,
8314 Expr *LHSExpr, Expr *RHSExpr) {
8315 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
8316 // The syntax only allows initializer lists on the RHS of assignment,
8317 // so we don't need to worry about accepting invalid code for
8318 // non-assignment operators.
8320 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8321 // of x = {} is x = T().
8322 InitializationKind Kind =
8323 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8324 InitializedEntity Entity =
8325 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8326 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8327 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8328 if (Init.isInvalid())
8330 RHSExpr = Init.take();
8333 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8334 QualType ResultTy; // Result type of the binary operator.
8335 // The following two variables are used for compound assignment operators
8336 QualType CompLHSTy; // Type of LHS after promotions for computation
8337 QualType CompResultTy; // Type of computation result
8338 ExprValueKind VK = VK_RValue;
8339 ExprObjectKind OK = OK_Ordinary;
8343 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8344 if (getLangOpts().CPlusPlus &&
8345 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8346 VK = LHS.get()->getValueKind();
8347 OK = LHS.get()->getObjectKind();
8349 if (!ResultTy.isNull())
8350 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8354 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8359 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8363 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8366 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8369 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8373 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8379 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8383 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8388 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8392 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8396 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8397 Opc == BO_DivAssign);
8398 CompLHSTy = CompResultTy;
8399 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8400 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8403 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8404 CompLHSTy = CompResultTy;
8405 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8406 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8409 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8410 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8411 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8414 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8415 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8416 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8420 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8421 CompLHSTy = CompResultTy;
8422 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8423 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8428 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8429 CompLHSTy = CompResultTy;
8430 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8431 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8434 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8435 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8436 VK = RHS.get()->getValueKind();
8437 OK = RHS.get()->getObjectKind();
8441 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8444 // Check for array bounds violations for both sides of the BinaryOperator
8445 CheckArrayAccess(LHS.get());
8446 CheckArrayAccess(RHS.get());
8448 if (CompResultTy.isNull())
8449 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8450 ResultTy, VK, OK, OpLoc,
8451 FPFeatures.fp_contract));
8452 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8455 OK = LHS.get()->getObjectKind();
8457 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8458 ResultTy, VK, OK, CompLHSTy,
8459 CompResultTy, OpLoc,
8460 FPFeatures.fp_contract));
8463 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8464 /// operators are mixed in a way that suggests that the programmer forgot that
8465 /// comparison operators have higher precedence. The most typical example of
8466 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8467 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8468 SourceLocation OpLoc, Expr *LHSExpr,
8470 typedef BinaryOperator BinOp;
8471 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8472 RHSopc = static_cast<BinOp::Opcode>(-1);
8473 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8474 LHSopc = BO->getOpcode();
8475 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8476 RHSopc = BO->getOpcode();
8478 // Subs are not binary operators.
8479 if (LHSopc == -1 && RHSopc == -1)
8482 // Bitwise operations are sometimes used as eager logical ops.
8483 // Don't diagnose this.
8484 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8485 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
8488 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8489 bool isRightComp = BinOp::isComparisonOp(RHSopc);
8490 if (!isLeftComp && !isRightComp) return;
8492 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8494 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8495 StringRef OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8496 : BinOp::getOpcodeStr(RHSopc);
8497 SourceRange ParensRange = isLeftComp ?
8498 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8499 RHSExpr->getLocEnd())
8500 : SourceRange(LHSExpr->getLocStart(),
8501 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
8503 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8504 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8505 SuggestParentheses(Self, OpLoc,
8506 Self.PDiag(diag::note_precedence_silence) << OpStr,
8507 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8508 SuggestParentheses(Self, OpLoc,
8509 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8513 /// \brief It accepts a '&' expr that is inside a '|' one.
8514 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8517 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8518 BinaryOperator *Bop) {
8519 assert(Bop->getOpcode() == BO_And);
8520 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8521 << Bop->getSourceRange() << OpLoc;
8522 SuggestParentheses(Self, Bop->getOperatorLoc(),
8523 Self.PDiag(diag::note_precedence_silence)
8524 << Bop->getOpcodeStr(),
8525 Bop->getSourceRange());
8528 /// \brief It accepts a '&&' expr that is inside a '||' one.
8529 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8532 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8533 BinaryOperator *Bop) {
8534 assert(Bop->getOpcode() == BO_LAnd);
8535 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8536 << Bop->getSourceRange() << OpLoc;
8537 SuggestParentheses(Self, Bop->getOperatorLoc(),
8538 Self.PDiag(diag::note_precedence_silence)
8539 << Bop->getOpcodeStr(),
8540 Bop->getSourceRange());
8543 /// \brief Returns true if the given expression can be evaluated as a constant
8545 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8547 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8550 /// \brief Returns true if the given expression can be evaluated as a constant
8552 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8554 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8557 /// \brief Look for '&&' in the left hand of a '||' expr.
8558 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8559 Expr *LHSExpr, Expr *RHSExpr) {
8560 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8561 if (Bop->getOpcode() == BO_LAnd) {
8562 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8563 if (EvaluatesAsFalse(S, RHSExpr))
8565 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8566 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8567 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8568 } else if (Bop->getOpcode() == BO_LOr) {
8569 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8570 // If it's "a || b && 1 || c" we didn't warn earlier for
8571 // "a || b && 1", but warn now.
8572 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8573 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8579 /// \brief Look for '&&' in the right hand of a '||' expr.
8580 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8581 Expr *LHSExpr, Expr *RHSExpr) {
8582 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8583 if (Bop->getOpcode() == BO_LAnd) {
8584 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8585 if (EvaluatesAsFalse(S, LHSExpr))
8587 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8588 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8589 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8594 /// \brief Look for '&' in the left or right hand of a '|' expr.
8595 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8597 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8598 if (Bop->getOpcode() == BO_And)
8599 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8603 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8604 Expr *SubExpr, StringRef Shift) {
8605 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8606 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
8607 StringRef Op = Bop->getOpcodeStr();
8608 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
8609 << Bop->getSourceRange() << OpLoc << Shift << Op;
8610 SuggestParentheses(S, Bop->getOperatorLoc(),
8611 S.PDiag(diag::note_precedence_silence) << Op,
8612 Bop->getSourceRange());
8617 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8619 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8620 SourceLocation OpLoc, Expr *LHSExpr,
8622 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8623 if (BinaryOperator::isBitwiseOp(Opc))
8624 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8626 // Diagnose "arg1 & arg2 | arg3"
8627 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8628 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8629 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8632 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8633 // We don't warn for 'assert(a || b && "bad")' since this is safe.
8634 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8635 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8636 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8639 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8641 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8642 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8643 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
8647 // Binary Operators. 'Tok' is the token for the operator.
8648 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8649 tok::TokenKind Kind,
8650 Expr *LHSExpr, Expr *RHSExpr) {
8651 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8652 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8653 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8655 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8656 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8658 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8661 /// Build an overloaded binary operator expression in the given scope.
8662 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8663 BinaryOperatorKind Opc,
8664 Expr *LHS, Expr *RHS) {
8665 // Find all of the overloaded operators visible from this
8666 // point. We perform both an operator-name lookup from the local
8667 // scope and an argument-dependent lookup based on the types of
8669 UnresolvedSet<16> Functions;
8670 OverloadedOperatorKind OverOp
8671 = BinaryOperator::getOverloadedOperator(Opc);
8672 if (Sc && OverOp != OO_None)
8673 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8674 RHS->getType(), Functions);
8676 // Build the (potentially-overloaded, potentially-dependent)
8677 // binary operation.
8678 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8681 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8682 BinaryOperatorKind Opc,
8683 Expr *LHSExpr, Expr *RHSExpr) {
8684 // We want to end up calling one of checkPseudoObjectAssignment
8685 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8686 // both expressions are overloadable or either is type-dependent),
8687 // or CreateBuiltinBinOp (in any other case). We also want to get
8688 // any placeholder types out of the way.
8690 // Handle pseudo-objects in the LHS.
8691 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8692 // Assignments with a pseudo-object l-value need special analysis.
8693 if (pty->getKind() == BuiltinType::PseudoObject &&
8694 BinaryOperator::isAssignmentOp(Opc))
8695 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8697 // Don't resolve overloads if the other type is overloadable.
8698 if (pty->getKind() == BuiltinType::Overload) {
8699 // We can't actually test that if we still have a placeholder,
8700 // though. Fortunately, none of the exceptions we see in that
8701 // code below are valid when the LHS is an overload set. Note
8702 // that an overload set can be dependently-typed, but it never
8703 // instantiates to having an overloadable type.
8704 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8705 if (resolvedRHS.isInvalid()) return ExprError();
8706 RHSExpr = resolvedRHS.take();
8708 if (RHSExpr->isTypeDependent() ||
8709 RHSExpr->getType()->isOverloadableType())
8710 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8713 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8714 if (LHS.isInvalid()) return ExprError();
8715 LHSExpr = LHS.take();
8718 // Handle pseudo-objects in the RHS.
8719 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8720 // An overload in the RHS can potentially be resolved by the type
8721 // being assigned to.
8722 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8723 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8724 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8726 if (LHSExpr->getType()->isOverloadableType())
8727 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8729 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8732 // Don't resolve overloads if the other type is overloadable.
8733 if (pty->getKind() == BuiltinType::Overload &&
8734 LHSExpr->getType()->isOverloadableType())
8735 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8737 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8738 if (!resolvedRHS.isUsable()) return ExprError();
8739 RHSExpr = resolvedRHS.take();
8742 if (getLangOpts().CPlusPlus) {
8743 // If either expression is type-dependent, always build an
8745 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8746 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8748 // Otherwise, build an overloaded op if either expression has an
8749 // overloadable type.
8750 if (LHSExpr->getType()->isOverloadableType() ||
8751 RHSExpr->getType()->isOverloadableType())
8752 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8755 // Build a built-in binary operation.
8756 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8759 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8760 UnaryOperatorKind Opc,
8762 ExprResult Input = Owned(InputExpr);
8763 ExprValueKind VK = VK_RValue;
8764 ExprObjectKind OK = OK_Ordinary;
8765 QualType resultType;
8771 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8778 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8781 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8782 if (Input.isInvalid()) return ExprError();
8783 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8788 Input = UsualUnaryConversions(Input.take());
8789 if (Input.isInvalid()) return ExprError();
8790 resultType = Input.get()->getType();
8791 if (resultType->isDependentType())
8793 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8794 resultType->isVectorType())
8796 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
8797 resultType->isEnumeralType())
8799 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
8801 resultType->isPointerType())
8804 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8805 << resultType << Input.get()->getSourceRange());
8807 case UO_Not: // bitwise complement
8808 Input = UsualUnaryConversions(Input.take());
8809 if (Input.isInvalid()) return ExprError();
8810 resultType = Input.get()->getType();
8811 if (resultType->isDependentType())
8813 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8814 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8815 // C99 does not support '~' for complex conjugation.
8816 Diag(OpLoc, diag::ext_integer_complement_complex)
8817 << resultType << Input.get()->getSourceRange();
8818 else if (resultType->hasIntegerRepresentation())
8821 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8822 << resultType << Input.get()->getSourceRange());
8826 case UO_LNot: // logical negation
8827 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8828 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8829 if (Input.isInvalid()) return ExprError();
8830 resultType = Input.get()->getType();
8832 // Though we still have to promote half FP to float...
8833 if (resultType->isHalfType()) {
8834 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8835 resultType = Context.FloatTy;
8838 if (resultType->isDependentType())
8840 if (resultType->isScalarType()) {
8841 // C99 6.5.3.3p1: ok, fallthrough;
8842 if (Context.getLangOpts().CPlusPlus) {
8843 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8844 // operand contextually converted to bool.
8845 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8846 ScalarTypeToBooleanCastKind(resultType));
8848 } else if (resultType->isExtVectorType()) {
8849 // Vector logical not returns the signed variant of the operand type.
8850 resultType = GetSignedVectorType(resultType);
8853 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8854 << resultType << Input.get()->getSourceRange());
8857 // LNot always has type int. C99 6.5.3.3p5.
8858 // In C++, it's bool. C++ 5.3.1p8
8859 resultType = Context.getLogicalOperationType();
8863 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8864 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8865 // complex l-values to ordinary l-values and all other values to r-values.
8866 if (Input.isInvalid()) return ExprError();
8867 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8868 if (Input.get()->getValueKind() != VK_RValue &&
8869 Input.get()->getObjectKind() == OK_Ordinary)
8870 VK = Input.get()->getValueKind();
8871 } else if (!getLangOpts().CPlusPlus) {
8872 // In C, a volatile scalar is read by __imag. In C++, it is not.
8873 Input = DefaultLvalueConversion(Input.take());
8877 resultType = Input.get()->getType();
8878 VK = Input.get()->getValueKind();
8879 OK = Input.get()->getObjectKind();
8882 if (resultType.isNull() || Input.isInvalid())
8885 // Check for array bounds violations in the operand of the UnaryOperator,
8886 // except for the '*' and '&' operators that have to be handled specially
8887 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8888 // that are explicitly defined as valid by the standard).
8889 if (Opc != UO_AddrOf && Opc != UO_Deref)
8890 CheckArrayAccess(Input.get());
8892 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8896 /// \brief Determine whether the given expression is a qualified member
8897 /// access expression, of a form that could be turned into a pointer to member
8898 /// with the address-of operator.
8899 static bool isQualifiedMemberAccess(Expr *E) {
8900 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8901 if (!DRE->getQualifier())
8904 ValueDecl *VD = DRE->getDecl();
8905 if (!VD->isCXXClassMember())
8908 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8911 return Method->isInstance();
8916 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8917 if (!ULE->getQualifier())
8920 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8921 DEnd = ULE->decls_end();
8923 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8924 if (Method->isInstance())
8927 // Overload set does not contain methods.
8938 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8939 UnaryOperatorKind Opc, Expr *Input) {
8940 // First things first: handle placeholders so that the
8941 // overloaded-operator check considers the right type.
8942 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8943 // Increment and decrement of pseudo-object references.
8944 if (pty->getKind() == BuiltinType::PseudoObject &&
8945 UnaryOperator::isIncrementDecrementOp(Opc))
8946 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8948 // extension is always a builtin operator.
8949 if (Opc == UO_Extension)
8950 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8952 // & gets special logic for several kinds of placeholder.
8953 // The builtin code knows what to do.
8954 if (Opc == UO_AddrOf &&
8955 (pty->getKind() == BuiltinType::Overload ||
8956 pty->getKind() == BuiltinType::UnknownAny ||
8957 pty->getKind() == BuiltinType::BoundMember))
8958 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8960 // Anything else needs to be handled now.
8961 ExprResult Result = CheckPlaceholderExpr(Input);
8962 if (Result.isInvalid()) return ExprError();
8963 Input = Result.take();
8966 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
8967 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8968 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
8969 // Find all of the overloaded operators visible from this
8970 // point. We perform both an operator-name lookup from the local
8971 // scope and an argument-dependent lookup based on the types of
8973 UnresolvedSet<16> Functions;
8974 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8975 if (S && OverOp != OO_None)
8976 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8979 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8982 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8985 // Unary Operators. 'Tok' is the token for the operator.
8986 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8987 tok::TokenKind Op, Expr *Input) {
8988 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8991 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8992 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8993 LabelDecl *TheDecl) {
8995 // Create the AST node. The address of a label always has type 'void*'.
8996 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8997 Context.getPointerType(Context.VoidTy)));
9000 /// Given the last statement in a statement-expression, check whether
9001 /// the result is a producing expression (like a call to an
9002 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9003 /// release out of the full-expression. Otherwise, return null.
9005 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9006 // Should always be wrapped with one of these.
9007 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9008 if (!cleanups) return 0;
9010 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9011 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9014 // Splice out the cast. This shouldn't modify any interesting
9015 // features of the statement.
9016 Expr *producer = cast->getSubExpr();
9017 assert(producer->getType() == cast->getType());
9018 assert(producer->getValueKind() == cast->getValueKind());
9019 cleanups->setSubExpr(producer);
9023 void Sema::ActOnStartStmtExpr() {
9024 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9027 void Sema::ActOnStmtExprError() {
9028 // Note that function is also called by TreeTransform when leaving a
9029 // StmtExpr scope without rebuilding anything.
9031 DiscardCleanupsInEvaluationContext();
9032 PopExpressionEvaluationContext();
9036 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9037 SourceLocation RPLoc) { // "({..})"
9038 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9039 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9041 if (hasAnyUnrecoverableErrorsInThisFunction())
9042 DiscardCleanupsInEvaluationContext();
9043 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9044 PopExpressionEvaluationContext();
9047 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9049 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9051 // FIXME: there are a variety of strange constraints to enforce here, for
9052 // example, it is not possible to goto into a stmt expression apparently.
9053 // More semantic analysis is needed.
9055 // If there are sub stmts in the compound stmt, take the type of the last one
9056 // as the type of the stmtexpr.
9057 QualType Ty = Context.VoidTy;
9058 bool StmtExprMayBindToTemp = false;
9059 if (!Compound->body_empty()) {
9060 Stmt *LastStmt = Compound->body_back();
9061 LabelStmt *LastLabelStmt = 0;
9062 // If LastStmt is a label, skip down through into the body.
9063 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9064 LastLabelStmt = Label;
9065 LastStmt = Label->getSubStmt();
9068 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9069 // Do function/array conversion on the last expression, but not
9070 // lvalue-to-rvalue. However, initialize an unqualified type.
9071 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9072 if (LastExpr.isInvalid())
9074 Ty = LastExpr.get()->getType().getUnqualifiedType();
9076 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9077 // In ARC, if the final expression ends in a consume, splice
9078 // the consume out and bind it later. In the alternate case
9079 // (when dealing with a retainable type), the result
9080 // initialization will create a produce. In both cases the
9081 // result will be +1, and we'll need to balance that out with
9083 if (Expr *rebuiltLastStmt
9084 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9085 LastExpr = rebuiltLastStmt;
9087 LastExpr = PerformCopyInitialization(
9088 InitializedEntity::InitializeResult(LPLoc,
9095 if (LastExpr.isInvalid())
9097 if (LastExpr.get() != 0) {
9099 Compound->setLastStmt(LastExpr.take());
9101 LastLabelStmt->setSubStmt(LastExpr.take());
9102 StmtExprMayBindToTemp = true;
9108 // FIXME: Check that expression type is complete/non-abstract; statement
9109 // expressions are not lvalues.
9110 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9111 if (StmtExprMayBindToTemp)
9112 return MaybeBindToTemporary(ResStmtExpr);
9113 return Owned(ResStmtExpr);
9116 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9117 TypeSourceInfo *TInfo,
9118 OffsetOfComponent *CompPtr,
9119 unsigned NumComponents,
9120 SourceLocation RParenLoc) {
9121 QualType ArgTy = TInfo->getType();
9122 bool Dependent = ArgTy->isDependentType();
9123 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9125 // We must have at least one component that refers to the type, and the first
9126 // one is known to be a field designator. Verify that the ArgTy represents
9127 // a struct/union/class.
9128 if (!Dependent && !ArgTy->isRecordType())
9129 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9130 << ArgTy << TypeRange);
9132 // Type must be complete per C99 7.17p3 because a declaring a variable
9133 // with an incomplete type would be ill-formed.
9135 && RequireCompleteType(BuiltinLoc, ArgTy,
9136 diag::err_offsetof_incomplete_type, TypeRange))
9139 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9140 // GCC extension, diagnose them.
9141 // FIXME: This diagnostic isn't actually visible because the location is in
9143 if (NumComponents != 1)
9144 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9145 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9147 bool DidWarnAboutNonPOD = false;
9148 QualType CurrentType = ArgTy;
9149 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9150 SmallVector<OffsetOfNode, 4> Comps;
9151 SmallVector<Expr*, 4> Exprs;
9152 for (unsigned i = 0; i != NumComponents; ++i) {
9153 const OffsetOfComponent &OC = CompPtr[i];
9154 if (OC.isBrackets) {
9155 // Offset of an array sub-field. TODO: Should we allow vector elements?
9156 if (!CurrentType->isDependentType()) {
9157 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9159 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9161 CurrentType = AT->getElementType();
9163 CurrentType = Context.DependentTy;
9165 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9166 if (IdxRval.isInvalid())
9168 Expr *Idx = IdxRval.take();
9170 // The expression must be an integral expression.
9171 // FIXME: An integral constant expression?
9172 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9173 !Idx->getType()->isIntegerType())
9174 return ExprError(Diag(Idx->getLocStart(),
9175 diag::err_typecheck_subscript_not_integer)
9176 << Idx->getSourceRange());
9178 // Record this array index.
9179 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9180 Exprs.push_back(Idx);
9184 // Offset of a field.
9185 if (CurrentType->isDependentType()) {
9186 // We have the offset of a field, but we can't look into the dependent
9187 // type. Just record the identifier of the field.
9188 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9189 CurrentType = Context.DependentTy;
9193 // We need to have a complete type to look into.
9194 if (RequireCompleteType(OC.LocStart, CurrentType,
9195 diag::err_offsetof_incomplete_type))
9198 // Look for the designated field.
9199 const RecordType *RC = CurrentType->getAs<RecordType>();
9201 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9203 RecordDecl *RD = RC->getDecl();
9205 // C++ [lib.support.types]p5:
9206 // The macro offsetof accepts a restricted set of type arguments in this
9207 // International Standard. type shall be a POD structure or a POD union
9209 // C++11 [support.types]p4:
9210 // If type is not a standard-layout class (Clause 9), the results are
9212 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9213 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9215 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9216 : diag::warn_offsetof_non_pod_type;
9218 if (!IsSafe && !DidWarnAboutNonPOD &&
9219 DiagRuntimeBehavior(BuiltinLoc, 0,
9221 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9223 DidWarnAboutNonPOD = true;
9226 // Look for the field.
9227 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9228 LookupQualifiedName(R, RD);
9229 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9230 IndirectFieldDecl *IndirectMemberDecl = 0;
9232 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9233 MemberDecl = IndirectMemberDecl->getAnonField();
9237 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9238 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9242 // (If the specified member is a bit-field, the behavior is undefined.)
9244 // We diagnose this as an error.
9245 if (MemberDecl->isBitField()) {
9246 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9247 << MemberDecl->getDeclName()
9248 << SourceRange(BuiltinLoc, RParenLoc);
9249 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9253 RecordDecl *Parent = MemberDecl->getParent();
9254 if (IndirectMemberDecl)
9255 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9257 // If the member was found in a base class, introduce OffsetOfNodes for
9258 // the base class indirections.
9259 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9260 /*DetectVirtual=*/false);
9261 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9262 CXXBasePath &Path = Paths.front();
9263 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9265 Comps.push_back(OffsetOfNode(B->Base));
9268 if (IndirectMemberDecl) {
9269 for (IndirectFieldDecl::chain_iterator FI =
9270 IndirectMemberDecl->chain_begin(),
9271 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9272 assert(isa<FieldDecl>(*FI));
9273 Comps.push_back(OffsetOfNode(OC.LocStart,
9274 cast<FieldDecl>(*FI), OC.LocEnd));
9277 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9279 CurrentType = MemberDecl->getType().getNonReferenceType();
9282 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9283 TInfo, Comps, Exprs, RParenLoc));
9286 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9287 SourceLocation BuiltinLoc,
9288 SourceLocation TypeLoc,
9289 ParsedType ParsedArgTy,
9290 OffsetOfComponent *CompPtr,
9291 unsigned NumComponents,
9292 SourceLocation RParenLoc) {
9294 TypeSourceInfo *ArgTInfo;
9295 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9300 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9302 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9307 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9309 Expr *LHSExpr, Expr *RHSExpr,
9310 SourceLocation RPLoc) {
9311 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9313 ExprValueKind VK = VK_RValue;
9314 ExprObjectKind OK = OK_Ordinary;
9316 bool ValueDependent = false;
9317 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9318 resType = Context.DependentTy;
9319 ValueDependent = true;
9321 // The conditional expression is required to be a constant expression.
9322 llvm::APSInt condEval(32);
9324 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9325 diag::err_typecheck_choose_expr_requires_constant, false);
9326 if (CondICE.isInvalid())
9328 CondExpr = CondICE.take();
9330 // If the condition is > zero, then the AST type is the same as the LSHExpr.
9331 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9333 resType = ActiveExpr->getType();
9334 ValueDependent = ActiveExpr->isValueDependent();
9335 VK = ActiveExpr->getValueKind();
9336 OK = ActiveExpr->getObjectKind();
9339 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9340 resType, VK, OK, RPLoc,
9341 resType->isDependentType(),
9345 //===----------------------------------------------------------------------===//
9346 // Clang Extensions.
9347 //===----------------------------------------------------------------------===//
9349 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9350 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9351 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9352 PushBlockScope(CurScope, Block);
9353 CurContext->addDecl(Block);
9355 PushDeclContext(CurScope, Block);
9359 getCurBlock()->HasImplicitReturnType = true;
9361 // Enter a new evaluation context to insulate the block from any
9362 // cleanups from the enclosing full-expression.
9363 PushExpressionEvaluationContext(PotentiallyEvaluated);
9366 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9368 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9369 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9370 BlockScopeInfo *CurBlock = getCurBlock();
9372 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9373 QualType T = Sig->getType();
9375 // FIXME: We should allow unexpanded parameter packs here, but that would,
9376 // in turn, make the block expression contain unexpanded parameter packs.
9377 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9378 // Drop the parameters.
9379 FunctionProtoType::ExtProtoInfo EPI;
9380 EPI.HasTrailingReturn = false;
9381 EPI.TypeQuals |= DeclSpec::TQ_const;
9382 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9384 Sig = Context.getTrivialTypeSourceInfo(T);
9387 // GetTypeForDeclarator always produces a function type for a block
9388 // literal signature. Furthermore, it is always a FunctionProtoType
9389 // unless the function was written with a typedef.
9390 assert(T->isFunctionType() &&
9391 "GetTypeForDeclarator made a non-function block signature");
9393 // Look for an explicit signature in that function type.
9394 FunctionProtoTypeLoc ExplicitSignature;
9396 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9397 if (isa<FunctionProtoTypeLoc>(tmp)) {
9398 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9400 // Check whether that explicit signature was synthesized by
9401 // GetTypeForDeclarator. If so, don't save that as part of the
9402 // written signature.
9403 if (ExplicitSignature.getLocalRangeBegin() ==
9404 ExplicitSignature.getLocalRangeEnd()) {
9405 // This would be much cheaper if we stored TypeLocs instead of
9407 TypeLoc Result = ExplicitSignature.getResultLoc();
9408 unsigned Size = Result.getFullDataSize();
9409 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9410 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9412 ExplicitSignature = FunctionProtoTypeLoc();
9416 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9417 CurBlock->FunctionType = T;
9419 const FunctionType *Fn = T->getAs<FunctionType>();
9420 QualType RetTy = Fn->getResultType();
9422 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9424 CurBlock->TheDecl->setIsVariadic(isVariadic);
9426 // Don't allow returning a objc interface by value.
9427 if (RetTy->isObjCObjectType()) {
9428 Diag(ParamInfo.getLocStart(),
9429 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9433 // Context.DependentTy is used as a placeholder for a missing block
9434 // return type. TODO: what should we do with declarators like:
9436 // If the answer is "apply template argument deduction"....
9437 if (RetTy != Context.DependentTy) {
9438 CurBlock->ReturnType = RetTy;
9439 CurBlock->TheDecl->setBlockMissingReturnType(false);
9440 CurBlock->HasImplicitReturnType = false;
9443 // Push block parameters from the declarator if we had them.
9444 SmallVector<ParmVarDecl*, 8> Params;
9445 if (ExplicitSignature) {
9446 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9447 ParmVarDecl *Param = ExplicitSignature.getArg(I);
9448 if (Param->getIdentifier() == 0 &&
9449 !Param->isImplicit() &&
9450 !Param->isInvalidDecl() &&
9451 !getLangOpts().CPlusPlus)
9452 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9453 Params.push_back(Param);
9456 // Fake up parameter variables if we have a typedef, like
9458 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9459 for (FunctionProtoType::arg_type_iterator
9460 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9461 ParmVarDecl *Param =
9462 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9463 ParamInfo.getLocStart(),
9465 Params.push_back(Param);
9469 // Set the parameters on the block decl.
9470 if (!Params.empty()) {
9471 CurBlock->TheDecl->setParams(Params);
9472 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9473 CurBlock->TheDecl->param_end(),
9474 /*CheckParameterNames=*/false);
9477 // Finally we can process decl attributes.
9478 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9480 // Put the parameter variables in scope. We can bail out immediately
9481 // if we don't have any.
9485 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9486 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9487 (*AI)->setOwningFunction(CurBlock->TheDecl);
9489 // If this has an identifier, add it to the scope stack.
9490 if ((*AI)->getIdentifier()) {
9491 CheckShadow(CurBlock->TheScope, *AI);
9493 PushOnScopeChains(*AI, CurBlock->TheScope);
9498 /// ActOnBlockError - If there is an error parsing a block, this callback
9499 /// is invoked to pop the information about the block from the action impl.
9500 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9501 // Leave the expression-evaluation context.
9502 DiscardCleanupsInEvaluationContext();
9503 PopExpressionEvaluationContext();
9505 // Pop off CurBlock, handle nested blocks.
9507 PopFunctionScopeInfo();
9510 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9511 /// literal was successfully completed. ^(int x){...}
9512 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9513 Stmt *Body, Scope *CurScope) {
9514 // If blocks are disabled, emit an error.
9515 if (!LangOpts.Blocks)
9516 Diag(CaretLoc, diag::err_blocks_disable);
9518 // Leave the expression-evaluation context.
9519 if (hasAnyUnrecoverableErrorsInThisFunction())
9520 DiscardCleanupsInEvaluationContext();
9521 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9522 PopExpressionEvaluationContext();
9524 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9526 if (BSI->HasImplicitReturnType)
9527 deduceClosureReturnType(*BSI);
9531 QualType RetTy = Context.VoidTy;
9532 if (!BSI->ReturnType.isNull())
9533 RetTy = BSI->ReturnType;
9535 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9538 // Set the captured variables on the block.
9539 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9540 SmallVector<BlockDecl::Capture, 4> Captures;
9541 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9542 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9543 if (Cap.isThisCapture())
9545 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9546 Cap.isNested(), Cap.getCopyExpr());
9547 Captures.push_back(NewCap);
9549 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9550 BSI->CXXThisCaptureIndex != 0);
9552 // If the user wrote a function type in some form, try to use that.
9553 if (!BSI->FunctionType.isNull()) {
9554 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9556 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9557 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9559 // Turn protoless block types into nullary block types.
9560 if (isa<FunctionNoProtoType>(FTy)) {
9561 FunctionProtoType::ExtProtoInfo EPI;
9563 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9565 // Otherwise, if we don't need to change anything about the function type,
9566 // preserve its sugar structure.
9567 } else if (FTy->getResultType() == RetTy &&
9568 (!NoReturn || FTy->getNoReturnAttr())) {
9569 BlockTy = BSI->FunctionType;
9571 // Otherwise, make the minimal modifications to the function type.
9573 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9574 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9575 EPI.TypeQuals = 0; // FIXME: silently?
9577 BlockTy = Context.getFunctionType(RetTy,
9578 FPT->arg_type_begin(),
9583 // If we don't have a function type, just build one from nothing.
9585 FunctionProtoType::ExtProtoInfo EPI;
9586 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9587 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9590 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9591 BSI->TheDecl->param_end());
9592 BlockTy = Context.getBlockPointerType(BlockTy);
9594 // If needed, diagnose invalid gotos and switches in the block.
9595 if (getCurFunction()->NeedsScopeChecking() &&
9596 !hasAnyUnrecoverableErrorsInThisFunction() &&
9597 !PP.isCodeCompletionEnabled())
9598 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9600 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9602 // Try to apply the named return value optimization. We have to check again
9603 // if we can do this, though, because blocks keep return statements around
9604 // to deduce an implicit return type.
9605 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9606 !BSI->TheDecl->isDependentContext())
9607 computeNRVO(Body, getCurBlock());
9609 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9610 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9611 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9613 // If the block isn't obviously global, i.e. it captures anything at
9614 // all, then we need to do a few things in the surrounding context:
9615 if (Result->getBlockDecl()->hasCaptures()) {
9616 // First, this expression has a new cleanup object.
9617 ExprCleanupObjects.push_back(Result->getBlockDecl());
9618 ExprNeedsCleanups = true;
9620 // It also gets a branch-protected scope if any of the captured
9621 // variables needs destruction.
9622 for (BlockDecl::capture_const_iterator
9623 ci = Result->getBlockDecl()->capture_begin(),
9624 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9625 const VarDecl *var = ci->getVariable();
9626 if (var->getType().isDestructedType() != QualType::DK_none) {
9627 getCurFunction()->setHasBranchProtectedScope();
9633 return Owned(Result);
9636 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9637 Expr *E, ParsedType Ty,
9638 SourceLocation RPLoc) {
9639 TypeSourceInfo *TInfo;
9640 GetTypeFromParser(Ty, &TInfo);
9641 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9644 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9645 Expr *E, TypeSourceInfo *TInfo,
9646 SourceLocation RPLoc) {
9649 // Get the va_list type
9650 QualType VaListType = Context.getBuiltinVaListType();
9651 if (VaListType->isArrayType()) {
9652 // Deal with implicit array decay; for example, on x86-64,
9653 // va_list is an array, but it's supposed to decay to
9654 // a pointer for va_arg.
9655 VaListType = Context.getArrayDecayedType(VaListType);
9656 // Make sure the input expression also decays appropriately.
9657 ExprResult Result = UsualUnaryConversions(E);
9658 if (Result.isInvalid())
9661 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9662 // If va_list is a record type and we are compiling in C++ mode,
9663 // check the argument using reference binding.
9664 InitializedEntity Entity
9665 = InitializedEntity::InitializeParameter(Context,
9666 Context.getLValueReferenceType(VaListType), false);
9667 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9668 if (Init.isInvalid())
9670 E = Init.takeAs<Expr>();
9672 // Otherwise, the va_list argument must be an l-value because
9673 // it is modified by va_arg.
9674 if (!E->isTypeDependent() &&
9675 CheckForModifiableLvalue(E, BuiltinLoc, *this))
9679 if (!E->isTypeDependent() &&
9680 !Context.hasSameType(VaListType, E->getType())) {
9681 return ExprError(Diag(E->getLocStart(),
9682 diag::err_first_argument_to_va_arg_not_of_type_va_list)
9683 << OrigExpr->getType() << E->getSourceRange());
9686 if (!TInfo->getType()->isDependentType()) {
9687 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9688 diag::err_second_parameter_to_va_arg_incomplete,
9689 TInfo->getTypeLoc()))
9692 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9694 diag::err_second_parameter_to_va_arg_abstract,
9695 TInfo->getTypeLoc()))
9698 if (!TInfo->getType().isPODType(Context)) {
9699 Diag(TInfo->getTypeLoc().getBeginLoc(),
9700 TInfo->getType()->isObjCLifetimeType()
9701 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9702 : diag::warn_second_parameter_to_va_arg_not_pod)
9704 << TInfo->getTypeLoc().getSourceRange();
9707 // Check for va_arg where arguments of the given type will be promoted
9708 // (i.e. this va_arg is guaranteed to have undefined behavior).
9709 QualType PromoteType;
9710 if (TInfo->getType()->isPromotableIntegerType()) {
9711 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9712 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9713 PromoteType = QualType();
9715 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9716 PromoteType = Context.DoubleTy;
9717 if (!PromoteType.isNull())
9718 Diag(TInfo->getTypeLoc().getBeginLoc(),
9719 diag::warn_second_parameter_to_va_arg_never_compatible)
9722 << TInfo->getTypeLoc().getSourceRange();
9725 QualType T = TInfo->getType().getNonLValueExprType(Context);
9726 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9729 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9730 // The type of __null will be int or long, depending on the size of
9731 // pointers on the target.
9733 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9734 if (pw == Context.getTargetInfo().getIntWidth())
9736 else if (pw == Context.getTargetInfo().getLongWidth())
9737 Ty = Context.LongTy;
9738 else if (pw == Context.getTargetInfo().getLongLongWidth())
9739 Ty = Context.LongLongTy;
9741 llvm_unreachable("I don't know size of pointer!");
9744 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9747 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9748 Expr *SrcExpr, FixItHint &Hint) {
9749 if (!SemaRef.getLangOpts().ObjC1)
9752 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9756 // Check if the destination is of type 'id'.
9757 if (!PT->isObjCIdType()) {
9758 // Check if the destination is the 'NSString' interface.
9759 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9760 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9764 // Ignore any parens, implicit casts (should only be
9765 // array-to-pointer decays), and not-so-opaque values. The last is
9766 // important for making this trigger for property assignments.
9767 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9768 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9769 if (OV->getSourceExpr())
9770 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9772 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9773 if (!SL || !SL->isAscii())
9776 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9779 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9781 QualType DstType, QualType SrcType,
9782 Expr *SrcExpr, AssignmentAction Action,
9785 *Complained = false;
9787 // Decode the result (notice that AST's are still created for extensions).
9788 bool CheckInferredResultType = false;
9789 bool isInvalid = false;
9790 unsigned DiagKind = 0;
9792 ConversionFixItGenerator ConvHints;
9793 bool MayHaveConvFixit = false;
9794 bool MayHaveFunctionDiff = false;
9798 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9802 DiagKind = diag::ext_typecheck_convert_pointer_int;
9803 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9804 MayHaveConvFixit = true;
9807 DiagKind = diag::ext_typecheck_convert_int_pointer;
9808 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9809 MayHaveConvFixit = true;
9811 case IncompatiblePointer:
9812 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9813 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9814 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9815 SrcType->isObjCObjectPointerType();
9816 if (Hint.isNull() && !CheckInferredResultType) {
9817 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9819 MayHaveConvFixit = true;
9821 case IncompatiblePointerSign:
9822 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9824 case FunctionVoidPointer:
9825 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9827 case IncompatiblePointerDiscardsQualifiers: {
9828 // Perform array-to-pointer decay if necessary.
9829 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9831 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9832 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9833 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9834 DiagKind = diag::err_typecheck_incompatible_address_space;
9838 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9839 DiagKind = diag::err_typecheck_incompatible_ownership;
9843 llvm_unreachable("unknown error case for discarding qualifiers!");
9846 case CompatiblePointerDiscardsQualifiers:
9847 // If the qualifiers lost were because we were applying the
9848 // (deprecated) C++ conversion from a string literal to a char*
9849 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9850 // Ideally, this check would be performed in
9851 // checkPointerTypesForAssignment. However, that would require a
9852 // bit of refactoring (so that the second argument is an
9853 // expression, rather than a type), which should be done as part
9854 // of a larger effort to fix checkPointerTypesForAssignment for
9856 if (getLangOpts().CPlusPlus &&
9857 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9859 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9861 case IncompatibleNestedPointerQualifiers:
9862 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9864 case IntToBlockPointer:
9865 DiagKind = diag::err_int_to_block_pointer;
9867 case IncompatibleBlockPointer:
9868 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9870 case IncompatibleObjCQualifiedId:
9871 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9872 // it can give a more specific diagnostic.
9873 DiagKind = diag::warn_incompatible_qualified_id;
9875 case IncompatibleVectors:
9876 DiagKind = diag::warn_incompatible_vectors;
9878 case IncompatibleObjCWeakRef:
9879 DiagKind = diag::err_arc_weak_unavailable_assign;
9882 DiagKind = diag::err_typecheck_convert_incompatible;
9883 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9884 MayHaveConvFixit = true;
9886 MayHaveFunctionDiff = true;
9890 QualType FirstType, SecondType;
9893 case AA_Initializing:
9894 // The destination type comes first.
9895 FirstType = DstType;
9896 SecondType = SrcType;
9904 // The source type comes first.
9905 FirstType = SrcType;
9906 SecondType = DstType;
9910 PartialDiagnostic FDiag = PDiag(DiagKind);
9911 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9913 // If we can fix the conversion, suggest the FixIts.
9914 assert(ConvHints.isNull() || Hint.isNull());
9915 if (!ConvHints.isNull()) {
9916 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9917 HE = ConvHints.Hints.end(); HI != HE; ++HI)
9922 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9924 if (MayHaveFunctionDiff)
9925 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9929 if (SecondType == Context.OverloadTy)
9930 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9933 if (CheckInferredResultType)
9934 EmitRelatedResultTypeNote(SrcExpr);
9941 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9942 llvm::APSInt *Result) {
9943 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9945 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9946 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9950 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9953 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9954 llvm::APSInt *Result,
9957 class IDDiagnoser : public VerifyICEDiagnoser {
9961 IDDiagnoser(unsigned DiagID)
9962 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9964 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9965 S.Diag(Loc, DiagID) << SR;
9967 } Diagnoser(DiagID);
9969 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9972 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9974 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
9978 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9979 VerifyICEDiagnoser &Diagnoser,
9981 SourceLocation DiagLoc = E->getLocStart();
9983 if (getLangOpts().CPlusPlus0x) {
9984 // C++11 [expr.const]p5:
9985 // If an expression of literal class type is used in a context where an
9986 // integral constant expression is required, then that class type shall
9987 // have a single non-explicit conversion function to an integral or
9988 // unscoped enumeration type
9989 ExprResult Converted;
9990 if (!Diagnoser.Suppress) {
9991 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9993 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9995 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9997 return S.Diag(Loc, diag::err_ice_not_integral) << T;
10000 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10001 SourceLocation Loc,
10003 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10006 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10007 SourceLocation Loc,
10010 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10013 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10014 CXXConversionDecl *Conv,
10016 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10017 << ConvTy->isEnumeralType() << ConvTy;
10020 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10022 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10025 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10026 CXXConversionDecl *Conv,
10028 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10029 << ConvTy->isEnumeralType() << ConvTy;
10032 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10033 SourceLocation Loc,
10036 return DiagnosticBuilder::getEmpty();
10038 } ConvertDiagnoser;
10040 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10042 /*AllowScopedEnumerations*/ false);
10044 // The caller wants to silently enquire whether this is an ICE. Don't
10045 // produce any diagnostics if it isn't.
10046 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10048 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10050 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10052 return DiagnosticBuilder::getEmpty();
10055 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10056 SourceLocation Loc,
10058 return DiagnosticBuilder::getEmpty();
10061 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10062 SourceLocation Loc,
10065 return DiagnosticBuilder::getEmpty();
10068 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10069 CXXConversionDecl *Conv,
10071 return DiagnosticBuilder::getEmpty();
10074 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10076 return DiagnosticBuilder::getEmpty();
10079 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10080 CXXConversionDecl *Conv,
10082 return DiagnosticBuilder::getEmpty();
10085 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10086 SourceLocation Loc,
10089 return DiagnosticBuilder::getEmpty();
10091 } ConvertDiagnoser;
10093 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10094 ConvertDiagnoser, false);
10096 if (Converted.isInvalid())
10098 E = Converted.take();
10099 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10100 return ExprError();
10101 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10102 // An ICE must be of integral or unscoped enumeration type.
10103 if (!Diagnoser.Suppress)
10104 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10105 return ExprError();
10108 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10109 // in the non-ICE case.
10110 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
10112 *Result = E->EvaluateKnownConstInt(Context);
10116 Expr::EvalResult EvalResult;
10117 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10118 EvalResult.Diag = &Notes;
10120 // Try to evaluate the expression, and produce diagnostics explaining why it's
10121 // not a constant expression as a side-effect.
10122 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10123 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10125 // In C++11, we can rely on diagnostics being produced for any expression
10126 // which is not a constant expression. If no diagnostics were produced, then
10127 // this is a constant expression.
10128 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
10130 *Result = EvalResult.Val.getInt();
10134 // If our only note is the usual "invalid subexpression" note, just point
10135 // the caret at its location rather than producing an essentially
10137 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10138 diag::note_invalid_subexpr_in_const_expr) {
10139 DiagLoc = Notes[0].first;
10143 if (!Folded || !AllowFold) {
10144 if (!Diagnoser.Suppress) {
10145 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10146 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10147 Diag(Notes[I].first, Notes[I].second);
10150 return ExprError();
10153 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10154 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10155 Diag(Notes[I].first, Notes[I].second);
10158 *Result = EvalResult.Val.getInt();
10163 // Handle the case where we conclude a expression which we speculatively
10164 // considered to be unevaluated is actually evaluated.
10165 class TransformToPE : public TreeTransform<TransformToPE> {
10166 typedef TreeTransform<TransformToPE> BaseTransform;
10169 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10171 // Make sure we redo semantic analysis
10172 bool AlwaysRebuild() { return true; }
10174 // Make sure we handle LabelStmts correctly.
10175 // FIXME: This does the right thing, but maybe we need a more general
10176 // fix to TreeTransform?
10177 StmtResult TransformLabelStmt(LabelStmt *S) {
10178 S->getDecl()->setStmt(0);
10179 return BaseTransform::TransformLabelStmt(S);
10182 // We need to special-case DeclRefExprs referring to FieldDecls which
10183 // are not part of a member pointer formation; normal TreeTransforming
10184 // doesn't catch this case because of the way we represent them in the AST.
10185 // FIXME: This is a bit ugly; is it really the best way to handle this
10188 // Error on DeclRefExprs referring to FieldDecls.
10189 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10190 if (isa<FieldDecl>(E->getDecl()) &&
10191 !SemaRef.isUnevaluatedContext())
10192 return SemaRef.Diag(E->getLocation(),
10193 diag::err_invalid_non_static_member_use)
10194 << E->getDecl() << E->getSourceRange();
10196 return BaseTransform::TransformDeclRefExpr(E);
10199 // Exception: filter out member pointer formation
10200 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10201 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10204 return BaseTransform::TransformUnaryOperator(E);
10207 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10208 // Lambdas never need to be transformed.
10214 ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
10215 assert(ExprEvalContexts.back().Context == Unevaluated &&
10216 "Should only transform unevaluated expressions");
10217 ExprEvalContexts.back().Context =
10218 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10219 if (ExprEvalContexts.back().Context == Unevaluated)
10221 return TransformToPE(*this).TransformExpr(E);
10225 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10226 Decl *LambdaContextDecl,
10228 ExprEvalContexts.push_back(
10229 ExpressionEvaluationContextRecord(NewContext,
10230 ExprCleanupObjects.size(),
10234 ExprNeedsCleanups = false;
10235 if (!MaybeODRUseExprs.empty())
10236 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10240 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10241 ReuseLambdaContextDecl_t,
10243 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10244 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10247 void Sema::PopExpressionEvaluationContext() {
10248 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10250 if (!Rec.Lambdas.empty()) {
10251 if (Rec.Context == Unevaluated) {
10252 // C++11 [expr.prim.lambda]p2:
10253 // A lambda-expression shall not appear in an unevaluated operand
10255 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10256 Diag(Rec.Lambdas[I]->getLocStart(),
10257 diag::err_lambda_unevaluated_operand);
10259 // Mark the capture expressions odr-used. This was deferred
10260 // during lambda expression creation.
10261 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10262 LambdaExpr *Lambda = Rec.Lambdas[I];
10263 for (LambdaExpr::capture_init_iterator
10264 C = Lambda->capture_init_begin(),
10265 CEnd = Lambda->capture_init_end();
10267 MarkDeclarationsReferencedInExpr(*C);
10273 // When are coming out of an unevaluated context, clear out any
10274 // temporaries that we may have created as part of the evaluation of
10275 // the expression in that context: they aren't relevant because they
10276 // will never be constructed.
10277 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10278 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10279 ExprCleanupObjects.end());
10280 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10281 CleanupVarDeclMarking();
10282 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10283 // Otherwise, merge the contexts together.
10285 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10286 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10287 Rec.SavedMaybeODRUseExprs.end());
10290 // Pop the current expression evaluation context off the stack.
10291 ExprEvalContexts.pop_back();
10294 void Sema::DiscardCleanupsInEvaluationContext() {
10295 ExprCleanupObjects.erase(
10296 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10297 ExprCleanupObjects.end());
10298 ExprNeedsCleanups = false;
10299 MaybeODRUseExprs.clear();
10302 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10303 if (!E->getType()->isVariablyModifiedType())
10305 return TranformToPotentiallyEvaluated(E);
10308 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10309 // Do not mark anything as "used" within a dependent context; wait for
10310 // an instantiation.
10311 if (SemaRef.CurContext->isDependentContext())
10314 switch (SemaRef.ExprEvalContexts.back().Context) {
10315 case Sema::Unevaluated:
10316 // We are in an expression that is not potentially evaluated; do nothing.
10317 // (Depending on how you read the standard, we actually do need to do
10318 // something here for null pointer constants, but the standard's
10319 // definition of a null pointer constant is completely crazy.)
10322 case Sema::ConstantEvaluated:
10323 case Sema::PotentiallyEvaluated:
10324 // We are in a potentially evaluated expression (or a constant-expression
10325 // in C++03); we need to do implicit template instantiation, implicitly
10326 // define class members, and mark most declarations as used.
10329 case Sema::PotentiallyEvaluatedIfUsed:
10330 // Referenced declarations will only be used if the construct in the
10331 // containing expression is used.
10334 llvm_unreachable("Invalid context");
10337 /// \brief Mark a function referenced, and check whether it is odr-used
10338 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10339 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10340 assert(Func && "No function?");
10342 Func->setReferenced();
10344 // C++11 [basic.def.odr]p3:
10345 // A function whose name appears as a potentially-evaluated expression is
10346 // odr-used if it is the unique lookup result or the selected member of a
10347 // set of overloaded functions [...].
10349 // We (incorrectly) mark overload resolution as an unevaluated context, so we
10350 // can just check that here. Skip the rest of this function if we've already
10351 // marked the function as used.
10352 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10353 // C++11 [temp.inst]p3:
10354 // Unless a function template specialization has been explicitly
10355 // instantiated or explicitly specialized, the function template
10356 // specialization is implicitly instantiated when the specialization is
10357 // referenced in a context that requires a function definition to exist.
10359 // We consider constexpr function templates to be referenced in a context
10360 // that requires a definition to exist whenever they are referenced.
10362 // FIXME: This instantiates constexpr functions too frequently. If this is
10363 // really an unevaluated context (and we're not just in the definition of a
10364 // function template or overload resolution or other cases which we
10365 // incorrectly consider to be unevaluated contexts), and we're not in a
10366 // subexpression which we actually need to evaluate (for instance, a
10367 // template argument, array bound or an expression in a braced-init-list),
10368 // we are not permitted to instantiate this constexpr function definition.
10370 // FIXME: This also implicitly defines special members too frequently. They
10371 // are only supposed to be implicitly defined if they are odr-used, but they
10372 // are not odr-used from constant expressions in unevaluated contexts.
10373 // However, they cannot be referenced if they are deleted, and they are
10374 // deleted whenever the implicit definition of the special member would
10376 if (!Func->isConstexpr() || Func->getBody())
10378 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10379 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10383 // Note that this declaration has been used.
10384 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10385 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10386 if (Constructor->isDefaultConstructor()) {
10387 if (Constructor->isTrivial())
10389 if (!Constructor->isUsed(false))
10390 DefineImplicitDefaultConstructor(Loc, Constructor);
10391 } else if (Constructor->isCopyConstructor()) {
10392 if (!Constructor->isUsed(false))
10393 DefineImplicitCopyConstructor(Loc, Constructor);
10394 } else if (Constructor->isMoveConstructor()) {
10395 if (!Constructor->isUsed(false))
10396 DefineImplicitMoveConstructor(Loc, Constructor);
10400 MarkVTableUsed(Loc, Constructor->getParent());
10401 } else if (CXXDestructorDecl *Destructor =
10402 dyn_cast<CXXDestructorDecl>(Func)) {
10403 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10404 !Destructor->isUsed(false))
10405 DefineImplicitDestructor(Loc, Destructor);
10406 if (Destructor->isVirtual())
10407 MarkVTableUsed(Loc, Destructor->getParent());
10408 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10409 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10410 MethodDecl->isOverloadedOperator() &&
10411 MethodDecl->getOverloadedOperator() == OO_Equal) {
10412 if (!MethodDecl->isUsed(false)) {
10413 if (MethodDecl->isCopyAssignmentOperator())
10414 DefineImplicitCopyAssignment(Loc, MethodDecl);
10416 DefineImplicitMoveAssignment(Loc, MethodDecl);
10418 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10419 MethodDecl->getParent()->isLambda()) {
10420 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10421 if (Conversion->isLambdaToBlockPointerConversion())
10422 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10424 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10425 } else if (MethodDecl->isVirtual())
10426 MarkVTableUsed(Loc, MethodDecl->getParent());
10429 // Recursive functions should be marked when used from another function.
10430 // FIXME: Is this really right?
10431 if (CurContext == Func) return;
10433 // Resolve the exception specification for any function which is
10434 // used: CodeGen will need it.
10435 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10436 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10437 ResolveExceptionSpec(Loc, FPT);
10439 // Implicit instantiation of function templates and member functions of
10440 // class templates.
10441 if (Func->isImplicitlyInstantiable()) {
10442 bool AlreadyInstantiated = false;
10443 SourceLocation PointOfInstantiation = Loc;
10444 if (FunctionTemplateSpecializationInfo *SpecInfo
10445 = Func->getTemplateSpecializationInfo()) {
10446 if (SpecInfo->getPointOfInstantiation().isInvalid())
10447 SpecInfo->setPointOfInstantiation(Loc);
10448 else if (SpecInfo->getTemplateSpecializationKind()
10449 == TSK_ImplicitInstantiation) {
10450 AlreadyInstantiated = true;
10451 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10453 } else if (MemberSpecializationInfo *MSInfo
10454 = Func->getMemberSpecializationInfo()) {
10455 if (MSInfo->getPointOfInstantiation().isInvalid())
10456 MSInfo->setPointOfInstantiation(Loc);
10457 else if (MSInfo->getTemplateSpecializationKind()
10458 == TSK_ImplicitInstantiation) {
10459 AlreadyInstantiated = true;
10460 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10464 if (!AlreadyInstantiated || Func->isConstexpr()) {
10465 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10466 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10467 PendingLocalImplicitInstantiations.push_back(
10468 std::make_pair(Func, PointOfInstantiation));
10469 else if (Func->isConstexpr())
10470 // Do not defer instantiations of constexpr functions, to avoid the
10471 // expression evaluator needing to call back into Sema if it sees a
10472 // call to such a function.
10473 InstantiateFunctionDefinition(PointOfInstantiation, Func);
10475 PendingInstantiations.push_back(std::make_pair(Func,
10476 PointOfInstantiation));
10477 // Notify the consumer that a function was implicitly instantiated.
10478 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10482 // Walk redefinitions, as some of them may be instantiable.
10483 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10484 e(Func->redecls_end()); i != e; ++i) {
10485 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10486 MarkFunctionReferenced(Loc, *i);
10490 // Keep track of used but undefined functions.
10491 if (!Func->isPure() && !Func->hasBody() &&
10492 Func->getLinkage() != ExternalLinkage) {
10493 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10494 if (old.isInvalid()) old = Loc;
10497 Func->setUsed(true);
10501 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10502 VarDecl *var, DeclContext *DC) {
10503 DeclContext *VarDC = var->getDeclContext();
10505 // If the parameter still belongs to the translation unit, then
10506 // we're actually just using one parameter in the declaration of
10508 if (isa<ParmVarDecl>(var) &&
10509 isa<TranslationUnitDecl>(VarDC))
10512 // For C code, don't diagnose about capture if we're not actually in code
10513 // right now; it's impossible to write a non-constant expression outside of
10514 // function context, so we'll get other (more useful) diagnostics later.
10516 // For C++, things get a bit more nasty... it would be nice to suppress this
10517 // diagnostic for certain cases like using a local variable in an array bound
10518 // for a member of a local class, but the correct predicate is not obvious.
10519 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10522 if (isa<CXXMethodDecl>(VarDC) &&
10523 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10524 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10525 << var->getIdentifier();
10526 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10527 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10528 << var->getIdentifier() << fn->getDeclName();
10529 } else if (isa<BlockDecl>(VarDC)) {
10530 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10531 << var->getIdentifier();
10533 // FIXME: Is there any other context where a local variable can be
10535 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10536 << var->getIdentifier();
10539 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10540 << var->getIdentifier();
10542 // FIXME: Add additional diagnostic info about class etc. which prevents
10546 /// \brief Capture the given variable in the given lambda expression.
10547 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10548 VarDecl *Var, QualType FieldType,
10549 QualType DeclRefType,
10550 SourceLocation Loc,
10551 bool RefersToEnclosingLocal) {
10552 CXXRecordDecl *Lambda = LSI->Lambda;
10554 // Build the non-static data member.
10556 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10557 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10558 0, false, ICIS_NoInit);
10559 Field->setImplicit(true);
10560 Field->setAccess(AS_private);
10561 Lambda->addDecl(Field);
10563 // C++11 [expr.prim.lambda]p21:
10564 // When the lambda-expression is evaluated, the entities that
10565 // are captured by copy are used to direct-initialize each
10566 // corresponding non-static data member of the resulting closure
10567 // object. (For array members, the array elements are
10568 // direct-initialized in increasing subscript order.) These
10569 // initializations are performed in the (unspecified) order in
10570 // which the non-static data members are declared.
10572 // Introduce a new evaluation context for the initialization, so
10573 // that temporaries introduced as part of the capture are retained
10574 // to be re-"exported" from the lambda expression itself.
10575 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10577 // C++ [expr.prim.labda]p12:
10578 // An entity captured by a lambda-expression is odr-used (3.2) in
10579 // the scope containing the lambda-expression.
10580 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10581 DeclRefType, VK_LValue, Loc);
10582 Var->setReferenced(true);
10583 Var->setUsed(true);
10585 // When the field has array type, create index variables for each
10586 // dimension of the array. We use these index variables to subscript
10587 // the source array, and other clients (e.g., CodeGen) will perform
10588 // the necessary iteration with these index variables.
10589 SmallVector<VarDecl *, 4> IndexVariables;
10590 QualType BaseType = FieldType;
10591 QualType SizeType = S.Context.getSizeType();
10592 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10593 while (const ConstantArrayType *Array
10594 = S.Context.getAsConstantArrayType(BaseType)) {
10595 // Create the iteration variable for this array index.
10596 IdentifierInfo *IterationVarName = 0;
10598 SmallString<8> Str;
10599 llvm::raw_svector_ostream OS(Str);
10600 OS << "__i" << IndexVariables.size();
10601 IterationVarName = &S.Context.Idents.get(OS.str());
10603 VarDecl *IterationVar
10604 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10605 IterationVarName, SizeType,
10606 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10608 IndexVariables.push_back(IterationVar);
10609 LSI->ArrayIndexVars.push_back(IterationVar);
10611 // Create a reference to the iteration variable.
10612 ExprResult IterationVarRef
10613 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10614 assert(!IterationVarRef.isInvalid() &&
10615 "Reference to invented variable cannot fail!");
10616 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10617 assert(!IterationVarRef.isInvalid() &&
10618 "Conversion of invented variable cannot fail!");
10620 // Subscript the array with this iteration variable.
10621 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10622 Ref, Loc, IterationVarRef.take(), Loc);
10623 if (Subscript.isInvalid()) {
10624 S.CleanupVarDeclMarking();
10625 S.DiscardCleanupsInEvaluationContext();
10626 S.PopExpressionEvaluationContext();
10627 return ExprError();
10630 Ref = Subscript.take();
10631 BaseType = Array->getElementType();
10634 // Construct the entity that we will be initializing. For an array, this
10635 // will be first element in the array, which may require several levels
10636 // of array-subscript entities.
10637 SmallVector<InitializedEntity, 4> Entities;
10638 Entities.reserve(1 + IndexVariables.size());
10639 Entities.push_back(
10640 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10641 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10642 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10646 InitializationKind InitKind
10647 = InitializationKind::CreateDirect(Loc, Loc, Loc);
10648 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10649 ExprResult Result(true);
10650 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10651 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
10653 // If this initialization requires any cleanups (e.g., due to a
10654 // default argument to a copy constructor), note that for the
10656 if (S.ExprNeedsCleanups)
10657 LSI->ExprNeedsCleanups = true;
10659 // Exit the expression evaluation context used for the capture.
10660 S.CleanupVarDeclMarking();
10661 S.DiscardCleanupsInEvaluationContext();
10662 S.PopExpressionEvaluationContext();
10666 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10667 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10668 bool BuildAndDiagnose,
10669 QualType &CaptureType,
10670 QualType &DeclRefType) {
10671 bool Nested = false;
10673 DeclContext *DC = CurContext;
10674 if (Var->getDeclContext() == DC) return true;
10675 if (!Var->hasLocalStorage()) return true;
10677 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10679 // Walk up the stack to determine whether we can capture the variable,
10680 // performing the "simple" checks that don't depend on type. We stop when
10681 // we've either hit the declared scope of the variable or find an existing
10682 // capture of that variable.
10683 CaptureType = Var->getType();
10684 DeclRefType = CaptureType.getNonReferenceType();
10685 bool Explicit = (Kind != TryCapture_Implicit);
10686 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10688 // Only block literals and lambda expressions can capture; other
10689 // scopes don't work.
10690 DeclContext *ParentDC;
10691 if (isa<BlockDecl>(DC))
10692 ParentDC = DC->getParent();
10693 else if (isa<CXXMethodDecl>(DC) &&
10694 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10695 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10696 ParentDC = DC->getParent()->getParent();
10698 if (BuildAndDiagnose)
10699 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10703 CapturingScopeInfo *CSI =
10704 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10706 // Check whether we've already captured it.
10707 if (CSI->CaptureMap.count(Var)) {
10708 // If we found a capture, any subcaptures are nested.
10711 // Retrieve the capture type for this variable.
10712 CaptureType = CSI->getCapture(Var).getCaptureType();
10714 // Compute the type of an expression that refers to this variable.
10715 DeclRefType = CaptureType.getNonReferenceType();
10717 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10718 if (Cap.isCopyCapture() &&
10719 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10720 DeclRefType.addConst();
10724 bool IsBlock = isa<BlockScopeInfo>(CSI);
10725 bool IsLambda = !IsBlock;
10727 // Lambdas are not allowed to capture unnamed variables
10728 // (e.g. anonymous unions).
10729 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10730 // assuming that's the intent.
10731 if (IsLambda && !Var->getDeclName()) {
10732 if (BuildAndDiagnose) {
10733 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10734 Diag(Var->getLocation(), diag::note_declared_at);
10739 // Prohibit variably-modified types; they're difficult to deal with.
10740 if (Var->getType()->isVariablyModifiedType()) {
10741 if (BuildAndDiagnose) {
10743 Diag(Loc, diag::err_ref_vm_type);
10745 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10746 Diag(Var->getLocation(), diag::note_previous_decl)
10747 << Var->getDeclName();
10752 // Lambdas are not allowed to capture __block variables; they don't
10753 // support the expected semantics.
10754 if (IsLambda && HasBlocksAttr) {
10755 if (BuildAndDiagnose) {
10756 Diag(Loc, diag::err_lambda_capture_block)
10757 << Var->getDeclName();
10758 Diag(Var->getLocation(), diag::note_previous_decl)
10759 << Var->getDeclName();
10764 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10765 // No capture-default
10766 if (BuildAndDiagnose) {
10767 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10768 Diag(Var->getLocation(), diag::note_previous_decl)
10769 << Var->getDeclName();
10770 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10771 diag::note_lambda_decl);
10776 FunctionScopesIndex--;
10779 } while (!Var->getDeclContext()->Equals(DC));
10781 // Walk back down the scope stack, computing the type of the capture at
10782 // each step, checking type-specific requirements, and adding captures if
10784 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10786 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10788 // Compute the type of the capture and of a reference to the capture within
10790 if (isa<BlockScopeInfo>(CSI)) {
10791 Expr *CopyExpr = 0;
10792 bool ByRef = false;
10794 // Blocks are not allowed to capture arrays.
10795 if (CaptureType->isArrayType()) {
10796 if (BuildAndDiagnose) {
10797 Diag(Loc, diag::err_ref_array_type);
10798 Diag(Var->getLocation(), diag::note_previous_decl)
10799 << Var->getDeclName();
10804 // Forbid the block-capture of autoreleasing variables.
10805 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10806 if (BuildAndDiagnose) {
10807 Diag(Loc, diag::err_arc_autoreleasing_capture)
10809 Diag(Var->getLocation(), diag::note_previous_decl)
10810 << Var->getDeclName();
10815 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10816 // Block capture by reference does not change the capture or
10817 // declaration reference types.
10820 // Block capture by copy introduces 'const'.
10821 CaptureType = CaptureType.getNonReferenceType().withConst();
10822 DeclRefType = CaptureType;
10824 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10825 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10826 // The capture logic needs the destructor, so make sure we mark it.
10827 // Usually this is unnecessary because most local variables have
10828 // their destructors marked at declaration time, but parameters are
10829 // an exception because it's technically only the call site that
10830 // actually requires the destructor.
10831 if (isa<ParmVarDecl>(Var))
10832 FinalizeVarWithDestructor(Var, Record);
10834 // According to the blocks spec, the capture of a variable from
10835 // the stack requires a const copy constructor. This is not true
10836 // of the copy/move done to move a __block variable to the heap.
10837 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
10838 DeclRefType.withConst(),
10841 = PerformCopyInitialization(
10842 InitializedEntity::InitializeBlock(Var->getLocation(),
10843 CaptureType, false),
10844 Loc, Owned(DeclRef));
10846 // Build a full-expression copy expression if initialization
10847 // succeeded and used a non-trivial constructor. Recover from
10848 // errors by pretending that the copy isn't necessary.
10849 if (!Result.isInvalid() &&
10850 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10852 Result = MaybeCreateExprWithCleanups(Result);
10853 CopyExpr = Result.take();
10859 // Actually capture the variable.
10860 if (BuildAndDiagnose)
10861 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10862 SourceLocation(), CaptureType, CopyExpr);
10867 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10869 // Determine whether we are capturing by reference or by value.
10870 bool ByRef = false;
10871 if (I == N - 1 && Kind != TryCapture_Implicit) {
10872 ByRef = (Kind == TryCapture_ExplicitByRef);
10874 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
10877 // Compute the type of the field that will capture this variable.
10879 // C++11 [expr.prim.lambda]p15:
10880 // An entity is captured by reference if it is implicitly or
10881 // explicitly captured but not captured by copy. It is
10882 // unspecified whether additional unnamed non-static data
10883 // members are declared in the closure type for entities
10884 // captured by reference.
10886 // FIXME: It is not clear whether we want to build an lvalue reference
10887 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10888 // to do the former, while EDG does the latter. Core issue 1249 will
10889 // clarify, but for now we follow GCC because it's a more permissive and
10890 // easily defensible position.
10891 CaptureType = Context.getLValueReferenceType(DeclRefType);
10893 // C++11 [expr.prim.lambda]p14:
10894 // For each entity captured by copy, an unnamed non-static
10895 // data member is declared in the closure type. The
10896 // declaration order of these members is unspecified. The type
10897 // of such a data member is the type of the corresponding
10898 // captured entity if the entity is not a reference to an
10899 // object, or the referenced type otherwise. [Note: If the
10900 // captured entity is a reference to a function, the
10901 // corresponding data member is also a reference to a
10902 // function. - end note ]
10903 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10904 if (!RefType->getPointeeType()->isFunctionType())
10905 CaptureType = RefType->getPointeeType();
10908 // Forbid the lambda copy-capture of autoreleasing variables.
10909 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10910 if (BuildAndDiagnose) {
10911 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10912 Diag(Var->getLocation(), diag::note_previous_decl)
10913 << Var->getDeclName();
10919 // Capture this variable in the lambda.
10920 Expr *CopyExpr = 0;
10921 if (BuildAndDiagnose) {
10922 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10925 if (!Result.isInvalid())
10926 CopyExpr = Result.take();
10929 // Compute the type of a reference to this captured variable.
10931 DeclRefType = CaptureType.getNonReferenceType();
10933 // C++ [expr.prim.lambda]p5:
10934 // The closure type for a lambda-expression has a public inline
10935 // function call operator [...]. This function call operator is
10936 // declared const (9.3.1) if and only if the lambda-expression’s
10937 // parameter-declaration-clause is not followed by mutable.
10938 DeclRefType = CaptureType.getNonReferenceType();
10939 if (!LSI->Mutable && !CaptureType->isReferenceType())
10940 DeclRefType.addConst();
10943 // Add the capture.
10944 if (BuildAndDiagnose)
10945 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10946 EllipsisLoc, CaptureType, CopyExpr);
10953 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10954 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10955 QualType CaptureType;
10956 QualType DeclRefType;
10957 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10958 /*BuildAndDiagnose=*/true, CaptureType,
10962 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10963 QualType CaptureType;
10964 QualType DeclRefType;
10966 // Determine whether we can capture this variable.
10967 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10968 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10971 return DeclRefType;
10974 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10975 SourceLocation Loc) {
10976 // Keep track of used but undefined variables.
10977 // FIXME: We shouldn't suppress this warning for static data members.
10978 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
10979 Var->getLinkage() != ExternalLinkage &&
10980 !(Var->isStaticDataMember() && Var->hasInit())) {
10981 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10982 if (old.isInvalid()) old = Loc;
10985 SemaRef.tryCaptureVariable(Var, Loc);
10987 Var->setUsed(true);
10990 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10991 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10992 // an object that satisfies the requirements for appearing in a
10993 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10994 // is immediately applied." This function handles the lvalue-to-rvalue
10995 // conversion part.
10996 MaybeODRUseExprs.erase(E->IgnoreParens());
10999 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11000 if (!Res.isUsable())
11003 // If a constant-expression is a reference to a variable where we delay
11004 // deciding whether it is an odr-use, just assume we will apply the
11005 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
11006 // (a non-type template argument), we have special handling anyway.
11007 UpdateMarkingForLValueToRValue(Res.get());
11011 void Sema::CleanupVarDeclMarking() {
11012 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11013 e = MaybeODRUseExprs.end();
11016 SourceLocation Loc;
11017 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11018 Var = cast<VarDecl>(DRE->getDecl());
11019 Loc = DRE->getLocation();
11020 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11021 Var = cast<VarDecl>(ME->getMemberDecl());
11022 Loc = ME->getMemberLoc();
11024 llvm_unreachable("Unexpcted expression");
11027 MarkVarDeclODRUsed(*this, Var, Loc);
11030 MaybeODRUseExprs.clear();
11033 // Mark a VarDecl referenced, and perform the necessary handling to compute
11035 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11036 VarDecl *Var, Expr *E) {
11037 Var->setReferenced();
11039 if (!IsPotentiallyEvaluatedContext(SemaRef))
11042 // Implicit instantiation of static data members of class templates.
11043 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
11044 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11045 assert(MSInfo && "Missing member specialization information?");
11046 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11047 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
11048 (!AlreadyInstantiated ||
11049 Var->isUsableInConstantExpressions(SemaRef.Context))) {
11050 if (!AlreadyInstantiated) {
11051 // This is a modification of an existing AST node. Notify listeners.
11052 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11053 L->StaticDataMemberInstantiated(Var);
11054 MSInfo->setPointOfInstantiation(Loc);
11056 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
11057 if (Var->isUsableInConstantExpressions(SemaRef.Context))
11058 // Do not defer instantiations of variables which could be used in a
11059 // constant expression.
11060 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
11062 SemaRef.PendingInstantiations.push_back(
11063 std::make_pair(Var, PointOfInstantiation));
11067 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11068 // the requirements for appearing in a constant expression (5.19) and, if
11069 // it is an object, the lvalue-to-rvalue conversion (4.1)
11070 // is immediately applied." We check the first part here, and
11071 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11072 // Note that we use the C++11 definition everywhere because nothing in
11073 // C++03 depends on whether we get the C++03 version correct. The second
11074 // part does not apply to references, since they are not objects.
11075 const VarDecl *DefVD;
11076 if (E && !isa<ParmVarDecl>(Var) &&
11077 Var->isUsableInConstantExpressions(SemaRef.Context) &&
11078 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11079 if (!Var->getType()->isReferenceType())
11080 SemaRef.MaybeODRUseExprs.insert(E);
11082 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11085 /// \brief Mark a variable referenced, and check whether it is odr-used
11086 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11087 /// used directly for normal expressions referring to VarDecl.
11088 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11089 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
11092 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11093 Decl *D, Expr *E) {
11094 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11095 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11099 SemaRef.MarkAnyDeclReferenced(Loc, D);
11101 // If this is a call to a method via a cast, also mark the method in the
11102 // derived class used in case codegen can devirtualize the call.
11103 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11106 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11109 const Expr *Base = ME->getBase();
11110 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11111 if (!MostDerivedClassDecl)
11113 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11116 SemaRef.MarkAnyDeclReferenced(Loc, DM);
11119 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11120 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11121 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11124 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11125 void Sema::MarkMemberReferenced(MemberExpr *E) {
11126 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11129 /// \brief Perform marking for a reference to an arbitrary declaration. It
11130 /// marks the declaration referenced, and performs odr-use checking for functions
11131 /// and variables. This method should not be used when building an normal
11132 /// expression which refers to a variable.
11133 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11134 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11135 MarkVariableReferenced(Loc, VD);
11136 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11137 MarkFunctionReferenced(Loc, FD);
11139 D->setReferenced();
11143 // Mark all of the declarations referenced
11144 // FIXME: Not fully implemented yet! We need to have a better understanding
11145 // of when we're entering
11146 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11148 SourceLocation Loc;
11151 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11153 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11155 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11156 bool TraverseRecordType(RecordType *T);
11160 bool MarkReferencedDecls::TraverseTemplateArgument(
11161 const TemplateArgument &Arg) {
11162 if (Arg.getKind() == TemplateArgument::Declaration) {
11163 if (Decl *D = Arg.getAsDecl())
11164 S.MarkAnyDeclReferenced(Loc, D);
11167 return Inherited::TraverseTemplateArgument(Arg);
11170 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11171 if (ClassTemplateSpecializationDecl *Spec
11172 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11173 const TemplateArgumentList &Args = Spec->getTemplateArgs();
11174 return TraverseTemplateArguments(Args.data(), Args.size());
11180 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11181 MarkReferencedDecls Marker(*this, Loc);
11182 Marker.TraverseType(Context.getCanonicalType(T));
11186 /// \brief Helper class that marks all of the declarations referenced by
11187 /// potentially-evaluated subexpressions as "referenced".
11188 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11190 bool SkipLocalVariables;
11193 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11195 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11196 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11198 void VisitDeclRefExpr(DeclRefExpr *E) {
11199 // If we were asked not to visit local variables, don't.
11200 if (SkipLocalVariables) {
11201 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11202 if (VD->hasLocalStorage())
11206 S.MarkDeclRefReferenced(E);
11209 void VisitMemberExpr(MemberExpr *E) {
11210 S.MarkMemberReferenced(E);
11211 Inherited::VisitMemberExpr(E);
11214 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11215 S.MarkFunctionReferenced(E->getLocStart(),
11216 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11217 Visit(E->getSubExpr());
11220 void VisitCXXNewExpr(CXXNewExpr *E) {
11221 if (E->getOperatorNew())
11222 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11223 if (E->getOperatorDelete())
11224 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11225 Inherited::VisitCXXNewExpr(E);
11228 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11229 if (E->getOperatorDelete())
11230 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11231 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11232 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11233 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11234 S.MarkFunctionReferenced(E->getLocStart(),
11235 S.LookupDestructor(Record));
11238 Inherited::VisitCXXDeleteExpr(E);
11241 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11242 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11243 Inherited::VisitCXXConstructExpr(E);
11246 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11247 Visit(E->getExpr());
11250 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11251 Inherited::VisitImplicitCastExpr(E);
11253 if (E->getCastKind() == CK_LValueToRValue)
11254 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11259 /// \brief Mark any declarations that appear within this expression or any
11260 /// potentially-evaluated subexpressions as "referenced".
11262 /// \param SkipLocalVariables If true, don't mark local variables as
11264 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11265 bool SkipLocalVariables) {
11266 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11269 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11270 /// of the program being compiled.
11272 /// This routine emits the given diagnostic when the code currently being
11273 /// type-checked is "potentially evaluated", meaning that there is a
11274 /// possibility that the code will actually be executable. Code in sizeof()
11275 /// expressions, code used only during overload resolution, etc., are not
11276 /// potentially evaluated. This routine will suppress such diagnostics or,
11277 /// in the absolutely nutty case of potentially potentially evaluated
11278 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11281 /// This routine should be used for all diagnostics that describe the run-time
11282 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11283 /// Failure to do so will likely result in spurious diagnostics or failures
11284 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11285 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11286 const PartialDiagnostic &PD) {
11287 switch (ExprEvalContexts.back().Context) {
11289 // The argument will never be evaluated, so don't complain.
11292 case ConstantEvaluated:
11293 // Relevant diagnostics should be produced by constant evaluation.
11296 case PotentiallyEvaluated:
11297 case PotentiallyEvaluatedIfUsed:
11298 if (Statement && getCurFunctionOrMethodDecl()) {
11299 FunctionScopes.back()->PossiblyUnreachableDiags.
11300 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11311 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11312 CallExpr *CE, FunctionDecl *FD) {
11313 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11316 // If we're inside a decltype's expression, don't check for a valid return
11317 // type or construct temporaries until we know whether this is the last call.
11318 if (ExprEvalContexts.back().IsDecltype) {
11319 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11323 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11328 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11329 : FD(FD), CE(CE) { }
11331 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11333 S.Diag(Loc, diag::err_call_incomplete_return)
11334 << T << CE->getSourceRange();
11338 S.Diag(Loc, diag::err_call_function_incomplete_return)
11339 << CE->getSourceRange() << FD->getDeclName() << T;
11340 S.Diag(FD->getLocation(),
11341 diag::note_function_with_incomplete_return_type_declared_here)
11342 << FD->getDeclName();
11344 } Diagnoser(FD, CE);
11346 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11352 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11353 // will prevent this condition from triggering, which is what we want.
11354 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11355 SourceLocation Loc;
11357 unsigned diagnostic = diag::warn_condition_is_assignment;
11358 bool IsOrAssign = false;
11360 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11361 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11364 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11366 // Greylist some idioms by putting them into a warning subcategory.
11367 if (ObjCMessageExpr *ME
11368 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11369 Selector Sel = ME->getSelector();
11371 // self = [<foo> init...]
11372 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11373 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11375 // <foo> = [<bar> nextObject]
11376 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11377 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11380 Loc = Op->getOperatorLoc();
11381 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11382 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11385 IsOrAssign = Op->getOperator() == OO_PipeEqual;
11386 Loc = Op->getOperatorLoc();
11387 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11388 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11390 // Not an assignment.
11394 Diag(Loc, diagnostic) << E->getSourceRange();
11396 SourceLocation Open = E->getLocStart();
11397 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11398 Diag(Loc, diag::note_condition_assign_silence)
11399 << FixItHint::CreateInsertion(Open, "(")
11400 << FixItHint::CreateInsertion(Close, ")");
11403 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11404 << FixItHint::CreateReplacement(Loc, "!=");
11406 Diag(Loc, diag::note_condition_assign_to_comparison)
11407 << FixItHint::CreateReplacement(Loc, "==");
11410 /// \brief Redundant parentheses over an equality comparison can indicate
11411 /// that the user intended an assignment used as condition.
11412 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11413 // Don't warn if the parens came from a macro.
11414 SourceLocation parenLoc = ParenE->getLocStart();
11415 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11417 // Don't warn for dependent expressions.
11418 if (ParenE->isTypeDependent())
11421 Expr *E = ParenE->IgnoreParens();
11423 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11424 if (opE->getOpcode() == BO_EQ &&
11425 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11426 == Expr::MLV_Valid) {
11427 SourceLocation Loc = opE->getOperatorLoc();
11429 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11430 SourceRange ParenERange = ParenE->getSourceRange();
11431 Diag(Loc, diag::note_equality_comparison_silence)
11432 << FixItHint::CreateRemoval(ParenERange.getBegin())
11433 << FixItHint::CreateRemoval(ParenERange.getEnd());
11434 Diag(Loc, diag::note_equality_comparison_to_assign)
11435 << FixItHint::CreateReplacement(Loc, "=");
11439 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11440 DiagnoseAssignmentAsCondition(E);
11441 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11442 DiagnoseEqualityWithExtraParens(parenE);
11444 ExprResult result = CheckPlaceholderExpr(E);
11445 if (result.isInvalid()) return ExprError();
11448 if (!E->isTypeDependent()) {
11449 if (getLangOpts().CPlusPlus)
11450 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11452 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11453 if (ERes.isInvalid())
11454 return ExprError();
11457 QualType T = E->getType();
11458 if (!T->isScalarType()) { // C99 6.8.4.1p1
11459 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11460 << T << E->getSourceRange();
11461 return ExprError();
11468 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11471 return ExprError();
11473 return CheckBooleanCondition(SubExpr, Loc);
11477 /// A visitor for rebuilding a call to an __unknown_any expression
11478 /// to have an appropriate type.
11479 struct RebuildUnknownAnyFunction
11480 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11484 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11486 ExprResult VisitStmt(Stmt *S) {
11487 llvm_unreachable("unexpected statement!");
11490 ExprResult VisitExpr(Expr *E) {
11491 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11492 << E->getSourceRange();
11493 return ExprError();
11496 /// Rebuild an expression which simply semantically wraps another
11497 /// expression which it shares the type and value kind of.
11498 template <class T> ExprResult rebuildSugarExpr(T *E) {
11499 ExprResult SubResult = Visit(E->getSubExpr());
11500 if (SubResult.isInvalid()) return ExprError();
11502 Expr *SubExpr = SubResult.take();
11503 E->setSubExpr(SubExpr);
11504 E->setType(SubExpr->getType());
11505 E->setValueKind(SubExpr->getValueKind());
11506 assert(E->getObjectKind() == OK_Ordinary);
11510 ExprResult VisitParenExpr(ParenExpr *E) {
11511 return rebuildSugarExpr(E);
11514 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11515 return rebuildSugarExpr(E);
11518 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11519 ExprResult SubResult = Visit(E->getSubExpr());
11520 if (SubResult.isInvalid()) return ExprError();
11522 Expr *SubExpr = SubResult.take();
11523 E->setSubExpr(SubExpr);
11524 E->setType(S.Context.getPointerType(SubExpr->getType()));
11525 assert(E->getValueKind() == VK_RValue);
11526 assert(E->getObjectKind() == OK_Ordinary);
11530 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11531 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11533 E->setType(VD->getType());
11535 assert(E->getValueKind() == VK_RValue);
11536 if (S.getLangOpts().CPlusPlus &&
11537 !(isa<CXXMethodDecl>(VD) &&
11538 cast<CXXMethodDecl>(VD)->isInstance()))
11539 E->setValueKind(VK_LValue);
11544 ExprResult VisitMemberExpr(MemberExpr *E) {
11545 return resolveDecl(E, E->getMemberDecl());
11548 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11549 return resolveDecl(E, E->getDecl());
11554 /// Given a function expression of unknown-any type, try to rebuild it
11555 /// to have a function type.
11556 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11557 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11558 if (Result.isInvalid()) return ExprError();
11559 return S.DefaultFunctionArrayConversion(Result.take());
11563 /// A visitor for rebuilding an expression of type __unknown_anytype
11564 /// into one which resolves the type directly on the referring
11565 /// expression. Strict preservation of the original source
11566 /// structure is not a goal.
11567 struct RebuildUnknownAnyExpr
11568 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11572 /// The current destination type.
11575 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11576 : S(S), DestType(CastType) {}
11578 ExprResult VisitStmt(Stmt *S) {
11579 llvm_unreachable("unexpected statement!");
11582 ExprResult VisitExpr(Expr *E) {
11583 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11584 << E->getSourceRange();
11585 return ExprError();
11588 ExprResult VisitCallExpr(CallExpr *E);
11589 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11591 /// Rebuild an expression which simply semantically wraps another
11592 /// expression which it shares the type and value kind of.
11593 template <class T> ExprResult rebuildSugarExpr(T *E) {
11594 ExprResult SubResult = Visit(E->getSubExpr());
11595 if (SubResult.isInvalid()) return ExprError();
11596 Expr *SubExpr = SubResult.take();
11597 E->setSubExpr(SubExpr);
11598 E->setType(SubExpr->getType());
11599 E->setValueKind(SubExpr->getValueKind());
11600 assert(E->getObjectKind() == OK_Ordinary);
11604 ExprResult VisitParenExpr(ParenExpr *E) {
11605 return rebuildSugarExpr(E);
11608 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11609 return rebuildSugarExpr(E);
11612 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11613 const PointerType *Ptr = DestType->getAs<PointerType>();
11615 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11616 << E->getSourceRange();
11617 return ExprError();
11619 assert(E->getValueKind() == VK_RValue);
11620 assert(E->getObjectKind() == OK_Ordinary);
11621 E->setType(DestType);
11623 // Build the sub-expression as if it were an object of the pointee type.
11624 DestType = Ptr->getPointeeType();
11625 ExprResult SubResult = Visit(E->getSubExpr());
11626 if (SubResult.isInvalid()) return ExprError();
11627 E->setSubExpr(SubResult.take());
11631 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11633 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11635 ExprResult VisitMemberExpr(MemberExpr *E) {
11636 return resolveDecl(E, E->getMemberDecl());
11639 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11640 return resolveDecl(E, E->getDecl());
11645 /// Rebuilds a call expression which yielded __unknown_anytype.
11646 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11647 Expr *CalleeExpr = E->getCallee();
11651 FK_FunctionPointer,
11656 QualType CalleeType = CalleeExpr->getType();
11657 if (CalleeType == S.Context.BoundMemberTy) {
11658 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11659 Kind = FK_MemberFunction;
11660 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11661 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11662 CalleeType = Ptr->getPointeeType();
11663 Kind = FK_FunctionPointer;
11665 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11666 Kind = FK_BlockPointer;
11668 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11670 // Verify that this is a legal result type of a function.
11671 if (DestType->isArrayType() || DestType->isFunctionType()) {
11672 unsigned diagID = diag::err_func_returning_array_function;
11673 if (Kind == FK_BlockPointer)
11674 diagID = diag::err_block_returning_array_function;
11676 S.Diag(E->getExprLoc(), diagID)
11677 << DestType->isFunctionType() << DestType;
11678 return ExprError();
11681 // Otherwise, go ahead and set DestType as the call's result.
11682 E->setType(DestType.getNonLValueExprType(S.Context));
11683 E->setValueKind(Expr::getValueKindForType(DestType));
11684 assert(E->getObjectKind() == OK_Ordinary);
11686 // Rebuild the function type, replacing the result type with DestType.
11687 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11688 DestType = S.Context.getFunctionType(DestType,
11689 Proto->arg_type_begin(),
11690 Proto->getNumArgs(),
11691 Proto->getExtProtoInfo());
11693 DestType = S.Context.getFunctionNoProtoType(DestType,
11694 FnType->getExtInfo());
11696 // Rebuild the appropriate pointer-to-function type.
11698 case FK_MemberFunction:
11702 case FK_FunctionPointer:
11703 DestType = S.Context.getPointerType(DestType);
11706 case FK_BlockPointer:
11707 DestType = S.Context.getBlockPointerType(DestType);
11711 // Finally, we can recurse.
11712 ExprResult CalleeResult = Visit(CalleeExpr);
11713 if (!CalleeResult.isUsable()) return ExprError();
11714 E->setCallee(CalleeResult.take());
11716 // Bind a temporary if necessary.
11717 return S.MaybeBindToTemporary(E);
11720 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11721 // Verify that this is a legal result type of a call.
11722 if (DestType->isArrayType() || DestType->isFunctionType()) {
11723 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11724 << DestType->isFunctionType() << DestType;
11725 return ExprError();
11728 // Rewrite the method result type if available.
11729 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11730 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11731 Method->setResultType(DestType);
11734 // Change the type of the message.
11735 E->setType(DestType.getNonReferenceType());
11736 E->setValueKind(Expr::getValueKindForType(DestType));
11738 return S.MaybeBindToTemporary(E);
11741 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11742 // The only case we should ever see here is a function-to-pointer decay.
11743 if (E->getCastKind() == CK_FunctionToPointerDecay) {
11744 assert(E->getValueKind() == VK_RValue);
11745 assert(E->getObjectKind() == OK_Ordinary);
11747 E->setType(DestType);
11749 // Rebuild the sub-expression as the pointee (function) type.
11750 DestType = DestType->castAs<PointerType>()->getPointeeType();
11752 ExprResult Result = Visit(E->getSubExpr());
11753 if (!Result.isUsable()) return ExprError();
11755 E->setSubExpr(Result.take());
11757 } else if (E->getCastKind() == CK_LValueToRValue) {
11758 assert(E->getValueKind() == VK_RValue);
11759 assert(E->getObjectKind() == OK_Ordinary);
11761 assert(isa<BlockPointerType>(E->getType()));
11763 E->setType(DestType);
11765 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11766 DestType = S.Context.getLValueReferenceType(DestType);
11768 ExprResult Result = Visit(E->getSubExpr());
11769 if (!Result.isUsable()) return ExprError();
11771 E->setSubExpr(Result.take());
11774 llvm_unreachable("Unhandled cast type!");
11778 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11779 ExprValueKind ValueKind = VK_LValue;
11780 QualType Type = DestType;
11782 // We know how to make this work for certain kinds of decls:
11785 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11786 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11787 DestType = Ptr->getPointeeType();
11788 ExprResult Result = resolveDecl(E, VD);
11789 if (Result.isInvalid()) return ExprError();
11790 return S.ImpCastExprToType(Result.take(), Type,
11791 CK_FunctionToPointerDecay, VK_RValue);
11794 if (!Type->isFunctionType()) {
11795 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11796 << VD << E->getSourceRange();
11797 return ExprError();
11800 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11801 if (MD->isInstance()) {
11802 ValueKind = VK_RValue;
11803 Type = S.Context.BoundMemberTy;
11806 // Function references aren't l-values in C.
11807 if (!S.getLangOpts().CPlusPlus)
11808 ValueKind = VK_RValue;
11811 } else if (isa<VarDecl>(VD)) {
11812 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11813 Type = RefTy->getPointeeType();
11814 } else if (Type->isFunctionType()) {
11815 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11816 << VD << E->getSourceRange();
11817 return ExprError();
11822 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11823 << VD << E->getSourceRange();
11824 return ExprError();
11827 VD->setType(DestType);
11829 E->setValueKind(ValueKind);
11833 /// Check a cast of an unknown-any type. We intentionally only
11834 /// trigger this for C-style casts.
11835 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11836 Expr *CastExpr, CastKind &CastKind,
11837 ExprValueKind &VK, CXXCastPath &Path) {
11838 // Rewrite the casted expression from scratch.
11839 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
11840 if (!result.isUsable()) return ExprError();
11842 CastExpr = result.take();
11843 VK = CastExpr->getValueKind();
11844 CastKind = CK_NoOp;
11849 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11850 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11853 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11855 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
11857 E = E->IgnoreParenImpCasts();
11858 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11859 E = call->getCallee();
11860 diagID = diag::err_uncasted_call_of_unknown_any;
11866 SourceLocation loc;
11868 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
11869 loc = ref->getLocation();
11870 d = ref->getDecl();
11871 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
11872 loc = mem->getMemberLoc();
11873 d = mem->getMemberDecl();
11874 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
11875 diagID = diag::err_uncasted_call_of_unknown_any;
11876 loc = msg->getSelectorStartLoc();
11877 d = msg->getMethodDecl();
11879 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11880 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11881 << orig->getSourceRange();
11882 return ExprError();
11885 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11886 << E->getSourceRange();
11887 return ExprError();
11890 S.Diag(loc, diagID) << d << orig->getSourceRange();
11892 // Never recoverable.
11893 return ExprError();
11896 /// Check for operands with placeholder types and complain if found.
11897 /// Returns true if there was an error and no recovery was possible.
11898 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
11899 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11900 if (!placeholderType) return Owned(E);
11902 switch (placeholderType->getKind()) {
11904 // Overloaded expressions.
11905 case BuiltinType::Overload: {
11906 // Try to resolve a single function template specialization.
11907 // This is obligatory.
11908 ExprResult result = Owned(E);
11909 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11912 // If that failed, try to recover with a call.
11914 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11915 /*complain*/ true);
11920 // Bound member functions.
11921 case BuiltinType::BoundMember: {
11922 ExprResult result = Owned(E);
11923 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11924 /*complain*/ true);
11928 // ARC unbridged casts.
11929 case BuiltinType::ARCUnbridgedCast: {
11930 Expr *realCast = stripARCUnbridgedCast(E);
11931 diagnoseARCUnbridgedCast(realCast);
11932 return Owned(realCast);
11935 // Expressions of unknown type.
11936 case BuiltinType::UnknownAny:
11937 return diagnoseUnknownAnyExpr(*this, E);
11940 case BuiltinType::PseudoObject:
11941 return checkPseudoObjectRValue(E);
11943 case BuiltinType::BuiltinFn:
11944 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11945 return ExprError();
11947 // Everything else should be impossible.
11948 #define BUILTIN_TYPE(Id, SingletonId) \
11949 case BuiltinType::Id:
11950 #define PLACEHOLDER_TYPE(Id, SingletonId)
11951 #include "clang/AST/BuiltinTypes.def"
11955 llvm_unreachable("invalid placeholder type!");
11958 bool Sema::CheckCaseExpression(Expr *E) {
11959 if (E->isTypeDependent())
11961 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11962 return E->getType()->isIntegralOrEnumerationType();
11966 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11968 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11969 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11970 "Unknown Objective-C Boolean value!");
11971 QualType BoolT = Context.ObjCBuiltinBoolTy;
11972 if (!Context.getBOOLDecl()) {
11973 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
11974 Sema::LookupOrdinaryName);
11975 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
11976 NamedDecl *ND = Result.getFoundDecl();
11977 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11978 Context.setBOOLDecl(TD);
11981 if (Context.getBOOLDecl())
11982 BoolT = Context.getBOOLType();
11983 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,