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 "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/ExprOpenMP.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53 // See if this is an auto-typed variable whose initializer we are parsing.
54 if (ParsingInitForAutoVars.count(D))
57 // See if this is a deleted function.
58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
62 // If the function has a deduced return type, and we can't deduce it,
63 // then we can't use it either.
64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
69 // See if this function is unavailable.
70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78 // Warn if this is used but marked unused.
79 if (const auto *A = D->getAttr<UnusedAttr>()) {
80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81 // should diagnose them.
82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84 if (DC && !DC->hasAttr<UnusedAttr>())
85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
94 const ObjCInterfaceDecl *OID = OMD->getClassInterface();
98 for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99 if (ObjCMethodDecl *CatMeth =
100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101 if (!CatMeth->hasAttr<AvailabilityAttr>())
106 static AvailabilityResult
107 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
108 const ObjCInterfaceDecl *UnknownObjCClass,
109 bool ObjCPropertyAccess) {
110 // See if this declaration is unavailable or deprecated.
112 AvailabilityResult Result = D->getAvailability(&Message);
114 // For typedefs, if the typedef declaration appears available look
115 // to the underlying type to see if it is more restrictive.
116 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
117 if (Result == AR_Available) {
118 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
120 Result = D->getAvailability(&Message);
127 // Forward class declarations get their attributes from their definition.
128 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
129 if (IDecl->getDefinition()) {
130 D = IDecl->getDefinition();
131 Result = D->getAvailability(&Message);
135 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
136 if (Result == AR_Available) {
137 const DeclContext *DC = ECD->getDeclContext();
138 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
139 Result = TheEnumDecl->getAvailability(&Message);
142 const ObjCPropertyDecl *ObjCPDecl = nullptr;
143 if (Result == AR_Deprecated || Result == AR_Unavailable ||
144 Result == AR_NotYetIntroduced) {
145 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
146 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
147 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
148 if (PDeclResult == Result)
159 if (S.getCurContextAvailability() != AR_Deprecated)
160 S.EmitAvailabilityWarning(Sema::AD_Deprecation,
161 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
165 case AR_NotYetIntroduced: {
166 // Don't do this for enums, they can't be redeclared.
167 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
170 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
171 // Objective-C method declarations in categories are not modelled as
172 // redeclarations, so manually look for a redeclaration in a category
174 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
176 // In general, D will point to the most recent redeclaration. However,
177 // for `@class A;` decls, this isn't true -- manually go through the
178 // redecl chain in that case.
179 if (Warn && isa<ObjCInterfaceDecl>(D))
180 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
181 Redecl = Redecl->getPreviousDecl())
182 if (!Redecl->hasAttr<AvailabilityAttr>() ||
183 Redecl->getAttr<AvailabilityAttr>()->isInherited())
187 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
188 UnknownObjCClass, ObjCPDecl,
194 if (S.getCurContextAvailability() != AR_Unavailable)
195 S.EmitAvailabilityWarning(Sema::AD_Unavailable,
196 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
204 /// \brief Emit a note explaining that this function is deleted.
205 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
206 assert(Decl->isDeleted());
208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
210 if (Method && Method->isDeleted() && Method->isDefaulted()) {
211 // If the method was explicitly defaulted, point at that declaration.
212 if (!Method->isImplicit())
213 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
215 // Try to diagnose why this special member function was implicitly
216 // deleted. This might fail, if that reason no longer applies.
217 CXXSpecialMember CSM = getSpecialMember(Method);
218 if (CSM != CXXInvalid)
219 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
224 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
225 if (Ctor && Ctor->isInheritingConstructor())
226 return NoteDeletedInheritingConstructor(Ctor);
228 Diag(Decl->getLocation(), diag::note_availability_specified_here)
232 /// \brief Determine whether a FunctionDecl was ever declared with an
233 /// explicit storage class.
234 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
235 for (auto I : D->redecls()) {
236 if (I->getStorageClass() != SC_None)
242 /// \brief Check whether we're in an extern inline function and referring to a
243 /// variable or function with internal linkage (C11 6.7.4p3).
245 /// This is only a warning because we used to silently accept this code, but
246 /// in many cases it will not behave correctly. This is not enabled in C++ mode
247 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
248 /// and so while there may still be user mistakes, most of the time we can't
249 /// prove that there are errors.
250 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
252 SourceLocation Loc) {
253 // This is disabled under C++; there are too many ways for this to fire in
254 // contexts where the warning is a false positive, or where it is technically
255 // correct but benign.
256 if (S.getLangOpts().CPlusPlus)
259 // Check if this is an inlined function or method.
260 FunctionDecl *Current = S.getCurFunctionDecl();
263 if (!Current->isInlined())
265 if (!Current->isExternallyVisible())
268 // Check if the decl has internal linkage.
269 if (D->getFormalLinkage() != InternalLinkage)
272 // Downgrade from ExtWarn to Extension if
273 // (1) the supposedly external inline function is in the main file,
274 // and probably won't be included anywhere else.
275 // (2) the thing we're referencing is a pure function.
276 // (3) the thing we're referencing is another inline function.
277 // This last can give us false negatives, but it's better than warning on
278 // wrappers for simple C library functions.
279 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
280 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
281 if (!DowngradeWarning && UsedFn)
282 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
284 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
285 : diag::ext_internal_in_extern_inline)
286 << /*IsVar=*/!UsedFn << D;
288 S.MaybeSuggestAddingStaticToDecl(Current);
290 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
294 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
295 const FunctionDecl *First = Cur->getFirstDecl();
297 // Suggest "static" on the function, if possible.
298 if (!hasAnyExplicitStorageClass(First)) {
299 SourceLocation DeclBegin = First->getSourceRange().getBegin();
300 Diag(DeclBegin, diag::note_convert_inline_to_static)
301 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
305 /// \brief Determine whether the use of this declaration is valid, and
306 /// emit any corresponding diagnostics.
308 /// This routine diagnoses various problems with referencing
309 /// declarations that can occur when using a declaration. For example,
310 /// it might warn if a deprecated or unavailable declaration is being
311 /// used, or produce an error (and return true) if a C++0x deleted
312 /// function is being used.
314 /// \returns true if there was an error (this declaration cannot be
315 /// referenced), false otherwise.
317 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
318 const ObjCInterfaceDecl *UnknownObjCClass,
319 bool ObjCPropertyAccess) {
320 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
321 // If there were any diagnostics suppressed by template argument deduction,
323 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
324 if (Pos != SuppressedDiagnostics.end()) {
325 for (const PartialDiagnosticAt &Suppressed : Pos->second)
326 Diag(Suppressed.first, Suppressed.second);
328 // Clear out the list of suppressed diagnostics, so that we don't emit
329 // them again for this specialization. However, we don't obsolete this
330 // entry from the table, because we want to avoid ever emitting these
331 // diagnostics again.
335 // C++ [basic.start.main]p3:
336 // The function 'main' shall not be used within a program.
337 if (cast<FunctionDecl>(D)->isMain())
338 Diag(Loc, diag::ext_main_used);
341 // See if this is an auto-typed variable whose initializer we are parsing.
342 if (ParsingInitForAutoVars.count(D)) {
343 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
345 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
346 << D->getDeclName() << (unsigned)AT->getKeyword();
350 // See if this is a deleted function.
351 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
352 if (FD->isDeleted()) {
353 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
354 if (Ctor && Ctor->isInheritingConstructor())
355 Diag(Loc, diag::err_deleted_inherited_ctor_use)
357 << Ctor->getInheritedConstructor().getConstructor()->getParent();
359 Diag(Loc, diag::err_deleted_function_use);
360 NoteDeletedFunction(FD);
364 // If the function has a deduced return type, and we can't deduce it,
365 // then we can't use it either.
366 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
367 DeduceReturnType(FD, Loc))
371 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
372 // Only the variables omp_in and omp_out are allowed in the combiner.
373 // Only the variables omp_priv and omp_orig are allowed in the
374 // initializer-clause.
375 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
376 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
378 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
379 << getCurFunction()->HasOMPDeclareReductionCombiner;
380 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
383 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
386 DiagnoseUnusedOfDecl(*this, D, Loc);
388 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
393 /// \brief Retrieve the message suffix that should be added to a
394 /// diagnostic complaining about the given function being deleted or
396 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
398 if (FD->getAvailability(&Message))
399 return ": " + Message;
401 return std::string();
404 /// DiagnoseSentinelCalls - This routine checks whether a call or
405 /// message-send is to a declaration with the sentinel attribute, and
406 /// if so, it checks that the requirements of the sentinel are
408 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
409 ArrayRef<Expr *> Args) {
410 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
414 // The number of formal parameters of the declaration.
415 unsigned numFormalParams;
417 // The kind of declaration. This is also an index into a %select in
419 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
421 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
422 numFormalParams = MD->param_size();
423 calleeType = CT_Method;
424 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
425 numFormalParams = FD->param_size();
426 calleeType = CT_Function;
427 } else if (isa<VarDecl>(D)) {
428 QualType type = cast<ValueDecl>(D)->getType();
429 const FunctionType *fn = nullptr;
430 if (const PointerType *ptr = type->getAs<PointerType>()) {
431 fn = ptr->getPointeeType()->getAs<FunctionType>();
433 calleeType = CT_Function;
434 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
435 fn = ptr->getPointeeType()->castAs<FunctionType>();
436 calleeType = CT_Block;
441 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
442 numFormalParams = proto->getNumParams();
450 // "nullPos" is the number of formal parameters at the end which
451 // effectively count as part of the variadic arguments. This is
452 // useful if you would prefer to not have *any* formal parameters,
453 // but the language forces you to have at least one.
454 unsigned nullPos = attr->getNullPos();
455 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
456 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
458 // The number of arguments which should follow the sentinel.
459 unsigned numArgsAfterSentinel = attr->getSentinel();
461 // If there aren't enough arguments for all the formal parameters,
462 // the sentinel, and the args after the sentinel, complain.
463 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
464 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
465 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
469 // Otherwise, find the sentinel expression.
470 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
471 if (!sentinelExpr) return;
472 if (sentinelExpr->isValueDependent()) return;
473 if (Context.isSentinelNullExpr(sentinelExpr)) return;
475 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
476 // or 'NULL' if those are actually defined in the context. Only use
477 // 'nil' for ObjC methods, where it's much more likely that the
478 // variadic arguments form a list of object pointers.
479 SourceLocation MissingNilLoc
480 = getLocForEndOfToken(sentinelExpr->getLocEnd());
481 std::string NullValue;
482 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
484 else if (getLangOpts().CPlusPlus11)
485 NullValue = "nullptr";
486 else if (PP.isMacroDefined("NULL"))
489 NullValue = "(void*) 0";
491 if (MissingNilLoc.isInvalid())
492 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
494 Diag(MissingNilLoc, diag::warn_missing_sentinel)
496 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
497 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
500 SourceRange Sema::getExprRange(Expr *E) const {
501 return E ? E->getSourceRange() : SourceRange();
504 //===----------------------------------------------------------------------===//
505 // Standard Promotions and Conversions
506 //===----------------------------------------------------------------------===//
508 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
509 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
510 // Handle any placeholder expressions which made it here.
511 if (E->getType()->isPlaceholderType()) {
512 ExprResult result = CheckPlaceholderExpr(E);
513 if (result.isInvalid()) return ExprError();
517 QualType Ty = E->getType();
518 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
520 if (Ty->isFunctionType()) {
521 // If we are here, we are not calling a function but taking
522 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
523 if (getLangOpts().OpenCL) {
525 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
529 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
530 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
531 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
534 E = ImpCastExprToType(E, Context.getPointerType(Ty),
535 CK_FunctionToPointerDecay).get();
536 } else if (Ty->isArrayType()) {
537 // In C90 mode, arrays only promote to pointers if the array expression is
538 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
539 // type 'array of type' is converted to an expression that has type 'pointer
540 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
541 // that has type 'array of type' ...". The relevant change is "an lvalue"
542 // (C90) to "an expression" (C99).
545 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
546 // T" can be converted to an rvalue of type "pointer to T".
548 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
549 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
550 CK_ArrayToPointerDecay).get();
555 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
556 // Check to see if we are dereferencing a null pointer. If so,
557 // and if not volatile-qualified, this is undefined behavior that the
558 // optimizer will delete, so warn about it. People sometimes try to use this
559 // to get a deterministic trap and are surprised by clang's behavior. This
560 // only handles the pattern "*null", which is a very syntactic check.
561 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
562 if (UO->getOpcode() == UO_Deref &&
563 UO->getSubExpr()->IgnoreParenCasts()->
564 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
565 !UO->getType().isVolatileQualified()) {
566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567 S.PDiag(diag::warn_indirection_through_null)
568 << UO->getSubExpr()->getSourceRange());
569 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
570 S.PDiag(diag::note_indirection_through_null));
574 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
575 SourceLocation AssignLoc,
577 const ObjCIvarDecl *IV = OIRE->getDecl();
581 DeclarationName MemberName = IV->getDeclName();
582 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
583 if (!Member || !Member->isStr("isa"))
586 const Expr *Base = OIRE->getBase();
587 QualType BaseType = Base->getType();
589 BaseType = BaseType->getPointeeType();
590 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
591 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
592 ObjCInterfaceDecl *ClassDeclared = nullptr;
593 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
594 if (!ClassDeclared->getSuperClass()
595 && (*ClassDeclared->ivar_begin()) == IV) {
597 NamedDecl *ObjectSetClass =
598 S.LookupSingleName(S.TUScope,
599 &S.Context.Idents.get("object_setClass"),
600 SourceLocation(), S.LookupOrdinaryName);
601 if (ObjectSetClass) {
602 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
603 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
604 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
605 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
607 FixItHint::CreateInsertion(RHSLocEnd, ")");
610 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
612 NamedDecl *ObjectGetClass =
613 S.LookupSingleName(S.TUScope,
614 &S.Context.Idents.get("object_getClass"),
615 SourceLocation(), S.LookupOrdinaryName);
617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
618 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
619 FixItHint::CreateReplacement(
620 SourceRange(OIRE->getOpLoc(),
621 OIRE->getLocEnd()), ")");
623 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
625 S.Diag(IV->getLocation(), diag::note_ivar_decl);
630 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
631 // Handle any placeholder expressions which made it here.
632 if (E->getType()->isPlaceholderType()) {
633 ExprResult result = CheckPlaceholderExpr(E);
634 if (result.isInvalid()) return ExprError();
638 // C++ [conv.lval]p1:
639 // A glvalue of a non-function, non-array type T can be
640 // converted to a prvalue.
641 if (!E->isGLValue()) return E;
643 QualType T = E->getType();
644 assert(!T.isNull() && "r-value conversion on typeless expression?");
646 // We don't want to throw lvalue-to-rvalue casts on top of
647 // expressions of certain types in C++.
648 if (getLangOpts().CPlusPlus &&
649 (E->getType() == Context.OverloadTy ||
650 T->isDependentType() ||
654 // The C standard is actually really unclear on this point, and
655 // DR106 tells us what the result should be but not why. It's
656 // generally best to say that void types just doesn't undergo
657 // lvalue-to-rvalue at all. Note that expressions of unqualified
658 // 'void' type are never l-values, but qualified void can be.
662 // OpenCL usually rejects direct accesses to values of 'half' type.
663 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
665 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
670 CheckForNullPointerDereference(*this, E);
671 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
672 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
673 &Context.Idents.get("object_getClass"),
674 SourceLocation(), LookupOrdinaryName);
676 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
677 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
678 FixItHint::CreateReplacement(
679 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
683 else if (const ObjCIvarRefExpr *OIRE =
684 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
685 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
687 // C++ [conv.lval]p1:
688 // [...] If T is a non-class type, the type of the prvalue is the
689 // cv-unqualified version of T. Otherwise, the type of the
693 // If the lvalue has qualified type, the value has the unqualified
694 // version of the type of the lvalue; otherwise, the value has the
695 // type of the lvalue.
696 if (T.hasQualifiers())
697 T = T.getUnqualifiedType();
699 // Under the MS ABI, lock down the inheritance model now.
700 if (T->isMemberPointerType() &&
701 Context.getTargetInfo().getCXXABI().isMicrosoft())
702 (void)isCompleteType(E->getExprLoc(), T);
704 UpdateMarkingForLValueToRValue(E);
706 // Loading a __weak object implicitly retains the value, so we need a cleanup to
708 if (getLangOpts().ObjCAutoRefCount &&
709 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
710 Cleanup.setExprNeedsCleanups(true);
712 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
716 // ... if the lvalue has atomic type, the value has the non-atomic version
717 // of the type of the lvalue ...
718 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
719 T = Atomic->getValueType().getUnqualifiedType();
720 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
727 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
728 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
731 Res = DefaultLvalueConversion(Res.get());
737 /// CallExprUnaryConversions - a special case of an unary conversion
738 /// performed on a function designator of a call expression.
739 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
740 QualType Ty = E->getType();
742 // Only do implicit cast for a function type, but not for a pointer
744 if (Ty->isFunctionType()) {
745 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
746 CK_FunctionToPointerDecay).get();
750 Res = DefaultLvalueConversion(Res.get());
756 /// UsualUnaryConversions - Performs various conversions that are common to most
757 /// operators (C99 6.3). The conversions of array and function types are
758 /// sometimes suppressed. For example, the array->pointer conversion doesn't
759 /// apply if the array is an argument to the sizeof or address (&) operators.
760 /// In these instances, this routine should *not* be called.
761 ExprResult Sema::UsualUnaryConversions(Expr *E) {
762 // First, convert to an r-value.
763 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
768 QualType Ty = E->getType();
769 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
771 // Half FP have to be promoted to float unless it is natively supported
772 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
773 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
775 // Try to perform integral promotions if the object has a theoretically
777 if (Ty->isIntegralOrUnscopedEnumerationType()) {
780 // The following may be used in an expression wherever an int or
781 // unsigned int may be used:
782 // - an object or expression with an integer type whose integer
783 // conversion rank is less than or equal to the rank of int
785 // - A bit-field of type _Bool, int, signed int, or unsigned int.
787 // If an int can represent all values of the original type, the
788 // value is converted to an int; otherwise, it is converted to an
789 // unsigned int. These are called the integer promotions. All
790 // other types are unchanged by the integer promotions.
792 QualType PTy = Context.isPromotableBitField(E);
794 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
797 if (Ty->isPromotableIntegerType()) {
798 QualType PT = Context.getPromotedIntegerType(Ty);
799 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
806 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
807 /// do not have a prototype. Arguments that have type float or __fp16
808 /// are promoted to double. All other argument types are converted by
809 /// UsualUnaryConversions().
810 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
811 QualType Ty = E->getType();
812 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
814 ExprResult Res = UsualUnaryConversions(E);
819 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
821 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
822 if (BTy && (BTy->getKind() == BuiltinType::Half ||
823 BTy->getKind() == BuiltinType::Float))
824 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
826 // C++ performs lvalue-to-rvalue conversion as a default argument
827 // promotion, even on class types, but note:
828 // C++11 [conv.lval]p2:
829 // When an lvalue-to-rvalue conversion occurs in an unevaluated
830 // operand or a subexpression thereof the value contained in the
831 // referenced object is not accessed. Otherwise, if the glvalue
832 // has a class type, the conversion copy-initializes a temporary
833 // of type T from the glvalue and the result of the conversion
834 // is a prvalue for the temporary.
835 // FIXME: add some way to gate this entire thing for correctness in
836 // potentially potentially evaluated contexts.
837 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
838 ExprResult Temp = PerformCopyInitialization(
839 InitializedEntity::InitializeTemporary(E->getType()),
841 if (Temp.isInvalid())
849 /// Determine the degree of POD-ness for an expression.
850 /// Incomplete types are considered POD, since this check can be performed
851 /// when we're in an unevaluated context.
852 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
853 if (Ty->isIncompleteType()) {
854 // C++11 [expr.call]p7:
855 // After these conversions, if the argument does not have arithmetic,
856 // enumeration, pointer, pointer to member, or class type, the program
859 // Since we've already performed array-to-pointer and function-to-pointer
860 // decay, the only such type in C++ is cv void. This also handles
861 // initializer lists as variadic arguments.
862 if (Ty->isVoidType())
865 if (Ty->isObjCObjectType())
870 if (Ty.isCXX98PODType(Context))
873 // C++11 [expr.call]p7:
874 // Passing a potentially-evaluated argument of class type (Clause 9)
875 // having a non-trivial copy constructor, a non-trivial move constructor,
876 // or a non-trivial destructor, with no corresponding parameter,
877 // is conditionally-supported with implementation-defined semantics.
878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880 if (!Record->hasNonTrivialCopyConstructor() &&
881 !Record->hasNonTrivialMoveConstructor() &&
882 !Record->hasNonTrivialDestructor())
883 return VAK_ValidInCXX11;
885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
888 if (Ty->isObjCObjectType())
891 if (getLangOpts().MSVCCompat)
892 return VAK_MSVCUndefined;
894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895 // permitted to reject them. We should consider doing so.
896 return VAK_Undefined;
899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900 // Don't allow one to pass an Objective-C interface to a vararg.
901 const QualType &Ty = E->getType();
902 VarArgKind VAK = isValidVarArgType(Ty);
904 // Complain about passing non-POD types through varargs.
906 case VAK_ValidInCXX11:
908 E->getLocStart(), nullptr,
909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
913 if (Ty->isRecordType()) {
914 // This is unlikely to be what the user intended. If the class has a
915 // 'c_str' member function, the user probably meant to call that.
916 DiagRuntimeBehavior(E->getLocStart(), nullptr,
917 PDiag(diag::warn_pass_class_arg_to_vararg)
918 << Ty << CT << hasCStrMethod(E) << ".c_str()");
923 case VAK_MSVCUndefined:
925 E->getLocStart(), nullptr,
926 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
927 << getLangOpts().CPlusPlus11 << Ty << CT);
931 if (Ty->isObjCObjectType())
933 E->getLocStart(), nullptr,
934 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
937 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
938 << isa<InitListExpr>(E) << Ty << CT;
943 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
944 /// will create a trap if the resulting type is not a POD type.
945 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
946 FunctionDecl *FDecl) {
947 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
948 // Strip the unbridged-cast placeholder expression off, if applicable.
949 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
950 (CT == VariadicMethod ||
951 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
952 E = stripARCUnbridgedCast(E);
954 // Otherwise, do normal placeholder checking.
956 ExprResult ExprRes = CheckPlaceholderExpr(E);
957 if (ExprRes.isInvalid())
963 ExprResult ExprRes = DefaultArgumentPromotion(E);
964 if (ExprRes.isInvalid())
968 // Diagnostics regarding non-POD argument types are
969 // emitted along with format string checking in Sema::CheckFunctionCall().
970 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
971 // Turn this into a trap.
973 SourceLocation TemplateKWLoc;
975 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
977 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
979 if (TrapFn.isInvalid())
982 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
983 E->getLocStart(), None,
985 if (Call.isInvalid())
988 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
990 if (Comma.isInvalid())
995 if (!getLangOpts().CPlusPlus &&
996 RequireCompleteType(E->getExprLoc(), E->getType(),
997 diag::err_call_incomplete_argument))
1003 /// \brief Converts an integer to complex float type. Helper function of
1004 /// UsualArithmeticConversions()
1006 /// \return false if the integer expression is an integer type and is
1007 /// successfully converted to the complex type.
1008 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1009 ExprResult &ComplexExpr,
1013 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1014 if (SkipCast) return false;
1015 if (IntTy->isIntegerType()) {
1016 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1017 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1018 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1019 CK_FloatingRealToComplex);
1021 assert(IntTy->isComplexIntegerType());
1022 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1023 CK_IntegralComplexToFloatingComplex);
1028 /// \brief Handle arithmetic conversion with complex types. Helper function of
1029 /// UsualArithmeticConversions()
1030 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1031 ExprResult &RHS, QualType LHSType,
1033 bool IsCompAssign) {
1034 // if we have an integer operand, the result is the complex type.
1035 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1038 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1039 /*skipCast*/IsCompAssign))
1042 // This handles complex/complex, complex/float, or float/complex.
1043 // When both operands are complex, the shorter operand is converted to the
1044 // type of the longer, and that is the type of the result. This corresponds
1045 // to what is done when combining two real floating-point operands.
1046 // The fun begins when size promotion occur across type domains.
1047 // From H&S 6.3.4: When one operand is complex and the other is a real
1048 // floating-point type, the less precise type is converted, within it's
1049 // real or complex domain, to the precision of the other type. For example,
1050 // when combining a "long double" with a "double _Complex", the
1051 // "double _Complex" is promoted to "long double _Complex".
1053 // Compute the rank of the two types, regardless of whether they are complex.
1054 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1056 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1057 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1058 QualType LHSElementType =
1059 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1060 QualType RHSElementType =
1061 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1063 QualType ResultType = S.Context.getComplexType(LHSElementType);
1065 // Promote the precision of the LHS if not an assignment.
1066 ResultType = S.Context.getComplexType(RHSElementType);
1067 if (!IsCompAssign) {
1070 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1072 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1074 } else if (Order > 0) {
1075 // Promote the precision of the RHS.
1077 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1079 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1084 /// \brief Hande arithmetic conversion from integer to float. Helper function
1085 /// of UsualArithmeticConversions()
1086 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1087 ExprResult &IntExpr,
1088 QualType FloatTy, QualType IntTy,
1089 bool ConvertFloat, bool ConvertInt) {
1090 if (IntTy->isIntegerType()) {
1092 // Convert intExpr to the lhs floating point type.
1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1094 CK_IntegralToFloating);
1098 // Convert both sides to the appropriate complex float.
1099 assert(IntTy->isComplexIntegerType());
1100 QualType result = S.Context.getComplexType(FloatTy);
1102 // _Complex int -> _Complex float
1104 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1105 CK_IntegralComplexToFloatingComplex);
1107 // float -> _Complex float
1109 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1110 CK_FloatingRealToComplex);
1115 /// \brief Handle arithmethic conversion with floating point types. Helper
1116 /// function of UsualArithmeticConversions()
1117 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1118 ExprResult &RHS, QualType LHSType,
1119 QualType RHSType, bool IsCompAssign) {
1120 bool LHSFloat = LHSType->isRealFloatingType();
1121 bool RHSFloat = RHSType->isRealFloatingType();
1123 // If we have two real floating types, convert the smaller operand
1124 // to the bigger result.
1125 if (LHSFloat && RHSFloat) {
1126 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1128 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1132 assert(order < 0 && "illegal float comparison");
1134 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1139 // Half FP has to be promoted to float unless it is natively supported
1140 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1141 LHSType = S.Context.FloatTy;
1143 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1144 /*convertFloat=*/!IsCompAssign,
1145 /*convertInt=*/ true);
1148 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1149 /*convertInt=*/ true,
1150 /*convertFloat=*/!IsCompAssign);
1153 /// \brief Diagnose attempts to convert between __float128 and long double if
1154 /// there is no support for such conversion. Helper function of
1155 /// UsualArithmeticConversions().
1156 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1158 /* No issue converting if at least one of the types is not a floating point
1159 type or the two types have the same rank.
1161 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1162 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1165 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1166 "The remaining types must be floating point types.");
1168 auto *LHSComplex = LHSType->getAs<ComplexType>();
1169 auto *RHSComplex = RHSType->getAs<ComplexType>();
1171 QualType LHSElemType = LHSComplex ?
1172 LHSComplex->getElementType() : LHSType;
1173 QualType RHSElemType = RHSComplex ?
1174 RHSComplex->getElementType() : RHSType;
1176 // No issue if the two types have the same representation
1177 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1178 &S.Context.getFloatTypeSemantics(RHSElemType))
1181 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1182 RHSElemType == S.Context.LongDoubleTy);
1183 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1184 RHSElemType == S.Context.Float128Ty);
1186 /* We've handled the situation where __float128 and long double have the same
1187 representation. The only other allowable conversion is if long double is
1190 return Float128AndLongDouble &&
1191 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1192 &llvm::APFloat::IEEEdouble);
1195 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1198 /// These helper callbacks are placed in an anonymous namespace to
1199 /// permit their use as function template parameters.
1200 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1201 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1204 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1205 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1206 CK_IntegralComplexCast);
1210 /// \brief Handle integer arithmetic conversions. Helper function of
1211 /// UsualArithmeticConversions()
1212 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1213 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1214 ExprResult &RHS, QualType LHSType,
1215 QualType RHSType, bool IsCompAssign) {
1216 // The rules for this case are in C99 6.3.1.8
1217 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1218 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1219 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1220 if (LHSSigned == RHSSigned) {
1221 // Same signedness; use the higher-ranked type
1223 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1225 } else if (!IsCompAssign)
1226 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1228 } else if (order != (LHSSigned ? 1 : -1)) {
1229 // The unsigned type has greater than or equal rank to the
1230 // signed type, so use the unsigned type
1232 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1234 } else if (!IsCompAssign)
1235 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1237 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1238 // The two types are different widths; if we are here, that
1239 // means the signed type is larger than the unsigned type, so
1240 // use the signed type.
1242 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1244 } else if (!IsCompAssign)
1245 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1248 // The signed type is higher-ranked than the unsigned type,
1249 // but isn't actually any bigger (like unsigned int and long
1250 // on most 32-bit systems). Use the unsigned type corresponding
1251 // to the signed type.
1253 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1254 RHS = (*doRHSCast)(S, RHS.get(), result);
1256 LHS = (*doLHSCast)(S, LHS.get(), result);
1261 /// \brief Handle conversions with GCC complex int extension. Helper function
1262 /// of UsualArithmeticConversions()
1263 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1264 ExprResult &RHS, QualType LHSType,
1266 bool IsCompAssign) {
1267 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1268 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1270 if (LHSComplexInt && RHSComplexInt) {
1271 QualType LHSEltType = LHSComplexInt->getElementType();
1272 QualType RHSEltType = RHSComplexInt->getElementType();
1273 QualType ScalarType =
1274 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1275 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1277 return S.Context.getComplexType(ScalarType);
1280 if (LHSComplexInt) {
1281 QualType LHSEltType = LHSComplexInt->getElementType();
1282 QualType ScalarType =
1283 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1284 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1285 QualType ComplexType = S.Context.getComplexType(ScalarType);
1286 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1287 CK_IntegralRealToComplex);
1292 assert(RHSComplexInt);
1294 QualType RHSEltType = RHSComplexInt->getElementType();
1295 QualType ScalarType =
1296 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1297 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1298 QualType ComplexType = S.Context.getComplexType(ScalarType);
1301 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1302 CK_IntegralRealToComplex);
1306 /// UsualArithmeticConversions - Performs various conversions that are common to
1307 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1308 /// routine returns the first non-arithmetic type found. The client is
1309 /// responsible for emitting appropriate error diagnostics.
1310 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1311 bool IsCompAssign) {
1312 if (!IsCompAssign) {
1313 LHS = UsualUnaryConversions(LHS.get());
1314 if (LHS.isInvalid())
1318 RHS = UsualUnaryConversions(RHS.get());
1319 if (RHS.isInvalid())
1322 // For conversion purposes, we ignore any qualifiers.
1323 // For example, "const float" and "float" are equivalent.
1325 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1327 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1329 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1330 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1331 LHSType = AtomicLHS->getValueType();
1333 // If both types are identical, no conversion is needed.
1334 if (LHSType == RHSType)
1337 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1338 // The caller can deal with this (e.g. pointer + int).
1339 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1342 // Apply unary and bitfield promotions to the LHS's type.
1343 QualType LHSUnpromotedType = LHSType;
1344 if (LHSType->isPromotableIntegerType())
1345 LHSType = Context.getPromotedIntegerType(LHSType);
1346 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1347 if (!LHSBitfieldPromoteTy.isNull())
1348 LHSType = LHSBitfieldPromoteTy;
1349 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1350 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1352 // If both types are identical, no conversion is needed.
1353 if (LHSType == RHSType)
1356 // At this point, we have two different arithmetic types.
1358 // Diagnose attempts to convert between __float128 and long double where
1359 // such conversions currently can't be handled.
1360 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1363 // Handle complex types first (C99 6.3.1.8p1).
1364 if (LHSType->isComplexType() || RHSType->isComplexType())
1365 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1368 // Now handle "real" floating types (i.e. float, double, long double).
1369 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1370 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1373 // Handle GCC complex int extension.
1374 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1375 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1378 // Finally, we have two differing integer types.
1379 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1380 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1384 //===----------------------------------------------------------------------===//
1385 // Semantic Analysis for various Expression Types
1386 //===----------------------------------------------------------------------===//
1390 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1391 SourceLocation DefaultLoc,
1392 SourceLocation RParenLoc,
1393 Expr *ControllingExpr,
1394 ArrayRef<ParsedType> ArgTypes,
1395 ArrayRef<Expr *> ArgExprs) {
1396 unsigned NumAssocs = ArgTypes.size();
1397 assert(NumAssocs == ArgExprs.size());
1399 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1400 for (unsigned i = 0; i < NumAssocs; ++i) {
1402 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1407 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1409 llvm::makeArrayRef(Types, NumAssocs),
1416 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1417 SourceLocation DefaultLoc,
1418 SourceLocation RParenLoc,
1419 Expr *ControllingExpr,
1420 ArrayRef<TypeSourceInfo *> Types,
1421 ArrayRef<Expr *> Exprs) {
1422 unsigned NumAssocs = Types.size();
1423 assert(NumAssocs == Exprs.size());
1425 // Decay and strip qualifiers for the controlling expression type, and handle
1426 // placeholder type replacement. See committee discussion from WG14 DR423.
1428 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1429 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1432 ControllingExpr = R.get();
1435 // The controlling expression is an unevaluated operand, so side effects are
1436 // likely unintended.
1437 if (ActiveTemplateInstantiations.empty() &&
1438 ControllingExpr->HasSideEffects(Context, false))
1439 Diag(ControllingExpr->getExprLoc(),
1440 diag::warn_side_effects_unevaluated_context);
1442 bool TypeErrorFound = false,
1443 IsResultDependent = ControllingExpr->isTypeDependent(),
1444 ContainsUnexpandedParameterPack
1445 = ControllingExpr->containsUnexpandedParameterPack();
1447 for (unsigned i = 0; i < NumAssocs; ++i) {
1448 if (Exprs[i]->containsUnexpandedParameterPack())
1449 ContainsUnexpandedParameterPack = true;
1452 if (Types[i]->getType()->containsUnexpandedParameterPack())
1453 ContainsUnexpandedParameterPack = true;
1455 if (Types[i]->getType()->isDependentType()) {
1456 IsResultDependent = true;
1458 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1459 // complete object type other than a variably modified type."
1461 if (Types[i]->getType()->isIncompleteType())
1462 D = diag::err_assoc_type_incomplete;
1463 else if (!Types[i]->getType()->isObjectType())
1464 D = diag::err_assoc_type_nonobject;
1465 else if (Types[i]->getType()->isVariablyModifiedType())
1466 D = diag::err_assoc_type_variably_modified;
1469 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1470 << Types[i]->getTypeLoc().getSourceRange()
1471 << Types[i]->getType();
1472 TypeErrorFound = true;
1475 // C11 6.5.1.1p2 "No two generic associations in the same generic
1476 // selection shall specify compatible types."
1477 for (unsigned j = i+1; j < NumAssocs; ++j)
1478 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1479 Context.typesAreCompatible(Types[i]->getType(),
1480 Types[j]->getType())) {
1481 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1482 diag::err_assoc_compatible_types)
1483 << Types[j]->getTypeLoc().getSourceRange()
1484 << Types[j]->getType()
1485 << Types[i]->getType();
1486 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1487 diag::note_compat_assoc)
1488 << Types[i]->getTypeLoc().getSourceRange()
1489 << Types[i]->getType();
1490 TypeErrorFound = true;
1498 // If we determined that the generic selection is result-dependent, don't
1499 // try to compute the result expression.
1500 if (IsResultDependent)
1501 return new (Context) GenericSelectionExpr(
1502 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1503 ContainsUnexpandedParameterPack);
1505 SmallVector<unsigned, 1> CompatIndices;
1506 unsigned DefaultIndex = -1U;
1507 for (unsigned i = 0; i < NumAssocs; ++i) {
1510 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1511 Types[i]->getType()))
1512 CompatIndices.push_back(i);
1515 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1516 // type compatible with at most one of the types named in its generic
1517 // association list."
1518 if (CompatIndices.size() > 1) {
1519 // We strip parens here because the controlling expression is typically
1520 // parenthesized in macro definitions.
1521 ControllingExpr = ControllingExpr->IgnoreParens();
1522 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1523 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1524 << (unsigned) CompatIndices.size();
1525 for (unsigned I : CompatIndices) {
1526 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1527 diag::note_compat_assoc)
1528 << Types[I]->getTypeLoc().getSourceRange()
1529 << Types[I]->getType();
1534 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1535 // its controlling expression shall have type compatible with exactly one of
1536 // the types named in its generic association list."
1537 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1538 // We strip parens here because the controlling expression is typically
1539 // parenthesized in macro definitions.
1540 ControllingExpr = ControllingExpr->IgnoreParens();
1541 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1542 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1546 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1547 // type name that is compatible with the type of the controlling expression,
1548 // then the result expression of the generic selection is the expression
1549 // in that generic association. Otherwise, the result expression of the
1550 // generic selection is the expression in the default generic association."
1551 unsigned ResultIndex =
1552 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1554 return new (Context) GenericSelectionExpr(
1555 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1556 ContainsUnexpandedParameterPack, ResultIndex);
1559 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1560 /// location of the token and the offset of the ud-suffix within it.
1561 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1563 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1567 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1568 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1569 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1570 IdentifierInfo *UDSuffix,
1571 SourceLocation UDSuffixLoc,
1572 ArrayRef<Expr*> Args,
1573 SourceLocation LitEndLoc) {
1574 assert(Args.size() <= 2 && "too many arguments for literal operator");
1577 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1578 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1579 if (ArgTy[ArgIdx]->isArrayType())
1580 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1583 DeclarationName OpName =
1584 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1585 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1586 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1588 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1589 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1590 /*AllowRaw*/false, /*AllowTemplate*/false,
1591 /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1594 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1597 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1598 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1599 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1600 /// multiple tokens. However, the common case is that StringToks points to one
1604 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1605 assert(!StringToks.empty() && "Must have at least one string!");
1607 StringLiteralParser Literal(StringToks, PP);
1608 if (Literal.hadError)
1611 SmallVector<SourceLocation, 4> StringTokLocs;
1612 for (const Token &Tok : StringToks)
1613 StringTokLocs.push_back(Tok.getLocation());
1615 QualType CharTy = Context.CharTy;
1616 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1617 if (Literal.isWide()) {
1618 CharTy = Context.getWideCharType();
1619 Kind = StringLiteral::Wide;
1620 } else if (Literal.isUTF8()) {
1621 Kind = StringLiteral::UTF8;
1622 } else if (Literal.isUTF16()) {
1623 CharTy = Context.Char16Ty;
1624 Kind = StringLiteral::UTF16;
1625 } else if (Literal.isUTF32()) {
1626 CharTy = Context.Char32Ty;
1627 Kind = StringLiteral::UTF32;
1628 } else if (Literal.isPascal()) {
1629 CharTy = Context.UnsignedCharTy;
1632 QualType CharTyConst = CharTy;
1633 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1634 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1635 CharTyConst.addConst();
1637 // Get an array type for the string, according to C99 6.4.5. This includes
1638 // the nul terminator character as well as the string length for pascal
1640 QualType StrTy = Context.getConstantArrayType(CharTyConst,
1641 llvm::APInt(32, Literal.GetNumStringChars()+1),
1642 ArrayType::Normal, 0);
1644 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1645 if (getLangOpts().OpenCL) {
1646 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1649 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1650 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1651 Kind, Literal.Pascal, StrTy,
1653 StringTokLocs.size());
1654 if (Literal.getUDSuffix().empty())
1657 // We're building a user-defined literal.
1658 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1659 SourceLocation UDSuffixLoc =
1660 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1661 Literal.getUDSuffixOffset());
1663 // Make sure we're allowed user-defined literals here.
1665 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1667 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1668 // operator "" X (str, len)
1669 QualType SizeType = Context.getSizeType();
1671 DeclarationName OpName =
1672 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1673 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1674 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1676 QualType ArgTy[] = {
1677 Context.getArrayDecayedType(StrTy), SizeType
1680 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1681 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1682 /*AllowRaw*/false, /*AllowTemplate*/false,
1683 /*AllowStringTemplate*/true)) {
1686 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1687 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1689 Expr *Args[] = { Lit, LenArg };
1691 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1694 case LOLR_StringTemplate: {
1695 TemplateArgumentListInfo ExplicitArgs;
1697 unsigned CharBits = Context.getIntWidth(CharTy);
1698 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1699 llvm::APSInt Value(CharBits, CharIsUnsigned);
1701 TemplateArgument TypeArg(CharTy);
1702 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1703 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1705 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1706 Value = Lit->getCodeUnit(I);
1707 TemplateArgument Arg(Context, Value, CharTy);
1708 TemplateArgumentLocInfo ArgInfo;
1709 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1711 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1716 llvm_unreachable("unexpected literal operator lookup result");
1720 llvm_unreachable("unexpected literal operator lookup result");
1724 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1726 const CXXScopeSpec *SS) {
1727 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1728 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1731 /// BuildDeclRefExpr - Build an expression that references a
1732 /// declaration that does not require a closure capture.
1734 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1735 const DeclarationNameInfo &NameInfo,
1736 const CXXScopeSpec *SS, NamedDecl *FoundD,
1737 const TemplateArgumentListInfo *TemplateArgs) {
1738 if (getLangOpts().CUDA)
1739 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1740 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1741 if (CheckCUDATarget(Caller, Callee)) {
1742 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1743 << IdentifyCUDATarget(Callee) << D->getIdentifier()
1744 << IdentifyCUDATarget(Caller);
1745 Diag(D->getLocation(), diag::note_previous_decl)
1746 << D->getIdentifier();
1751 bool RefersToCapturedVariable =
1753 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1756 if (isa<VarTemplateSpecializationDecl>(D)) {
1757 VarTemplateSpecializationDecl *VarSpec =
1758 cast<VarTemplateSpecializationDecl>(D);
1760 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1761 : NestedNameSpecifierLoc(),
1762 VarSpec->getTemplateKeywordLoc(), D,
1763 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1764 FoundD, TemplateArgs);
1766 assert(!TemplateArgs && "No template arguments for non-variable"
1767 " template specialization references");
1768 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1769 : NestedNameSpecifierLoc(),
1770 SourceLocation(), D, RefersToCapturedVariable,
1771 NameInfo, Ty, VK, FoundD);
1774 MarkDeclRefReferenced(E);
1776 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1777 Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1778 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1779 recordUseOfEvaluatedWeak(E);
1781 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1782 UnusedPrivateFields.remove(FD);
1783 // Just in case we're building an illegal pointer-to-member.
1784 if (FD->isBitField())
1785 E->setObjectKind(OK_BitField);
1791 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1792 /// possibly a list of template arguments.
1794 /// If this produces template arguments, it is permitted to call
1795 /// DecomposeTemplateName.
1797 /// This actually loses a lot of source location information for
1798 /// non-standard name kinds; we should consider preserving that in
1801 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1802 TemplateArgumentListInfo &Buffer,
1803 DeclarationNameInfo &NameInfo,
1804 const TemplateArgumentListInfo *&TemplateArgs) {
1805 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1806 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1807 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1809 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1810 Id.TemplateId->NumArgs);
1811 translateTemplateArguments(TemplateArgsPtr, Buffer);
1813 TemplateName TName = Id.TemplateId->Template.get();
1814 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1815 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1816 TemplateArgs = &Buffer;
1818 NameInfo = GetNameFromUnqualifiedId(Id);
1819 TemplateArgs = nullptr;
1823 static void emitEmptyLookupTypoDiagnostic(
1824 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1825 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1826 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1828 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1830 // Emit a special diagnostic for failed member lookups.
1831 // FIXME: computing the declaration context might fail here (?)
1833 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1836 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1840 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1841 bool DroppedSpecifier =
1842 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1843 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1844 ? diag::note_implicit_param_decl
1845 : diag::note_previous_decl;
1847 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1848 SemaRef.PDiag(NoteID));
1850 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1851 << Typo << Ctx << DroppedSpecifier
1853 SemaRef.PDiag(NoteID));
1856 /// Diagnose an empty lookup.
1858 /// \return false if new lookup candidates were found
1860 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1861 std::unique_ptr<CorrectionCandidateCallback> CCC,
1862 TemplateArgumentListInfo *ExplicitTemplateArgs,
1863 ArrayRef<Expr *> Args, TypoExpr **Out) {
1864 DeclarationName Name = R.getLookupName();
1866 unsigned diagnostic = diag::err_undeclared_var_use;
1867 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1868 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1869 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1870 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1871 diagnostic = diag::err_undeclared_use;
1872 diagnostic_suggest = diag::err_undeclared_use_suggest;
1875 // If the original lookup was an unqualified lookup, fake an
1876 // unqualified lookup. This is useful when (for example) the
1877 // original lookup would not have found something because it was a
1879 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1881 if (isa<CXXRecordDecl>(DC)) {
1882 LookupQualifiedName(R, DC);
1885 // Don't give errors about ambiguities in this lookup.
1886 R.suppressDiagnostics();
1888 // During a default argument instantiation the CurContext points
1889 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1890 // function parameter list, hence add an explicit check.
1891 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1892 ActiveTemplateInstantiations.back().Kind ==
1893 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1894 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1895 bool isInstance = CurMethod &&
1896 CurMethod->isInstance() &&
1897 DC == CurMethod->getParent() && !isDefaultArgument;
1899 // Give a code modification hint to insert 'this->'.
1900 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1901 // Actually quite difficult!
1902 if (getLangOpts().MSVCCompat)
1903 diagnostic = diag::ext_found_via_dependent_bases_lookup;
1905 Diag(R.getNameLoc(), diagnostic) << Name
1906 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1907 CheckCXXThisCapture(R.getNameLoc());
1909 Diag(R.getNameLoc(), diagnostic) << Name;
1912 // Do we really want to note all of these?
1913 for (NamedDecl *D : R)
1914 Diag(D->getLocation(), diag::note_dependent_var_use);
1916 // Return true if we are inside a default argument instantiation
1917 // and the found name refers to an instance member function, otherwise
1918 // the function calling DiagnoseEmptyLookup will try to create an
1919 // implicit member call and this is wrong for default argument.
1920 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1921 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1925 // Tell the callee to try to recover.
1932 // In Microsoft mode, if we are performing lookup from within a friend
1933 // function definition declared at class scope then we must set
1934 // DC to the lexical parent to be able to search into the parent
1936 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1937 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1938 DC->getLexicalParent()->isRecord())
1939 DC = DC->getLexicalParent();
1941 DC = DC->getParent();
1944 // We didn't find anything, so try to correct for a typo.
1945 TypoCorrection Corrected;
1947 SourceLocation TypoLoc = R.getNameLoc();
1948 assert(!ExplicitTemplateArgs &&
1949 "Diagnosing an empty lookup with explicit template args!");
1950 *Out = CorrectTypoDelayed(
1951 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1952 [=](const TypoCorrection &TC) {
1953 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1954 diagnostic, diagnostic_suggest);
1956 nullptr, CTK_ErrorRecovery);
1959 } else if (S && (Corrected =
1960 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1961 &SS, std::move(CCC), CTK_ErrorRecovery))) {
1962 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1963 bool DroppedSpecifier =
1964 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1965 R.setLookupName(Corrected.getCorrection());
1967 bool AcceptableWithRecovery = false;
1968 bool AcceptableWithoutRecovery = false;
1969 NamedDecl *ND = Corrected.getFoundDecl();
1971 if (Corrected.isOverloaded()) {
1972 OverloadCandidateSet OCS(R.getNameLoc(),
1973 OverloadCandidateSet::CSK_Normal);
1974 OverloadCandidateSet::iterator Best;
1975 for (NamedDecl *CD : Corrected) {
1976 if (FunctionTemplateDecl *FTD =
1977 dyn_cast<FunctionTemplateDecl>(CD))
1978 AddTemplateOverloadCandidate(
1979 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1981 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1982 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1983 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1986 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1988 ND = Best->FoundDecl;
1989 Corrected.setCorrectionDecl(ND);
1992 // FIXME: Arbitrarily pick the first declaration for the note.
1993 Corrected.setCorrectionDecl(ND);
1998 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1999 CXXRecordDecl *Record = nullptr;
2000 if (Corrected.getCorrectionSpecifier()) {
2001 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2002 Record = Ty->getAsCXXRecordDecl();
2005 Record = cast<CXXRecordDecl>(
2006 ND->getDeclContext()->getRedeclContext());
2007 R.setNamingClass(Record);
2010 auto *UnderlyingND = ND->getUnderlyingDecl();
2011 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2012 isa<FunctionTemplateDecl>(UnderlyingND);
2013 // FIXME: If we ended up with a typo for a type name or
2014 // Objective-C class name, we're in trouble because the parser
2015 // is in the wrong place to recover. Suggest the typo
2016 // correction, but don't make it a fix-it since we're not going
2017 // to recover well anyway.
2018 AcceptableWithoutRecovery =
2019 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2021 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2022 // because we aren't able to recover.
2023 AcceptableWithoutRecovery = true;
2026 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2027 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2028 ? diag::note_implicit_param_decl
2029 : diag::note_previous_decl;
2031 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2032 PDiag(NoteID), AcceptableWithRecovery);
2034 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2035 << Name << computeDeclContext(SS, false)
2036 << DroppedSpecifier << SS.getRange(),
2037 PDiag(NoteID), AcceptableWithRecovery);
2039 // Tell the callee whether to try to recover.
2040 return !AcceptableWithRecovery;
2045 // Emit a special diagnostic for failed member lookups.
2046 // FIXME: computing the declaration context might fail here (?)
2047 if (!SS.isEmpty()) {
2048 Diag(R.getNameLoc(), diag::err_no_member)
2049 << Name << computeDeclContext(SS, false)
2054 // Give up, we can't recover.
2055 Diag(R.getNameLoc(), diagnostic) << Name;
2059 /// In Microsoft mode, if we are inside a template class whose parent class has
2060 /// dependent base classes, and we can't resolve an unqualified identifier, then
2061 /// assume the identifier is a member of a dependent base class. We can only
2062 /// recover successfully in static methods, instance methods, and other contexts
2063 /// where 'this' is available. This doesn't precisely match MSVC's
2064 /// instantiation model, but it's close enough.
2066 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2067 DeclarationNameInfo &NameInfo,
2068 SourceLocation TemplateKWLoc,
2069 const TemplateArgumentListInfo *TemplateArgs) {
2070 // Only try to recover from lookup into dependent bases in static methods or
2071 // contexts where 'this' is available.
2072 QualType ThisType = S.getCurrentThisType();
2073 const CXXRecordDecl *RD = nullptr;
2074 if (!ThisType.isNull())
2075 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2076 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2077 RD = MD->getParent();
2078 if (!RD || !RD->hasAnyDependentBases())
2081 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2082 // is available, suggest inserting 'this->' as a fixit.
2083 SourceLocation Loc = NameInfo.getLoc();
2084 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2085 DB << NameInfo.getName() << RD;
2087 if (!ThisType.isNull()) {
2088 DB << FixItHint::CreateInsertion(Loc, "this->");
2089 return CXXDependentScopeMemberExpr::Create(
2090 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2091 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2092 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2095 // Synthesize a fake NNS that points to the derived class. This will
2096 // perform name lookup during template instantiation.
2099 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2100 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2101 return DependentScopeDeclRefExpr::Create(
2102 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2107 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2108 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2109 bool HasTrailingLParen, bool IsAddressOfOperand,
2110 std::unique_ptr<CorrectionCandidateCallback> CCC,
2111 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2112 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2113 "cannot be direct & operand and have a trailing lparen");
2117 TemplateArgumentListInfo TemplateArgsBuffer;
2119 // Decompose the UnqualifiedId into the following data.
2120 DeclarationNameInfo NameInfo;
2121 const TemplateArgumentListInfo *TemplateArgs;
2122 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2124 DeclarationName Name = NameInfo.getName();
2125 IdentifierInfo *II = Name.getAsIdentifierInfo();
2126 SourceLocation NameLoc = NameInfo.getLoc();
2128 // C++ [temp.dep.expr]p3:
2129 // An id-expression is type-dependent if it contains:
2130 // -- an identifier that was declared with a dependent type,
2131 // (note: handled after lookup)
2132 // -- a template-id that is dependent,
2133 // (note: handled in BuildTemplateIdExpr)
2134 // -- a conversion-function-id that specifies a dependent type,
2135 // -- a nested-name-specifier that contains a class-name that
2136 // names a dependent type.
2137 // Determine whether this is a member of an unknown specialization;
2138 // we need to handle these differently.
2139 bool DependentID = false;
2140 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2141 Name.getCXXNameType()->isDependentType()) {
2143 } else if (SS.isSet()) {
2144 if (DeclContext *DC = computeDeclContext(SS, false)) {
2145 if (RequireCompleteDeclContext(SS, DC))
2153 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2154 IsAddressOfOperand, TemplateArgs);
2156 // Perform the required lookup.
2157 LookupResult R(*this, NameInfo,
2158 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2159 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2161 // Lookup the template name again to correctly establish the context in
2162 // which it was found. This is really unfortunate as we already did the
2163 // lookup to determine that it was a template name in the first place. If
2164 // this becomes a performance hit, we can work harder to preserve those
2165 // results until we get here but it's likely not worth it.
2166 bool MemberOfUnknownSpecialization;
2167 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2168 MemberOfUnknownSpecialization);
2170 if (MemberOfUnknownSpecialization ||
2171 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2172 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2173 IsAddressOfOperand, TemplateArgs);
2175 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2176 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2178 // If the result might be in a dependent base class, this is a dependent
2180 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2181 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2182 IsAddressOfOperand, TemplateArgs);
2184 // If this reference is in an Objective-C method, then we need to do
2185 // some special Objective-C lookup, too.
2186 if (IvarLookupFollowUp) {
2187 ExprResult E(LookupInObjCMethod(R, S, II, true));
2191 if (Expr *Ex = E.getAs<Expr>())
2196 if (R.isAmbiguous())
2199 // This could be an implicitly declared function reference (legal in C90,
2200 // extension in C99, forbidden in C++).
2201 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2202 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2203 if (D) R.addDecl(D);
2206 // Determine whether this name might be a candidate for
2207 // argument-dependent lookup.
2208 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2210 if (R.empty() && !ADL) {
2211 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2212 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2213 TemplateKWLoc, TemplateArgs))
2217 // Don't diagnose an empty lookup for inline assembly.
2218 if (IsInlineAsmIdentifier)
2221 // If this name wasn't predeclared and if this is not a function
2222 // call, diagnose the problem.
2223 TypoExpr *TE = nullptr;
2224 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2225 II, SS.isValid() ? SS.getScopeRep() : nullptr);
2226 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2227 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2228 "Typo correction callback misconfigured");
2230 // Make sure the callback knows what the typo being diagnosed is.
2231 CCC->setTypoName(II);
2233 CCC->setTypoNNS(SS.getScopeRep());
2235 if (DiagnoseEmptyLookup(S, SS, R,
2236 CCC ? std::move(CCC) : std::move(DefaultValidator),
2237 nullptr, None, &TE)) {
2238 if (TE && KeywordReplacement) {
2239 auto &State = getTypoExprState(TE);
2240 auto BestTC = State.Consumer->getNextCorrection();
2241 if (BestTC.isKeyword()) {
2242 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2243 if (State.DiagHandler)
2244 State.DiagHandler(BestTC);
2245 KeywordReplacement->startToken();
2246 KeywordReplacement->setKind(II->getTokenID());
2247 KeywordReplacement->setIdentifierInfo(II);
2248 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2249 // Clean up the state associated with the TypoExpr, since it has
2250 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2251 clearDelayedTypo(TE);
2252 // Signal that a correction to a keyword was performed by returning a
2253 // valid-but-null ExprResult.
2254 return (Expr*)nullptr;
2256 State.Consumer->resetCorrectionStream();
2258 return TE ? TE : ExprError();
2261 assert(!R.empty() &&
2262 "DiagnoseEmptyLookup returned false but added no results");
2264 // If we found an Objective-C instance variable, let
2265 // LookupInObjCMethod build the appropriate expression to
2266 // reference the ivar.
2267 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2269 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2270 // In a hopelessly buggy code, Objective-C instance variable
2271 // lookup fails and no expression will be built to reference it.
2272 if (!E.isInvalid() && !E.get())
2278 // This is guaranteed from this point on.
2279 assert(!R.empty() || ADL);
2281 // Check whether this might be a C++ implicit instance member access.
2282 // C++ [class.mfct.non-static]p3:
2283 // When an id-expression that is not part of a class member access
2284 // syntax and not used to form a pointer to member is used in the
2285 // body of a non-static member function of class X, if name lookup
2286 // resolves the name in the id-expression to a non-static non-type
2287 // member of some class C, the id-expression is transformed into a
2288 // class member access expression using (*this) as the
2289 // postfix-expression to the left of the . operator.
2291 // But we don't actually need to do this for '&' operands if R
2292 // resolved to a function or overloaded function set, because the
2293 // expression is ill-formed if it actually works out to be a
2294 // non-static member function:
2296 // C++ [expr.ref]p4:
2297 // Otherwise, if E1.E2 refers to a non-static member function. . .
2298 // [t]he expression can be used only as the left-hand operand of a
2299 // member function call.
2301 // There are other safeguards against such uses, but it's important
2302 // to get this right here so that we don't end up making a
2303 // spuriously dependent expression if we're inside a dependent
2305 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2306 bool MightBeImplicitMember;
2307 if (!IsAddressOfOperand)
2308 MightBeImplicitMember = true;
2309 else if (!SS.isEmpty())
2310 MightBeImplicitMember = false;
2311 else if (R.isOverloadedResult())
2312 MightBeImplicitMember = false;
2313 else if (R.isUnresolvableResult())
2314 MightBeImplicitMember = true;
2316 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2317 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2318 isa<MSPropertyDecl>(R.getFoundDecl());
2320 if (MightBeImplicitMember)
2321 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2322 R, TemplateArgs, S);
2325 if (TemplateArgs || TemplateKWLoc.isValid()) {
2327 // In C++1y, if this is a variable template id, then check it
2328 // in BuildTemplateIdExpr().
2329 // The single lookup result must be a variable template declaration.
2330 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2331 Id.TemplateId->Kind == TNK_Var_template) {
2332 assert(R.getAsSingle<VarTemplateDecl>() &&
2333 "There should only be one declaration found.");
2336 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2339 return BuildDeclarationNameExpr(SS, R, ADL);
2342 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2343 /// declaration name, generally during template instantiation.
2344 /// There's a large number of things which don't need to be done along
2346 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2347 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2348 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2349 DeclContext *DC = computeDeclContext(SS, false);
2351 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2352 NameInfo, /*TemplateArgs=*/nullptr);
2354 if (RequireCompleteDeclContext(SS, DC))
2357 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2358 LookupQualifiedName(R, DC);
2360 if (R.isAmbiguous())
2363 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2364 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2365 NameInfo, /*TemplateArgs=*/nullptr);
2368 Diag(NameInfo.getLoc(), diag::err_no_member)
2369 << NameInfo.getName() << DC << SS.getRange();
2373 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2374 // Diagnose a missing typename if this resolved unambiguously to a type in
2375 // a dependent context. If we can recover with a type, downgrade this to
2376 // a warning in Microsoft compatibility mode.
2377 unsigned DiagID = diag::err_typename_missing;
2378 if (RecoveryTSI && getLangOpts().MSVCCompat)
2379 DiagID = diag::ext_typename_missing;
2380 SourceLocation Loc = SS.getBeginLoc();
2381 auto D = Diag(Loc, DiagID);
2382 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2383 << SourceRange(Loc, NameInfo.getEndLoc());
2385 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2390 // Only issue the fixit if we're prepared to recover.
2391 D << FixItHint::CreateInsertion(Loc, "typename ");
2393 // Recover by pretending this was an elaborated type.
2394 QualType Ty = Context.getTypeDeclType(TD);
2396 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2398 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2399 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2400 QTL.setElaboratedKeywordLoc(SourceLocation());
2401 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2403 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2408 // Defend against this resolving to an implicit member access. We usually
2409 // won't get here if this might be a legitimate a class member (we end up in
2410 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2411 // a pointer-to-member or in an unevaluated context in C++11.
2412 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2413 return BuildPossibleImplicitMemberExpr(SS,
2414 /*TemplateKWLoc=*/SourceLocation(),
2415 R, /*TemplateArgs=*/nullptr, S);
2417 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2420 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2421 /// detected that we're currently inside an ObjC method. Perform some
2422 /// additional lookup.
2424 /// Ideally, most of this would be done by lookup, but there's
2425 /// actually quite a lot of extra work involved.
2427 /// Returns a null sentinel to indicate trivial success.
2429 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2430 IdentifierInfo *II, bool AllowBuiltinCreation) {
2431 SourceLocation Loc = Lookup.getNameLoc();
2432 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2434 // Check for error condition which is already reported.
2438 // There are two cases to handle here. 1) scoped lookup could have failed,
2439 // in which case we should look for an ivar. 2) scoped lookup could have
2440 // found a decl, but that decl is outside the current instance method (i.e.
2441 // a global variable). In these two cases, we do a lookup for an ivar with
2442 // this name, if the lookup sucedes, we replace it our current decl.
2444 // If we're in a class method, we don't normally want to look for
2445 // ivars. But if we don't find anything else, and there's an
2446 // ivar, that's an error.
2447 bool IsClassMethod = CurMethod->isClassMethod();
2451 LookForIvars = true;
2452 else if (IsClassMethod)
2453 LookForIvars = false;
2455 LookForIvars = (Lookup.isSingleResult() &&
2456 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2457 ObjCInterfaceDecl *IFace = nullptr;
2459 IFace = CurMethod->getClassInterface();
2460 ObjCInterfaceDecl *ClassDeclared;
2461 ObjCIvarDecl *IV = nullptr;
2462 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2463 // Diagnose using an ivar in a class method.
2465 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2466 << IV->getDeclName());
2468 // If we're referencing an invalid decl, just return this as a silent
2469 // error node. The error diagnostic was already emitted on the decl.
2470 if (IV->isInvalidDecl())
2473 // Check if referencing a field with __attribute__((deprecated)).
2474 if (DiagnoseUseOfDecl(IV, Loc))
2477 // Diagnose the use of an ivar outside of the declaring class.
2478 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2479 !declaresSameEntity(ClassDeclared, IFace) &&
2480 !getLangOpts().DebuggerSupport)
2481 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2483 // FIXME: This should use a new expr for a direct reference, don't
2484 // turn this into Self->ivar, just return a BareIVarExpr or something.
2485 IdentifierInfo &II = Context.Idents.get("self");
2486 UnqualifiedId SelfName;
2487 SelfName.setIdentifier(&II, SourceLocation());
2488 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2489 CXXScopeSpec SelfScopeSpec;
2490 SourceLocation TemplateKWLoc;
2491 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2492 SelfName, false, false);
2493 if (SelfExpr.isInvalid())
2496 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2497 if (SelfExpr.isInvalid())
2500 MarkAnyDeclReferenced(Loc, IV, true);
2502 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2503 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2504 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2505 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2507 ObjCIvarRefExpr *Result = new (Context)
2508 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2509 IV->getLocation(), SelfExpr.get(), true, true);
2511 if (getLangOpts().ObjCAutoRefCount) {
2512 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2513 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2514 recordUseOfEvaluatedWeak(Result);
2516 if (CurContext->isClosure())
2517 Diag(Loc, diag::warn_implicitly_retains_self)
2518 << FixItHint::CreateInsertion(Loc, "self->");
2523 } else if (CurMethod->isInstanceMethod()) {
2524 // We should warn if a local variable hides an ivar.
2525 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2526 ObjCInterfaceDecl *ClassDeclared;
2527 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2528 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2529 declaresSameEntity(IFace, ClassDeclared))
2530 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2533 } else if (Lookup.isSingleResult() &&
2534 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2535 // If accessing a stand-alone ivar in a class method, this is an error.
2536 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2537 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2538 << IV->getDeclName());
2541 if (Lookup.empty() && II && AllowBuiltinCreation) {
2542 // FIXME. Consolidate this with similar code in LookupName.
2543 if (unsigned BuiltinID = II->getBuiltinID()) {
2544 if (!(getLangOpts().CPlusPlus &&
2545 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2546 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2547 S, Lookup.isForRedeclaration(),
2548 Lookup.getNameLoc());
2549 if (D) Lookup.addDecl(D);
2553 // Sentinel value saying that we didn't do anything special.
2554 return ExprResult((Expr *)nullptr);
2557 /// \brief Cast a base object to a member's actual type.
2559 /// Logically this happens in three phases:
2561 /// * First we cast from the base type to the naming class.
2562 /// The naming class is the class into which we were looking
2563 /// when we found the member; it's the qualifier type if a
2564 /// qualifier was provided, and otherwise it's the base type.
2566 /// * Next we cast from the naming class to the declaring class.
2567 /// If the member we found was brought into a class's scope by
2568 /// a using declaration, this is that class; otherwise it's
2569 /// the class declaring the member.
2571 /// * Finally we cast from the declaring class to the "true"
2572 /// declaring class of the member. This conversion does not
2573 /// obey access control.
2575 Sema::PerformObjectMemberConversion(Expr *From,
2576 NestedNameSpecifier *Qualifier,
2577 NamedDecl *FoundDecl,
2578 NamedDecl *Member) {
2579 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2583 QualType DestRecordType;
2585 QualType FromRecordType;
2586 QualType FromType = From->getType();
2587 bool PointerConversions = false;
2588 if (isa<FieldDecl>(Member)) {
2589 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2591 if (FromType->getAs<PointerType>()) {
2592 DestType = Context.getPointerType(DestRecordType);
2593 FromRecordType = FromType->getPointeeType();
2594 PointerConversions = true;
2596 DestType = DestRecordType;
2597 FromRecordType = FromType;
2599 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2600 if (Method->isStatic())
2603 DestType = Method->getThisType(Context);
2604 DestRecordType = DestType->getPointeeType();
2606 if (FromType->getAs<PointerType>()) {
2607 FromRecordType = FromType->getPointeeType();
2608 PointerConversions = true;
2610 FromRecordType = FromType;
2611 DestType = DestRecordType;
2614 // No conversion necessary.
2618 if (DestType->isDependentType() || FromType->isDependentType())
2621 // If the unqualified types are the same, no conversion is necessary.
2622 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2625 SourceRange FromRange = From->getSourceRange();
2626 SourceLocation FromLoc = FromRange.getBegin();
2628 ExprValueKind VK = From->getValueKind();
2630 // C++ [class.member.lookup]p8:
2631 // [...] Ambiguities can often be resolved by qualifying a name with its
2634 // If the member was a qualified name and the qualified referred to a
2635 // specific base subobject type, we'll cast to that intermediate type
2636 // first and then to the object in which the member is declared. That allows
2637 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2639 // class Base { public: int x; };
2640 // class Derived1 : public Base { };
2641 // class Derived2 : public Base { };
2642 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2644 // void VeryDerived::f() {
2645 // x = 17; // error: ambiguous base subobjects
2646 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2648 if (Qualifier && Qualifier->getAsType()) {
2649 QualType QType = QualType(Qualifier->getAsType(), 0);
2650 assert(QType->isRecordType() && "lookup done with non-record type");
2652 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2654 // In C++98, the qualifier type doesn't actually have to be a base
2655 // type of the object type, in which case we just ignore it.
2656 // Otherwise build the appropriate casts.
2657 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2658 CXXCastPath BasePath;
2659 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2660 FromLoc, FromRange, &BasePath))
2663 if (PointerConversions)
2664 QType = Context.getPointerType(QType);
2665 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2666 VK, &BasePath).get();
2669 FromRecordType = QRecordType;
2671 // If the qualifier type was the same as the destination type,
2673 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2678 bool IgnoreAccess = false;
2680 // If we actually found the member through a using declaration, cast
2681 // down to the using declaration's type.
2683 // Pointer equality is fine here because only one declaration of a
2684 // class ever has member declarations.
2685 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2686 assert(isa<UsingShadowDecl>(FoundDecl));
2687 QualType URecordType = Context.getTypeDeclType(
2688 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2690 // We only need to do this if the naming-class to declaring-class
2691 // conversion is non-trivial.
2692 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2693 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2694 CXXCastPath BasePath;
2695 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2696 FromLoc, FromRange, &BasePath))
2699 QualType UType = URecordType;
2700 if (PointerConversions)
2701 UType = Context.getPointerType(UType);
2702 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2703 VK, &BasePath).get();
2705 FromRecordType = URecordType;
2708 // We don't do access control for the conversion from the
2709 // declaring class to the true declaring class.
2710 IgnoreAccess = true;
2713 CXXCastPath BasePath;
2714 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2715 FromLoc, FromRange, &BasePath,
2719 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2723 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2724 const LookupResult &R,
2725 bool HasTrailingLParen) {
2726 // Only when used directly as the postfix-expression of a call.
2727 if (!HasTrailingLParen)
2730 // Never if a scope specifier was provided.
2734 // Only in C++ or ObjC++.
2735 if (!getLangOpts().CPlusPlus)
2738 // Turn off ADL when we find certain kinds of declarations during
2740 for (NamedDecl *D : R) {
2741 // C++0x [basic.lookup.argdep]p3:
2742 // -- a declaration of a class member
2743 // Since using decls preserve this property, we check this on the
2745 if (D->isCXXClassMember())
2748 // C++0x [basic.lookup.argdep]p3:
2749 // -- a block-scope function declaration that is not a
2750 // using-declaration
2751 // NOTE: we also trigger this for function templates (in fact, we
2752 // don't check the decl type at all, since all other decl types
2753 // turn off ADL anyway).
2754 if (isa<UsingShadowDecl>(D))
2755 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2756 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2759 // C++0x [basic.lookup.argdep]p3:
2760 // -- a declaration that is neither a function or a function
2762 // And also for builtin functions.
2763 if (isa<FunctionDecl>(D)) {
2764 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2766 // But also builtin functions.
2767 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2769 } else if (!isa<FunctionTemplateDecl>(D))
2777 /// Diagnoses obvious problems with the use of the given declaration
2778 /// as an expression. This is only actually called for lookups that
2779 /// were not overloaded, and it doesn't promise that the declaration
2780 /// will in fact be used.
2781 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2782 if (isa<TypedefNameDecl>(D)) {
2783 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2787 if (isa<ObjCInterfaceDecl>(D)) {
2788 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2792 if (isa<NamespaceDecl>(D)) {
2793 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2800 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2801 LookupResult &R, bool NeedsADL,
2802 bool AcceptInvalidDecl) {
2803 // If this is a single, fully-resolved result and we don't need ADL,
2804 // just build an ordinary singleton decl ref.
2805 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2806 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2807 R.getRepresentativeDecl(), nullptr,
2810 // We only need to check the declaration if there's exactly one
2811 // result, because in the overloaded case the results can only be
2812 // functions and function templates.
2813 if (R.isSingleResult() &&
2814 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2817 // Otherwise, just build an unresolved lookup expression. Suppress
2818 // any lookup-related diagnostics; we'll hash these out later, when
2819 // we've picked a target.
2820 R.suppressDiagnostics();
2822 UnresolvedLookupExpr *ULE
2823 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2824 SS.getWithLocInContext(Context),
2825 R.getLookupNameInfo(),
2826 NeedsADL, R.isOverloadedResult(),
2827 R.begin(), R.end());
2832 /// \brief Complete semantic analysis for a reference to the given declaration.
2833 ExprResult Sema::BuildDeclarationNameExpr(
2834 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2835 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2836 bool AcceptInvalidDecl) {
2837 assert(D && "Cannot refer to a NULL declaration");
2838 assert(!isa<FunctionTemplateDecl>(D) &&
2839 "Cannot refer unambiguously to a function template");
2841 SourceLocation Loc = NameInfo.getLoc();
2842 if (CheckDeclInExpr(*this, Loc, D))
2845 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2846 // Specifically diagnose references to class templates that are missing
2847 // a template argument list.
2848 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2849 << Template << SS.getRange();
2850 Diag(Template->getLocation(), diag::note_template_decl_here);
2854 // Make sure that we're referring to a value.
2855 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2857 Diag(Loc, diag::err_ref_non_value)
2858 << D << SS.getRange();
2859 Diag(D->getLocation(), diag::note_declared_at);
2863 // Check whether this declaration can be used. Note that we suppress
2864 // this check when we're going to perform argument-dependent lookup
2865 // on this function name, because this might not be the function
2866 // that overload resolution actually selects.
2867 if (DiagnoseUseOfDecl(VD, Loc))
2870 // Only create DeclRefExpr's for valid Decl's.
2871 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2874 // Handle members of anonymous structs and unions. If we got here,
2875 // and the reference is to a class member indirect field, then this
2876 // must be the subject of a pointer-to-member expression.
2877 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2878 if (!indirectField->isCXXClassMember())
2879 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2883 QualType type = VD->getType();
2884 ExprValueKind valueKind = VK_RValue;
2886 switch (D->getKind()) {
2887 // Ignore all the non-ValueDecl kinds.
2888 #define ABSTRACT_DECL(kind)
2889 #define VALUE(type, base)
2890 #define DECL(type, base) \
2892 #include "clang/AST/DeclNodes.inc"
2893 llvm_unreachable("invalid value decl kind");
2895 // These shouldn't make it here.
2896 case Decl::ObjCAtDefsField:
2897 case Decl::ObjCIvar:
2898 llvm_unreachable("forming non-member reference to ivar?");
2900 // Enum constants are always r-values and never references.
2901 // Unresolved using declarations are dependent.
2902 case Decl::EnumConstant:
2903 case Decl::UnresolvedUsingValue:
2904 case Decl::OMPDeclareReduction:
2905 valueKind = VK_RValue;
2908 // Fields and indirect fields that got here must be for
2909 // pointer-to-member expressions; we just call them l-values for
2910 // internal consistency, because this subexpression doesn't really
2911 // exist in the high-level semantics.
2913 case Decl::IndirectField:
2914 assert(getLangOpts().CPlusPlus &&
2915 "building reference to field in C?");
2917 // These can't have reference type in well-formed programs, but
2918 // for internal consistency we do this anyway.
2919 type = type.getNonReferenceType();
2920 valueKind = VK_LValue;
2923 // Non-type template parameters are either l-values or r-values
2924 // depending on the type.
2925 case Decl::NonTypeTemplateParm: {
2926 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2927 type = reftype->getPointeeType();
2928 valueKind = VK_LValue; // even if the parameter is an r-value reference
2932 // For non-references, we need to strip qualifiers just in case
2933 // the template parameter was declared as 'const int' or whatever.
2934 valueKind = VK_RValue;
2935 type = type.getUnqualifiedType();
2940 case Decl::VarTemplateSpecialization:
2941 case Decl::VarTemplatePartialSpecialization:
2942 case Decl::OMPCapturedExpr:
2943 // In C, "extern void blah;" is valid and is an r-value.
2944 if (!getLangOpts().CPlusPlus &&
2945 !type.hasQualifiers() &&
2946 type->isVoidType()) {
2947 valueKind = VK_RValue;
2952 case Decl::ImplicitParam:
2953 case Decl::ParmVar: {
2954 // These are always l-values.
2955 valueKind = VK_LValue;
2956 type = type.getNonReferenceType();
2958 // FIXME: Does the addition of const really only apply in
2959 // potentially-evaluated contexts? Since the variable isn't actually
2960 // captured in an unevaluated context, it seems that the answer is no.
2961 if (!isUnevaluatedContext()) {
2962 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2963 if (!CapturedType.isNull())
2964 type = CapturedType;
2970 case Decl::Function: {
2971 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2972 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2973 type = Context.BuiltinFnTy;
2974 valueKind = VK_RValue;
2979 const FunctionType *fty = type->castAs<FunctionType>();
2981 // If we're referring to a function with an __unknown_anytype
2982 // result type, make the entire expression __unknown_anytype.
2983 if (fty->getReturnType() == Context.UnknownAnyTy) {
2984 type = Context.UnknownAnyTy;
2985 valueKind = VK_RValue;
2989 // Functions are l-values in C++.
2990 if (getLangOpts().CPlusPlus) {
2991 valueKind = VK_LValue;
2995 // C99 DR 316 says that, if a function type comes from a
2996 // function definition (without a prototype), that type is only
2997 // used for checking compatibility. Therefore, when referencing
2998 // the function, we pretend that we don't have the full function
3000 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3001 isa<FunctionProtoType>(fty))
3002 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3005 // Functions are r-values in C.
3006 valueKind = VK_RValue;
3010 case Decl::MSProperty:
3011 valueKind = VK_LValue;
3014 case Decl::CXXMethod:
3015 // If we're referring to a method with an __unknown_anytype
3016 // result type, make the entire expression __unknown_anytype.
3017 // This should only be possible with a type written directly.
3018 if (const FunctionProtoType *proto
3019 = dyn_cast<FunctionProtoType>(VD->getType()))
3020 if (proto->getReturnType() == Context.UnknownAnyTy) {
3021 type = Context.UnknownAnyTy;
3022 valueKind = VK_RValue;
3026 // C++ methods are l-values if static, r-values if non-static.
3027 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3028 valueKind = VK_LValue;
3033 case Decl::CXXConversion:
3034 case Decl::CXXDestructor:
3035 case Decl::CXXConstructor:
3036 valueKind = VK_RValue;
3040 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3045 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3046 SmallString<32> &Target) {
3047 Target.resize(CharByteWidth * (Source.size() + 1));
3048 char *ResultPtr = &Target[0];
3049 const UTF8 *ErrorPtr;
3050 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3053 Target.resize(ResultPtr - &Target[0]);
3056 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3057 PredefinedExpr::IdentType IT) {
3058 // Pick the current block, lambda, captured statement or function.
3059 Decl *currentDecl = nullptr;
3060 if (const BlockScopeInfo *BSI = getCurBlock())
3061 currentDecl = BSI->TheDecl;
3062 else if (const LambdaScopeInfo *LSI = getCurLambda())
3063 currentDecl = LSI->CallOperator;
3064 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3065 currentDecl = CSI->TheCapturedDecl;
3067 currentDecl = getCurFunctionOrMethodDecl();
3070 Diag(Loc, diag::ext_predef_outside_function);
3071 currentDecl = Context.getTranslationUnitDecl();
3075 StringLiteral *SL = nullptr;
3076 if (cast<DeclContext>(currentDecl)->isDependentContext())
3077 ResTy = Context.DependentTy;
3079 // Pre-defined identifiers are of type char[x], where x is the length of
3081 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3082 unsigned Length = Str.length();
3084 llvm::APInt LengthI(32, Length + 1);
3085 if (IT == PredefinedExpr::LFunction) {
3086 ResTy = Context.WideCharTy.withConst();
3087 SmallString<32> RawChars;
3088 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3090 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3091 /*IndexTypeQuals*/ 0);
3092 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3093 /*Pascal*/ false, ResTy, Loc);
3095 ResTy = Context.CharTy.withConst();
3096 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3097 /*IndexTypeQuals*/ 0);
3098 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3099 /*Pascal*/ false, ResTy, Loc);
3103 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3106 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3107 PredefinedExpr::IdentType IT;
3110 default: llvm_unreachable("Unknown simple primary expr!");
3111 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3112 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3113 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3114 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3115 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3116 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3119 return BuildPredefinedExpr(Loc, IT);
3122 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3123 SmallString<16> CharBuffer;
3124 bool Invalid = false;
3125 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3129 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3131 if (Literal.hadError())
3135 if (Literal.isWide())
3136 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3137 else if (Literal.isUTF16())
3138 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3139 else if (Literal.isUTF32())
3140 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3141 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3142 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3144 Ty = Context.CharTy; // 'x' -> char in C++
3146 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3147 if (Literal.isWide())
3148 Kind = CharacterLiteral::Wide;
3149 else if (Literal.isUTF16())
3150 Kind = CharacterLiteral::UTF16;
3151 else if (Literal.isUTF32())
3152 Kind = CharacterLiteral::UTF32;
3153 else if (Literal.isUTF8())
3154 Kind = CharacterLiteral::UTF8;
3156 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3159 if (Literal.getUDSuffix().empty())
3162 // We're building a user-defined literal.
3163 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3164 SourceLocation UDSuffixLoc =
3165 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3167 // Make sure we're allowed user-defined literals here.
3169 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3171 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3172 // operator "" X (ch)
3173 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3174 Lit, Tok.getLocation());
3177 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3178 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3179 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3180 Context.IntTy, Loc);
3183 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3184 QualType Ty, SourceLocation Loc) {
3185 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3187 using llvm::APFloat;
3188 APFloat Val(Format);
3190 APFloat::opStatus result = Literal.GetFloatValue(Val);
3192 // Overflow is always an error, but underflow is only an error if
3193 // we underflowed to zero (APFloat reports denormals as underflow).
3194 if ((result & APFloat::opOverflow) ||
3195 ((result & APFloat::opUnderflow) && Val.isZero())) {
3196 unsigned diagnostic;
3197 SmallString<20> buffer;
3198 if (result & APFloat::opOverflow) {
3199 diagnostic = diag::warn_float_overflow;
3200 APFloat::getLargest(Format).toString(buffer);
3202 diagnostic = diag::warn_float_underflow;
3203 APFloat::getSmallest(Format).toString(buffer);
3206 S.Diag(Loc, diagnostic)
3208 << StringRef(buffer.data(), buffer.size());
3211 bool isExact = (result == APFloat::opOK);
3212 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3215 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3216 assert(E && "Invalid expression");
3218 if (E->isValueDependent())
3221 QualType QT = E->getType();
3222 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3223 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3227 llvm::APSInt ValueAPS;
3228 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3233 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3234 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3235 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3236 << ValueAPS.toString(10) << ValueIsPositive;
3243 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3244 // Fast path for a single digit (which is quite common). A single digit
3245 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3246 if (Tok.getLength() == 1) {
3247 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3248 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3251 SmallString<128> SpellingBuffer;
3252 // NumericLiteralParser wants to overread by one character. Add padding to
3253 // the buffer in case the token is copied to the buffer. If getSpelling()
3254 // returns a StringRef to the memory buffer, it should have a null char at
3255 // the EOF, so it is also safe.
3256 SpellingBuffer.resize(Tok.getLength() + 1);
3258 // Get the spelling of the token, which eliminates trigraphs, etc.
3259 bool Invalid = false;
3260 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3264 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3265 if (Literal.hadError)
3268 if (Literal.hasUDSuffix()) {
3269 // We're building a user-defined literal.
3270 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3271 SourceLocation UDSuffixLoc =
3272 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3274 // Make sure we're allowed user-defined literals here.
3276 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3279 if (Literal.isFloatingLiteral()) {
3280 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3281 // long double, the literal is treated as a call of the form
3282 // operator "" X (f L)
3283 CookedTy = Context.LongDoubleTy;
3285 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3286 // unsigned long long, the literal is treated as a call of the form
3287 // operator "" X (n ULL)
3288 CookedTy = Context.UnsignedLongLongTy;
3291 DeclarationName OpName =
3292 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3293 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3294 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3296 SourceLocation TokLoc = Tok.getLocation();
3298 // Perform literal operator lookup to determine if we're building a raw
3299 // literal or a cooked one.
3300 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3301 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3302 /*AllowRaw*/true, /*AllowTemplate*/true,
3303 /*AllowStringTemplate*/false)) {
3309 if (Literal.isFloatingLiteral()) {
3310 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3312 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3313 if (Literal.GetIntegerValue(ResultVal))
3314 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3315 << /* Unsigned */ 1;
3316 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3319 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3323 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3324 // literal is treated as a call of the form
3325 // operator "" X ("n")
3326 unsigned Length = Literal.getUDSuffixOffset();
3327 QualType StrTy = Context.getConstantArrayType(
3328 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3329 ArrayType::Normal, 0);
3330 Expr *Lit = StringLiteral::Create(
3331 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3332 /*Pascal*/false, StrTy, &TokLoc, 1);
3333 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3336 case LOLR_Template: {
3337 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3338 // template), L is treated as a call fo the form
3339 // operator "" X <'c1', 'c2', ... 'ck'>()
3340 // where n is the source character sequence c1 c2 ... ck.
3341 TemplateArgumentListInfo ExplicitArgs;
3342 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3343 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3344 llvm::APSInt Value(CharBits, CharIsUnsigned);
3345 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3346 Value = TokSpelling[I];
3347 TemplateArgument Arg(Context, Value, Context.CharTy);
3348 TemplateArgumentLocInfo ArgInfo;
3349 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3351 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3354 case LOLR_StringTemplate:
3355 llvm_unreachable("unexpected literal operator lookup result");
3361 if (Literal.isFloatingLiteral()) {
3363 if (Literal.isHalf){
3364 if (getOpenCLOptions().cl_khr_fp16)
3365 Ty = Context.HalfTy;
3367 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3370 } else if (Literal.isFloat)
3371 Ty = Context.FloatTy;
3372 else if (Literal.isLong)
3373 Ty = Context.LongDoubleTy;
3374 else if (Literal.isFloat128)
3375 Ty = Context.Float128Ty;
3377 Ty = Context.DoubleTy;
3379 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3381 if (Ty == Context.DoubleTy) {
3382 if (getLangOpts().SinglePrecisionConstants) {
3383 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3384 } else if (getLangOpts().OpenCL &&
3385 !((getLangOpts().OpenCLVersion >= 120) ||
3386 getOpenCLOptions().cl_khr_fp64)) {
3387 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3388 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3391 } else if (!Literal.isIntegerLiteral()) {
3396 // 'long long' is a C99 or C++11 feature.
3397 if (!getLangOpts().C99 && Literal.isLongLong) {
3398 if (getLangOpts().CPlusPlus)
3399 Diag(Tok.getLocation(),
3400 getLangOpts().CPlusPlus11 ?
3401 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3403 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3406 // Get the value in the widest-possible width.
3407 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3408 llvm::APInt ResultVal(MaxWidth, 0);
3410 if (Literal.GetIntegerValue(ResultVal)) {
3411 // If this value didn't fit into uintmax_t, error and force to ull.
3412 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3413 << /* Unsigned */ 1;
3414 Ty = Context.UnsignedLongLongTy;
3415 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3416 "long long is not intmax_t?");
3418 // If this value fits into a ULL, try to figure out what else it fits into
3419 // according to the rules of C99 6.4.4.1p5.
3421 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3422 // be an unsigned int.
3423 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3425 // Check from smallest to largest, picking the smallest type we can.
3428 // Microsoft specific integer suffixes are explicitly sized.
3429 if (Literal.MicrosoftInteger) {
3430 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3432 Ty = Context.CharTy;
3434 Width = Literal.MicrosoftInteger;
3435 Ty = Context.getIntTypeForBitwidth(Width,
3436 /*Signed=*/!Literal.isUnsigned);
3440 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3441 // Are int/unsigned possibilities?
3442 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3444 // Does it fit in a unsigned int?
3445 if (ResultVal.isIntN(IntSize)) {
3446 // Does it fit in a signed int?
3447 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3449 else if (AllowUnsigned)
3450 Ty = Context.UnsignedIntTy;
3455 // Are long/unsigned long possibilities?
3456 if (Ty.isNull() && !Literal.isLongLong) {
3457 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3459 // Does it fit in a unsigned long?
3460 if (ResultVal.isIntN(LongSize)) {
3461 // Does it fit in a signed long?
3462 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3463 Ty = Context.LongTy;
3464 else if (AllowUnsigned)
3465 Ty = Context.UnsignedLongTy;
3466 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3468 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3469 const unsigned LongLongSize =
3470 Context.getTargetInfo().getLongLongWidth();
3471 Diag(Tok.getLocation(),
3472 getLangOpts().CPlusPlus
3474 ? diag::warn_old_implicitly_unsigned_long_cxx
3475 : /*C++98 UB*/ diag::
3476 ext_old_implicitly_unsigned_long_cxx
3477 : diag::warn_old_implicitly_unsigned_long)
3478 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3479 : /*will be ill-formed*/ 1);
3480 Ty = Context.UnsignedLongTy;
3486 // Check long long if needed.
3488 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3490 // Does it fit in a unsigned long long?
3491 if (ResultVal.isIntN(LongLongSize)) {
3492 // Does it fit in a signed long long?
3493 // To be compatible with MSVC, hex integer literals ending with the
3494 // LL or i64 suffix are always signed in Microsoft mode.
3495 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3496 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3497 Ty = Context.LongLongTy;
3498 else if (AllowUnsigned)
3499 Ty = Context.UnsignedLongLongTy;
3500 Width = LongLongSize;
3504 // If we still couldn't decide a type, we probably have something that
3505 // does not fit in a signed long long, but has no U suffix.
3507 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3508 Ty = Context.UnsignedLongLongTy;
3509 Width = Context.getTargetInfo().getLongLongWidth();
3512 if (ResultVal.getBitWidth() != Width)
3513 ResultVal = ResultVal.trunc(Width);
3515 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3518 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3519 if (Literal.isImaginary)
3520 Res = new (Context) ImaginaryLiteral(Res,
3521 Context.getComplexType(Res->getType()));
3526 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3527 assert(E && "ActOnParenExpr() missing expr");
3528 return new (Context) ParenExpr(L, R, E);
3531 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3533 SourceRange ArgRange) {
3534 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3535 // scalar or vector data type argument..."
3536 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3537 // type (C99 6.2.5p18) or void.
3538 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3539 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3544 assert((T->isVoidType() || !T->isIncompleteType()) &&
3545 "Scalar types should always be complete");
3549 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3551 SourceRange ArgRange,
3552 UnaryExprOrTypeTrait TraitKind) {
3553 // Invalid types must be hard errors for SFINAE in C++.
3554 if (S.LangOpts.CPlusPlus)
3558 if (T->isFunctionType() &&
3559 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3560 // sizeof(function)/alignof(function) is allowed as an extension.
3561 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3562 << TraitKind << ArgRange;
3566 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3567 // this is an error (OpenCL v1.1 s6.3.k)
3568 if (T->isVoidType()) {
3569 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3570 : diag::ext_sizeof_alignof_void_type;
3571 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3578 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3580 SourceRange ArgRange,
3581 UnaryExprOrTypeTrait TraitKind) {
3582 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3583 // runtime doesn't allow it.
3584 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3585 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3586 << T << (TraitKind == UETT_SizeOf)
3594 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3595 /// pointer type is equal to T) and emit a warning if it is.
3596 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3598 // Don't warn if the operation changed the type.
3599 if (T != E->getType())
3602 // Now look for array decays.
3603 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3604 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3607 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3609 << ICE->getSubExpr()->getType();
3612 /// \brief Check the constraints on expression operands to unary type expression
3613 /// and type traits.
3615 /// Completes any types necessary and validates the constraints on the operand
3616 /// expression. The logic mostly mirrors the type-based overload, but may modify
3617 /// the expression as it completes the type for that expression through template
3618 /// instantiation, etc.
3619 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3620 UnaryExprOrTypeTrait ExprKind) {
3621 QualType ExprTy = E->getType();
3622 assert(!ExprTy->isReferenceType());
3624 if (ExprKind == UETT_VecStep)
3625 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3626 E->getSourceRange());
3628 // Whitelist some types as extensions
3629 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3630 E->getSourceRange(), ExprKind))
3633 // 'alignof' applied to an expression only requires the base element type of
3634 // the expression to be complete. 'sizeof' requires the expression's type to
3635 // be complete (and will attempt to complete it if it's an array of unknown
3637 if (ExprKind == UETT_AlignOf) {
3638 if (RequireCompleteType(E->getExprLoc(),
3639 Context.getBaseElementType(E->getType()),
3640 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3641 E->getSourceRange()))
3644 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3645 ExprKind, E->getSourceRange()))
3649 // Completing the expression's type may have changed it.
3650 ExprTy = E->getType();
3651 assert(!ExprTy->isReferenceType());
3653 if (ExprTy->isFunctionType()) {
3654 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3655 << ExprKind << E->getSourceRange();
3659 // The operand for sizeof and alignof is in an unevaluated expression context,
3660 // so side effects could result in unintended consequences.
3661 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3662 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3663 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3665 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3666 E->getSourceRange(), ExprKind))
3669 if (ExprKind == UETT_SizeOf) {
3670 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3671 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3672 QualType OType = PVD->getOriginalType();
3673 QualType Type = PVD->getType();
3674 if (Type->isPointerType() && OType->isArrayType()) {
3675 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3677 Diag(PVD->getLocation(), diag::note_declared_at);
3682 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3683 // decays into a pointer and returns an unintended result. This is most
3684 // likely a typo for "sizeof(array) op x".
3685 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3686 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3688 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3696 /// \brief Check the constraints on operands to unary expression and type
3699 /// This will complete any types necessary, and validate the various constraints
3700 /// on those operands.
3702 /// The UsualUnaryConversions() function is *not* called by this routine.
3703 /// C99 6.3.2.1p[2-4] all state:
3704 /// Except when it is the operand of the sizeof operator ...
3706 /// C++ [expr.sizeof]p4
3707 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3708 /// standard conversions are not applied to the operand of sizeof.
3710 /// This policy is followed for all of the unary trait expressions.
3711 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3712 SourceLocation OpLoc,
3713 SourceRange ExprRange,
3714 UnaryExprOrTypeTrait ExprKind) {
3715 if (ExprType->isDependentType())
3718 // C++ [expr.sizeof]p2:
3719 // When applied to a reference or a reference type, the result
3720 // is the size of the referenced type.
3721 // C++11 [expr.alignof]p3:
3722 // When alignof is applied to a reference type, the result
3723 // shall be the alignment of the referenced type.
3724 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3725 ExprType = Ref->getPointeeType();
3727 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3728 // When alignof or _Alignof is applied to an array type, the result
3729 // is the alignment of the element type.
3730 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3731 ExprType = Context.getBaseElementType(ExprType);
3733 if (ExprKind == UETT_VecStep)
3734 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3736 // Whitelist some types as extensions
3737 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3741 if (RequireCompleteType(OpLoc, ExprType,
3742 diag::err_sizeof_alignof_incomplete_type,
3743 ExprKind, ExprRange))
3746 if (ExprType->isFunctionType()) {
3747 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3748 << ExprKind << ExprRange;
3752 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3759 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3760 E = E->IgnoreParens();
3762 // Cannot know anything else if the expression is dependent.
3763 if (E->isTypeDependent())
3766 if (E->getObjectKind() == OK_BitField) {
3767 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3768 << 1 << E->getSourceRange();
3772 ValueDecl *D = nullptr;
3773 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3775 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3776 D = ME->getMemberDecl();
3779 // If it's a field, require the containing struct to have a
3780 // complete definition so that we can compute the layout.
3782 // This can happen in C++11 onwards, either by naming the member
3783 // in a way that is not transformed into a member access expression
3784 // (in an unevaluated operand, for instance), or by naming the member
3785 // in a trailing-return-type.
3787 // For the record, since __alignof__ on expressions is a GCC
3788 // extension, GCC seems to permit this but always gives the
3789 // nonsensical answer 0.
3791 // We don't really need the layout here --- we could instead just
3792 // directly check for all the appropriate alignment-lowing
3793 // attributes --- but that would require duplicating a lot of
3794 // logic that just isn't worth duplicating for such a marginal
3796 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3797 // Fast path this check, since we at least know the record has a
3798 // definition if we can find a member of it.
3799 if (!FD->getParent()->isCompleteDefinition()) {
3800 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3801 << E->getSourceRange();
3805 // Otherwise, if it's a field, and the field doesn't have
3806 // reference type, then it must have a complete type (or be a
3807 // flexible array member, which we explicitly want to
3808 // white-list anyway), which makes the following checks trivial.
3809 if (!FD->getType()->isReferenceType())
3813 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3816 bool Sema::CheckVecStepExpr(Expr *E) {
3817 E = E->IgnoreParens();
3819 // Cannot know anything else if the expression is dependent.
3820 if (E->isTypeDependent())
3823 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3826 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3827 CapturingScopeInfo *CSI) {
3828 assert(T->isVariablyModifiedType());
3829 assert(CSI != nullptr);
3831 // We're going to walk down into the type and look for VLA expressions.
3833 const Type *Ty = T.getTypePtr();
3834 switch (Ty->getTypeClass()) {
3835 #define TYPE(Class, Base)
3836 #define ABSTRACT_TYPE(Class, Base)
3837 #define NON_CANONICAL_TYPE(Class, Base)
3838 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3839 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3840 #include "clang/AST/TypeNodes.def"
3843 // These types are never variably-modified.
3847 case Type::ExtVector:
3850 case Type::Elaborated:
3851 case Type::TemplateSpecialization:
3852 case Type::ObjCObject:
3853 case Type::ObjCInterface:
3854 case Type::ObjCObjectPointer:
3856 llvm_unreachable("type class is never variably-modified!");
3857 case Type::Adjusted:
3858 T = cast<AdjustedType>(Ty)->getOriginalType();
3861 T = cast<DecayedType>(Ty)->getPointeeType();
3864 T = cast<PointerType>(Ty)->getPointeeType();
3866 case Type::BlockPointer:
3867 T = cast<BlockPointerType>(Ty)->getPointeeType();
3869 case Type::LValueReference:
3870 case Type::RValueReference:
3871 T = cast<ReferenceType>(Ty)->getPointeeType();
3873 case Type::MemberPointer:
3874 T = cast<MemberPointerType>(Ty)->getPointeeType();
3876 case Type::ConstantArray:
3877 case Type::IncompleteArray:
3878 // Losing element qualification here is fine.
3879 T = cast<ArrayType>(Ty)->getElementType();
3881 case Type::VariableArray: {
3882 // Losing element qualification here is fine.
3883 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3885 // Unknown size indication requires no size computation.
3886 // Otherwise, evaluate and record it.
3887 if (auto Size = VAT->getSizeExpr()) {
3888 if (!CSI->isVLATypeCaptured(VAT)) {
3889 RecordDecl *CapRecord = nullptr;
3890 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3891 CapRecord = LSI->Lambda;
3892 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3893 CapRecord = CRSI->TheRecordDecl;
3896 auto ExprLoc = Size->getExprLoc();
3897 auto SizeType = Context.getSizeType();
3898 // Build the non-static data member.
3900 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3901 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3902 /*BW*/ nullptr, /*Mutable*/ false,
3903 /*InitStyle*/ ICIS_NoInit);
3904 Field->setImplicit(true);
3905 Field->setAccess(AS_private);
3906 Field->setCapturedVLAType(VAT);
3907 CapRecord->addDecl(Field);
3909 CSI->addVLATypeCapture(ExprLoc, SizeType);
3913 T = VAT->getElementType();
3916 case Type::FunctionProto:
3917 case Type::FunctionNoProto:
3918 T = cast<FunctionType>(Ty)->getReturnType();
3922 case Type::UnaryTransform:
3923 case Type::Attributed:
3924 case Type::SubstTemplateTypeParm:
3925 case Type::PackExpansion:
3926 // Keep walking after single level desugaring.
3927 T = T.getSingleStepDesugaredType(Context);
3930 T = cast<TypedefType>(Ty)->desugar();
3932 case Type::Decltype:
3933 T = cast<DecltypeType>(Ty)->desugar();
3936 T = cast<AutoType>(Ty)->getDeducedType();
3938 case Type::TypeOfExpr:
3939 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3942 T = cast<AtomicType>(Ty)->getValueType();
3945 } while (!T.isNull() && T->isVariablyModifiedType());
3948 /// \brief Build a sizeof or alignof expression given a type operand.
3950 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3951 SourceLocation OpLoc,
3952 UnaryExprOrTypeTrait ExprKind,
3957 QualType T = TInfo->getType();
3959 if (!T->isDependentType() &&
3960 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3963 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3964 if (auto *TT = T->getAs<TypedefType>()) {
3965 for (auto I = FunctionScopes.rbegin(),
3966 E = std::prev(FunctionScopes.rend());
3968 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3971 DeclContext *DC = nullptr;
3972 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3973 DC = LSI->CallOperator;
3974 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3975 DC = CRSI->TheCapturedDecl;
3976 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3979 if (DC->containsDecl(TT->getDecl()))
3981 captureVariablyModifiedType(Context, T, CSI);
3987 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3988 return new (Context) UnaryExprOrTypeTraitExpr(
3989 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3992 /// \brief Build a sizeof or alignof expression given an expression
3995 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3996 UnaryExprOrTypeTrait ExprKind) {
3997 ExprResult PE = CheckPlaceholderExpr(E);
4003 // Verify that the operand is valid.
4004 bool isInvalid = false;
4005 if (E->isTypeDependent()) {
4006 // Delay type-checking for type-dependent expressions.
4007 } else if (ExprKind == UETT_AlignOf) {
4008 isInvalid = CheckAlignOfExpr(*this, E);
4009 } else if (ExprKind == UETT_VecStep) {
4010 isInvalid = CheckVecStepExpr(E);
4011 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4012 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4014 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4015 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4018 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4024 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4025 PE = TransformToPotentiallyEvaluated(E);
4026 if (PE.isInvalid()) return ExprError();
4030 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4031 return new (Context) UnaryExprOrTypeTraitExpr(
4032 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4035 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4036 /// expr and the same for @c alignof and @c __alignof
4037 /// Note that the ArgRange is invalid if isType is false.
4039 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4040 UnaryExprOrTypeTrait ExprKind, bool IsType,
4041 void *TyOrEx, SourceRange ArgRange) {
4042 // If error parsing type, ignore.
4043 if (!TyOrEx) return ExprError();
4046 TypeSourceInfo *TInfo;
4047 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4048 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4051 Expr *ArgEx = (Expr *)TyOrEx;
4052 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4056 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4058 if (V.get()->isTypeDependent())
4059 return S.Context.DependentTy;
4061 // _Real and _Imag are only l-values for normal l-values.
4062 if (V.get()->getObjectKind() != OK_Ordinary) {
4063 V = S.DefaultLvalueConversion(V.get());
4068 // These operators return the element type of a complex type.
4069 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4070 return CT->getElementType();
4072 // Otherwise they pass through real integer and floating point types here.
4073 if (V.get()->getType()->isArithmeticType())
4074 return V.get()->getType();
4076 // Test for placeholders.
4077 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4078 if (PR.isInvalid()) return QualType();
4079 if (PR.get() != V.get()) {
4081 return CheckRealImagOperand(S, V, Loc, IsReal);
4084 // Reject anything else.
4085 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4086 << (IsReal ? "__real" : "__imag");
4093 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4094 tok::TokenKind Kind, Expr *Input) {
4095 UnaryOperatorKind Opc;
4097 default: llvm_unreachable("Unknown unary op!");
4098 case tok::plusplus: Opc = UO_PostInc; break;
4099 case tok::minusminus: Opc = UO_PostDec; break;
4102 // Since this might is a postfix expression, get rid of ParenListExprs.
4103 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4104 if (Result.isInvalid()) return ExprError();
4105 Input = Result.get();
4107 return BuildUnaryOp(S, OpLoc, Opc, Input);
4110 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4112 /// \return true on error
4113 static bool checkArithmeticOnObjCPointer(Sema &S,
4114 SourceLocation opLoc,
4116 assert(op->getType()->isObjCObjectPointerType());
4117 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4118 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4121 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4122 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4123 << op->getSourceRange();
4127 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4128 auto *BaseNoParens = Base->IgnoreParens();
4129 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4130 return MSProp->getPropertyDecl()->getType()->isArrayType();
4131 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4135 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4136 Expr *idx, SourceLocation rbLoc) {
4137 if (base && !base->getType().isNull() &&
4138 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4139 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4140 /*Length=*/nullptr, rbLoc);
4142 // Since this might be a postfix expression, get rid of ParenListExprs.
4143 if (isa<ParenListExpr>(base)) {
4144 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4145 if (result.isInvalid()) return ExprError();
4146 base = result.get();
4149 // Handle any non-overload placeholder types in the base and index
4150 // expressions. We can't handle overloads here because the other
4151 // operand might be an overloadable type, in which case the overload
4152 // resolution for the operator overload should get the first crack
4154 bool IsMSPropertySubscript = false;
4155 if (base->getType()->isNonOverloadPlaceholderType()) {
4156 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4157 if (!IsMSPropertySubscript) {
4158 ExprResult result = CheckPlaceholderExpr(base);
4159 if (result.isInvalid())
4161 base = result.get();
4164 if (idx->getType()->isNonOverloadPlaceholderType()) {
4165 ExprResult result = CheckPlaceholderExpr(idx);
4166 if (result.isInvalid()) return ExprError();
4170 // Build an unanalyzed expression if either operand is type-dependent.
4171 if (getLangOpts().CPlusPlus &&
4172 (base->isTypeDependent() || idx->isTypeDependent())) {
4173 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4174 VK_LValue, OK_Ordinary, rbLoc);
4177 // MSDN, property (C++)
4178 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4179 // This attribute can also be used in the declaration of an empty array in a
4180 // class or structure definition. For example:
4181 // __declspec(property(get=GetX, put=PutX)) int x[];
4182 // The above statement indicates that x[] can be used with one or more array
4183 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4184 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4185 if (IsMSPropertySubscript) {
4186 // Build MS property subscript expression if base is MS property reference
4187 // or MS property subscript.
4188 return new (Context) MSPropertySubscriptExpr(
4189 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4192 // Use C++ overloaded-operator rules if either operand has record
4193 // type. The spec says to do this if either type is *overloadable*,
4194 // but enum types can't declare subscript operators or conversion
4195 // operators, so there's nothing interesting for overload resolution
4196 // to do if there aren't any record types involved.
4198 // ObjC pointers have their own subscripting logic that is not tied
4199 // to overload resolution and so should not take this path.
4200 if (getLangOpts().CPlusPlus &&
4201 (base->getType()->isRecordType() ||
4202 (!base->getType()->isObjCObjectPointerType() &&
4203 idx->getType()->isRecordType()))) {
4204 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4207 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4210 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4212 SourceLocation ColonLoc, Expr *Length,
4213 SourceLocation RBLoc) {
4214 if (Base->getType()->isPlaceholderType() &&
4215 !Base->getType()->isSpecificPlaceholderType(
4216 BuiltinType::OMPArraySection)) {
4217 ExprResult Result = CheckPlaceholderExpr(Base);
4218 if (Result.isInvalid())
4220 Base = Result.get();
4222 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4223 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4224 if (Result.isInvalid())
4226 Result = DefaultLvalueConversion(Result.get());
4227 if (Result.isInvalid())
4229 LowerBound = Result.get();
4231 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4232 ExprResult Result = CheckPlaceholderExpr(Length);
4233 if (Result.isInvalid())
4235 Result = DefaultLvalueConversion(Result.get());
4236 if (Result.isInvalid())
4238 Length = Result.get();
4241 // Build an unanalyzed expression if either operand is type-dependent.
4242 if (Base->isTypeDependent() ||
4244 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4245 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4246 return new (Context)
4247 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4248 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4251 // Perform default conversions.
4252 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4254 if (OriginalTy->isAnyPointerType()) {
4255 ResultTy = OriginalTy->getPointeeType();
4256 } else if (OriginalTy->isArrayType()) {
4257 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4260 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4261 << Base->getSourceRange());
4265 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4267 if (Res.isInvalid())
4268 return ExprError(Diag(LowerBound->getExprLoc(),
4269 diag::err_omp_typecheck_section_not_integer)
4270 << 0 << LowerBound->getSourceRange());
4271 LowerBound = Res.get();
4273 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4274 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4275 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4276 << 0 << LowerBound->getSourceRange();
4280 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4281 if (Res.isInvalid())
4282 return ExprError(Diag(Length->getExprLoc(),
4283 diag::err_omp_typecheck_section_not_integer)
4284 << 1 << Length->getSourceRange());
4287 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4288 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4289 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4290 << 1 << Length->getSourceRange();
4293 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4294 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4295 // type. Note that functions are not objects, and that (in C99 parlance)
4296 // incomplete types are not object types.
4297 if (ResultTy->isFunctionType()) {
4298 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4299 << ResultTy << Base->getSourceRange();
4303 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4304 diag::err_omp_section_incomplete_type, Base))
4308 llvm::APSInt LowerBoundValue;
4309 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4310 // OpenMP 4.0, [2.4 Array Sections]
4311 // The lower-bound and length must evaluate to non-negative integers.
4312 if (LowerBoundValue.isNegative()) {
4313 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4314 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4315 << LowerBound->getSourceRange();
4322 llvm::APSInt LengthValue;
4323 if (Length->EvaluateAsInt(LengthValue, Context)) {
4324 // OpenMP 4.0, [2.4 Array Sections]
4325 // The lower-bound and length must evaluate to non-negative integers.
4326 if (LengthValue.isNegative()) {
4327 Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4328 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4329 << Length->getSourceRange();
4333 } else if (ColonLoc.isValid() &&
4334 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4335 !OriginalTy->isVariableArrayType()))) {
4336 // OpenMP 4.0, [2.4 Array Sections]
4337 // When the size of the array dimension is not known, the length must be
4338 // specified explicitly.
4339 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4340 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4344 if (!Base->getType()->isSpecificPlaceholderType(
4345 BuiltinType::OMPArraySection)) {
4346 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4347 if (Result.isInvalid())
4349 Base = Result.get();
4351 return new (Context)
4352 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4353 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4357 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4358 Expr *Idx, SourceLocation RLoc) {
4359 Expr *LHSExp = Base;
4362 // Perform default conversions.
4363 if (!LHSExp->getType()->getAs<VectorType>()) {
4364 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4365 if (Result.isInvalid())
4367 LHSExp = Result.get();
4369 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4370 if (Result.isInvalid())
4372 RHSExp = Result.get();
4374 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4375 ExprValueKind VK = VK_LValue;
4376 ExprObjectKind OK = OK_Ordinary;
4378 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4379 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4380 // in the subscript position. As a result, we need to derive the array base
4381 // and index from the expression types.
4382 Expr *BaseExpr, *IndexExpr;
4383 QualType ResultType;
4384 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4387 ResultType = Context.DependentTy;
4388 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4391 ResultType = PTy->getPointeeType();
4392 } else if (const ObjCObjectPointerType *PTy =
4393 LHSTy->getAs<ObjCObjectPointerType>()) {
4397 // Use custom logic if this should be the pseudo-object subscript
4399 if (!LangOpts.isSubscriptPointerArithmetic())
4400 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4403 ResultType = PTy->getPointeeType();
4404 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4405 // Handle the uncommon case of "123[Ptr]".
4408 ResultType = PTy->getPointeeType();
4409 } else if (const ObjCObjectPointerType *PTy =
4410 RHSTy->getAs<ObjCObjectPointerType>()) {
4411 // Handle the uncommon case of "123[Ptr]".
4414 ResultType = PTy->getPointeeType();
4415 if (!LangOpts.isSubscriptPointerArithmetic()) {
4416 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4417 << ResultType << BaseExpr->getSourceRange();
4420 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4421 BaseExpr = LHSExp; // vectors: V[123]
4423 VK = LHSExp->getValueKind();
4424 if (VK != VK_RValue)
4425 OK = OK_VectorComponent;
4427 // FIXME: need to deal with const...
4428 ResultType = VTy->getElementType();
4429 } else if (LHSTy->isArrayType()) {
4430 // If we see an array that wasn't promoted by
4431 // DefaultFunctionArrayLvalueConversion, it must be an array that
4432 // wasn't promoted because of the C90 rule that doesn't
4433 // allow promoting non-lvalue arrays. Warn, then
4434 // force the promotion here.
4435 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4436 LHSExp->getSourceRange();
4437 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4438 CK_ArrayToPointerDecay).get();
4439 LHSTy = LHSExp->getType();
4443 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4444 } else if (RHSTy->isArrayType()) {
4445 // Same as previous, except for 123[f().a] case
4446 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4447 RHSExp->getSourceRange();
4448 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4449 CK_ArrayToPointerDecay).get();
4450 RHSTy = RHSExp->getType();
4454 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4456 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4457 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4460 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4461 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4462 << IndexExpr->getSourceRange());
4464 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4465 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4466 && !IndexExpr->isTypeDependent())
4467 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4469 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4470 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4471 // type. Note that Functions are not objects, and that (in C99 parlance)
4472 // incomplete types are not object types.
4473 if (ResultType->isFunctionType()) {
4474 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4475 << ResultType << BaseExpr->getSourceRange();
4479 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4480 // GNU extension: subscripting on pointer to void
4481 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4482 << BaseExpr->getSourceRange();
4484 // C forbids expressions of unqualified void type from being l-values.
4485 // See IsCForbiddenLValueType.
4486 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4487 } else if (!ResultType->isDependentType() &&
4488 RequireCompleteType(LLoc, ResultType,
4489 diag::err_subscript_incomplete_type, BaseExpr))
4492 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4493 !ResultType.isCForbiddenLValueType());
4495 return new (Context)
4496 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4499 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4501 ParmVarDecl *Param) {
4502 if (Param->hasUnparsedDefaultArg()) {
4504 diag::err_use_of_default_argument_to_function_declared_later) <<
4505 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4506 Diag(UnparsedDefaultArgLocs[Param],
4507 diag::note_default_argument_declared_here);
4511 if (Param->hasUninstantiatedDefaultArg()) {
4512 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4514 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4517 // Instantiate the expression.
4518 MultiLevelTemplateArgumentList MutiLevelArgList
4519 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4521 InstantiatingTemplate Inst(*this, CallLoc, Param,
4522 MutiLevelArgList.getInnermost());
4523 if (Inst.isInvalid())
4525 if (Inst.isAlreadyInstantiating()) {
4526 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4527 Param->setInvalidDecl();
4533 // C++ [dcl.fct.default]p5:
4534 // The names in the [default argument] expression are bound, and
4535 // the semantic constraints are checked, at the point where the
4536 // default argument expression appears.
4537 ContextRAII SavedContext(*this, FD);
4538 LocalInstantiationScope Local(*this);
4539 Result = SubstExpr(UninstExpr, MutiLevelArgList);
4541 if (Result.isInvalid())
4544 // Check the expression as an initializer for the parameter.
4545 InitializedEntity Entity
4546 = InitializedEntity::InitializeParameter(Context, Param);
4547 InitializationKind Kind
4548 = InitializationKind::CreateCopy(Param->getLocation(),
4549 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4550 Expr *ResultE = Result.getAs<Expr>();
4552 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4553 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4554 if (Result.isInvalid())
4557 Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4558 Param->getOuterLocStart());
4559 if (Result.isInvalid())
4562 // Remember the instantiated default argument.
4563 Param->setDefaultArg(Result.getAs<Expr>());
4564 if (ASTMutationListener *L = getASTMutationListener()) {
4565 L->DefaultArgumentInstantiated(Param);
4569 // If the default argument expression is not set yet, we are building it now.
4570 if (!Param->hasInit()) {
4571 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4572 Param->setInvalidDecl();
4576 // If the default expression creates temporaries, we need to
4577 // push them to the current stack of expression temporaries so they'll
4578 // be properly destroyed.
4579 // FIXME: We should really be rebuilding the default argument with new
4580 // bound temporaries; see the comment in PR5810.
4581 // We don't need to do that with block decls, though, because
4582 // blocks in default argument expression can never capture anything.
4583 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4584 // Set the "needs cleanups" bit regardless of whether there are
4585 // any explicit objects.
4586 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4588 // Append all the objects to the cleanup list. Right now, this
4589 // should always be a no-op, because blocks in default argument
4590 // expressions should never be able to capture anything.
4591 assert(!Init->getNumObjects() &&
4592 "default argument expression has capturing blocks?");
4595 // We already type-checked the argument, so we know it works.
4596 // Just mark all of the declarations in this potentially-evaluated expression
4597 // as being "referenced".
4598 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4599 /*SkipLocalVariables=*/true);
4600 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4604 Sema::VariadicCallType
4605 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4607 if (Proto && Proto->isVariadic()) {
4608 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4609 return VariadicConstructor;
4610 else if (Fn && Fn->getType()->isBlockPointerType())
4611 return VariadicBlock;
4613 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4614 if (Method->isInstance())
4615 return VariadicMethod;
4616 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4617 return VariadicMethod;
4618 return VariadicFunction;
4620 return VariadicDoesNotApply;
4624 class FunctionCallCCC : public FunctionCallFilterCCC {
4626 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4627 unsigned NumArgs, MemberExpr *ME)
4628 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4629 FunctionName(FuncName) {}
4631 bool ValidateCandidate(const TypoCorrection &candidate) override {
4632 if (!candidate.getCorrectionSpecifier() ||
4633 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4637 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4641 const IdentifierInfo *const FunctionName;
4645 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4646 FunctionDecl *FDecl,
4647 ArrayRef<Expr *> Args) {
4648 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4649 DeclarationName FuncName = FDecl->getDeclName();
4650 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4652 if (TypoCorrection Corrected = S.CorrectTypo(
4653 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4654 S.getScopeForContext(S.CurContext), nullptr,
4655 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4657 Sema::CTK_ErrorRecovery)) {
4658 if (NamedDecl *ND = Corrected.getFoundDecl()) {
4659 if (Corrected.isOverloaded()) {
4660 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4661 OverloadCandidateSet::iterator Best;
4662 for (NamedDecl *CD : Corrected) {
4663 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4664 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4667 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4669 ND = Best->FoundDecl;
4670 Corrected.setCorrectionDecl(ND);
4676 ND = ND->getUnderlyingDecl();
4677 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4681 return TypoCorrection();
4684 /// ConvertArgumentsForCall - Converts the arguments specified in
4685 /// Args/NumArgs to the parameter types of the function FDecl with
4686 /// function prototype Proto. Call is the call expression itself, and
4687 /// Fn is the function expression. For a C++ member function, this
4688 /// routine does not attempt to convert the object argument. Returns
4689 /// true if the call is ill-formed.
4691 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4692 FunctionDecl *FDecl,
4693 const FunctionProtoType *Proto,
4694 ArrayRef<Expr *> Args,
4695 SourceLocation RParenLoc,
4696 bool IsExecConfig) {
4697 // Bail out early if calling a builtin with custom typechecking.
4699 if (unsigned ID = FDecl->getBuiltinID())
4700 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4703 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4704 // assignment, to the types of the corresponding parameter, ...
4705 unsigned NumParams = Proto->getNumParams();
4706 bool Invalid = false;
4707 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4708 unsigned FnKind = Fn->getType()->isBlockPointerType()
4710 : (IsExecConfig ? 3 /* kernel function (exec config) */
4711 : 0 /* function */);
4713 // If too few arguments are available (and we don't have default
4714 // arguments for the remaining parameters), don't make the call.
4715 if (Args.size() < NumParams) {
4716 if (Args.size() < MinArgs) {
4718 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4720 MinArgs == NumParams && !Proto->isVariadic()
4721 ? diag::err_typecheck_call_too_few_args_suggest
4722 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4723 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4724 << static_cast<unsigned>(Args.size())
4725 << TC.getCorrectionRange());
4726 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4728 MinArgs == NumParams && !Proto->isVariadic()
4729 ? diag::err_typecheck_call_too_few_args_one
4730 : diag::err_typecheck_call_too_few_args_at_least_one)
4731 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4733 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4734 ? diag::err_typecheck_call_too_few_args
4735 : diag::err_typecheck_call_too_few_args_at_least)
4736 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4737 << Fn->getSourceRange();
4739 // Emit the location of the prototype.
4740 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4741 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4746 Call->setNumArgs(Context, NumParams);
4749 // If too many are passed and not variadic, error on the extras and drop
4751 if (Args.size() > NumParams) {
4752 if (!Proto->isVariadic()) {
4754 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4756 MinArgs == NumParams && !Proto->isVariadic()
4757 ? diag::err_typecheck_call_too_many_args_suggest
4758 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4759 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4760 << static_cast<unsigned>(Args.size())
4761 << TC.getCorrectionRange());
4762 } else if (NumParams == 1 && FDecl &&
4763 FDecl->getParamDecl(0)->getDeclName())
4764 Diag(Args[NumParams]->getLocStart(),
4765 MinArgs == NumParams
4766 ? diag::err_typecheck_call_too_many_args_one
4767 : diag::err_typecheck_call_too_many_args_at_most_one)
4768 << FnKind << FDecl->getParamDecl(0)
4769 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4770 << SourceRange(Args[NumParams]->getLocStart(),
4771 Args.back()->getLocEnd());
4773 Diag(Args[NumParams]->getLocStart(),
4774 MinArgs == NumParams
4775 ? diag::err_typecheck_call_too_many_args
4776 : diag::err_typecheck_call_too_many_args_at_most)
4777 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4778 << Fn->getSourceRange()
4779 << SourceRange(Args[NumParams]->getLocStart(),
4780 Args.back()->getLocEnd());
4782 // Emit the location of the prototype.
4783 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4784 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4787 // This deletes the extra arguments.
4788 Call->setNumArgs(Context, NumParams);
4792 SmallVector<Expr *, 8> AllArgs;
4793 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4795 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4796 Proto, 0, Args, AllArgs, CallType);
4799 unsigned TotalNumArgs = AllArgs.size();
4800 for (unsigned i = 0; i < TotalNumArgs; ++i)
4801 Call->setArg(i, AllArgs[i]);
4806 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4807 const FunctionProtoType *Proto,
4808 unsigned FirstParam, ArrayRef<Expr *> Args,
4809 SmallVectorImpl<Expr *> &AllArgs,
4810 VariadicCallType CallType, bool AllowExplicit,
4811 bool IsListInitialization) {
4812 unsigned NumParams = Proto->getNumParams();
4813 bool Invalid = false;
4815 // Continue to check argument types (even if we have too few/many args).
4816 for (unsigned i = FirstParam; i < NumParams; i++) {
4817 QualType ProtoArgType = Proto->getParamType(i);
4820 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4821 if (ArgIx < Args.size()) {
4822 Arg = Args[ArgIx++];
4824 if (RequireCompleteType(Arg->getLocStart(),
4826 diag::err_call_incomplete_argument, Arg))
4829 // Strip the unbridged-cast placeholder expression off, if applicable.
4830 bool CFAudited = false;
4831 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4832 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4833 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4834 Arg = stripARCUnbridgedCast(Arg);
4835 else if (getLangOpts().ObjCAutoRefCount &&
4836 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4837 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4840 InitializedEntity Entity =
4841 Param ? InitializedEntity::InitializeParameter(Context, Param,
4843 : InitializedEntity::InitializeParameter(
4844 Context, ProtoArgType, Proto->isParamConsumed(i));
4846 // Remember that parameter belongs to a CF audited API.
4848 Entity.setParameterCFAudited();
4850 ExprResult ArgE = PerformCopyInitialization(
4851 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4852 if (ArgE.isInvalid())
4855 Arg = ArgE.getAs<Expr>();
4857 assert(Param && "can't use default arguments without a known callee");
4859 ExprResult ArgExpr =
4860 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4861 if (ArgExpr.isInvalid())
4864 Arg = ArgExpr.getAs<Expr>();
4867 // Check for array bounds violations for each argument to the call. This
4868 // check only triggers warnings when the argument isn't a more complex Expr
4869 // with its own checking, such as a BinaryOperator.
4870 CheckArrayAccess(Arg);
4872 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4873 CheckStaticArrayArgument(CallLoc, Param, Arg);
4875 AllArgs.push_back(Arg);
4878 // If this is a variadic call, handle args passed through "...".
4879 if (CallType != VariadicDoesNotApply) {
4880 // Assume that extern "C" functions with variadic arguments that
4881 // return __unknown_anytype aren't *really* variadic.
4882 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4883 FDecl->isExternC()) {
4884 for (Expr *A : Args.slice(ArgIx)) {
4885 QualType paramType; // ignored
4886 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4887 Invalid |= arg.isInvalid();
4888 AllArgs.push_back(arg.get());
4891 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4893 for (Expr *A : Args.slice(ArgIx)) {
4894 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4895 Invalid |= Arg.isInvalid();
4896 AllArgs.push_back(Arg.get());
4900 // Check for array bounds violations.
4901 for (Expr *A : Args.slice(ArgIx))
4902 CheckArrayAccess(A);
4907 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4908 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4909 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4910 TL = DTL.getOriginalLoc();
4911 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4912 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4913 << ATL.getLocalSourceRange();
4916 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4917 /// array parameter, check that it is non-null, and that if it is formed by
4918 /// array-to-pointer decay, the underlying array is sufficiently large.
4920 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4921 /// array type derivation, then for each call to the function, the value of the
4922 /// corresponding actual argument shall provide access to the first element of
4923 /// an array with at least as many elements as specified by the size expression.
4925 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4927 const Expr *ArgExpr) {
4928 // Static array parameters are not supported in C++.
4929 if (!Param || getLangOpts().CPlusPlus)
4932 QualType OrigTy = Param->getOriginalType();
4934 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4935 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4938 if (ArgExpr->isNullPointerConstant(Context,
4939 Expr::NPC_NeverValueDependent)) {
4940 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4941 DiagnoseCalleeStaticArrayParam(*this, Param);
4945 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4949 const ConstantArrayType *ArgCAT =
4950 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4954 if (ArgCAT->getSize().ult(CAT->getSize())) {
4955 Diag(CallLoc, diag::warn_static_array_too_small)
4956 << ArgExpr->getSourceRange()
4957 << (unsigned) ArgCAT->getSize().getZExtValue()
4958 << (unsigned) CAT->getSize().getZExtValue();
4959 DiagnoseCalleeStaticArrayParam(*this, Param);
4963 /// Given a function expression of unknown-any type, try to rebuild it
4964 /// to have a function type.
4965 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4967 /// Is the given type a placeholder that we need to lower out
4968 /// immediately during argument processing?
4969 static bool isPlaceholderToRemoveAsArg(QualType type) {
4970 // Placeholders are never sugared.
4971 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4972 if (!placeholder) return false;
4974 switch (placeholder->getKind()) {
4975 // Ignore all the non-placeholder types.
4976 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4977 case BuiltinType::Id:
4978 #include "clang/Basic/OpenCLImageTypes.def"
4979 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4980 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4981 #include "clang/AST/BuiltinTypes.def"
4984 // We cannot lower out overload sets; they might validly be resolved
4985 // by the call machinery.
4986 case BuiltinType::Overload:
4989 // Unbridged casts in ARC can be handled in some call positions and
4990 // should be left in place.
4991 case BuiltinType::ARCUnbridgedCast:
4994 // Pseudo-objects should be converted as soon as possible.
4995 case BuiltinType::PseudoObject:
4998 // The debugger mode could theoretically but currently does not try
4999 // to resolve unknown-typed arguments based on known parameter types.
5000 case BuiltinType::UnknownAny:
5003 // These are always invalid as call arguments and should be reported.
5004 case BuiltinType::BoundMember:
5005 case BuiltinType::BuiltinFn:
5006 case BuiltinType::OMPArraySection:
5010 llvm_unreachable("bad builtin type kind");
5013 /// Check an argument list for placeholders that we won't try to
5015 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5016 // Apply this processing to all the arguments at once instead of
5017 // dying at the first failure.
5018 bool hasInvalid = false;
5019 for (size_t i = 0, e = args.size(); i != e; i++) {
5020 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5021 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5022 if (result.isInvalid()) hasInvalid = true;
5023 else args[i] = result.get();
5024 } else if (hasInvalid) {
5025 (void)S.CorrectDelayedTyposInExpr(args[i]);
5031 /// If a builtin function has a pointer argument with no explicit address
5032 /// space, then it should be able to accept a pointer to any address
5033 /// space as input. In order to do this, we need to replace the
5034 /// standard builtin declaration with one that uses the same address space
5037 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5038 /// it does not contain any pointer arguments without
5039 /// an address space qualifer. Otherwise the rewritten
5040 /// FunctionDecl is returned.
5041 /// TODO: Handle pointer return types.
5042 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5043 const FunctionDecl *FDecl,
5044 MultiExprArg ArgExprs) {
5046 QualType DeclType = FDecl->getType();
5047 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5049 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5050 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5053 bool NeedsNewDecl = false;
5055 SmallVector<QualType, 8> OverloadParams;
5057 for (QualType ParamType : FT->param_types()) {
5059 // Convert array arguments to pointer to simplify type lookup.
5060 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
5061 QualType ArgType = Arg->getType();
5062 if (!ParamType->isPointerType() ||
5063 ParamType.getQualifiers().hasAddressSpace() ||
5064 !ArgType->isPointerType() ||
5065 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5066 OverloadParams.push_back(ParamType);
5070 NeedsNewDecl = true;
5071 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5073 QualType PointeeType = ParamType->getPointeeType();
5074 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5075 OverloadParams.push_back(Context.getPointerType(PointeeType));
5081 FunctionProtoType::ExtProtoInfo EPI;
5082 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5083 OverloadParams, EPI);
5084 DeclContext *Parent = Context.getTranslationUnitDecl();
5085 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5086 FDecl->getLocation(),
5087 FDecl->getLocation(),
5088 FDecl->getIdentifier(),
5092 /*hasPrototype=*/true);
5093 SmallVector<ParmVarDecl*, 16> Params;
5094 FT = cast<FunctionProtoType>(OverloadTy);
5095 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5096 QualType ParamType = FT->getParamType(i);
5098 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5099 SourceLocation(), nullptr, ParamType,
5100 /*TInfo=*/nullptr, SC_None, nullptr);
5101 Parm->setScopeInfo(0, i);
5102 Params.push_back(Parm);
5104 OverloadDecl->setParams(Params);
5105 return OverloadDecl;
5108 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5109 std::size_t NumArgs) {
5110 if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5111 /*PartialOverloading=*/false))
5112 return Callee->isVariadic();
5113 return Callee->getMinRequiredArguments() <= NumArgs;
5116 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5117 /// This provides the location of the left/right parens and a list of comma
5120 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5121 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5122 Expr *ExecConfig, bool IsExecConfig) {
5123 // Since this might be a postfix expression, get rid of ParenListExprs.
5124 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
5125 if (Result.isInvalid()) return ExprError();
5128 if (checkArgsForPlaceholders(*this, ArgExprs))
5131 if (getLangOpts().CPlusPlus) {
5132 // If this is a pseudo-destructor expression, build the call immediately.
5133 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5134 if (!ArgExprs.empty()) {
5135 // Pseudo-destructor calls should not have any arguments.
5136 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5137 << FixItHint::CreateRemoval(
5138 SourceRange(ArgExprs.front()->getLocStart(),
5139 ArgExprs.back()->getLocEnd()));
5142 return new (Context)
5143 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5145 if (Fn->getType() == Context.PseudoObjectTy) {
5146 ExprResult result = CheckPlaceholderExpr(Fn);
5147 if (result.isInvalid()) return ExprError();
5151 // Determine whether this is a dependent call inside a C++ template,
5152 // in which case we won't do any semantic analysis now.
5153 bool Dependent = false;
5154 if (Fn->isTypeDependent())
5156 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5161 return new (Context) CUDAKernelCallExpr(
5162 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5163 Context.DependentTy, VK_RValue, RParenLoc);
5165 return new (Context) CallExpr(
5166 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5170 // Determine whether this is a call to an object (C++ [over.call.object]).
5171 if (Fn->getType()->isRecordType())
5172 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
5175 if (Fn->getType() == Context.UnknownAnyTy) {
5176 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5177 if (result.isInvalid()) return ExprError();
5181 if (Fn->getType() == Context.BoundMemberTy) {
5182 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5186 // Check for overloaded calls. This can happen even in C due to extensions.
5187 if (Fn->getType() == Context.OverloadTy) {
5188 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5190 // We aren't supposed to apply this logic for if there's an '&' involved.
5191 if (!find.HasFormOfMemberPointer) {
5192 OverloadExpr *ovl = find.Expression;
5193 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5194 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
5195 RParenLoc, ExecConfig,
5196 /*AllowTypoCorrection=*/true,
5197 find.IsAddressOfOperand);
5198 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5202 // If we're directly calling a function, get the appropriate declaration.
5203 if (Fn->getType() == Context.UnknownAnyTy) {
5204 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5205 if (result.isInvalid()) return ExprError();
5209 Expr *NakedFn = Fn->IgnoreParens();
5211 bool CallingNDeclIndirectly = false;
5212 NamedDecl *NDecl = nullptr;
5213 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5214 if (UnOp->getOpcode() == UO_AddrOf) {
5215 CallingNDeclIndirectly = true;
5216 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5220 if (isa<DeclRefExpr>(NakedFn)) {
5221 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5223 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5224 if (FDecl && FDecl->getBuiltinID()) {
5225 // Rewrite the function decl for this builtin by replacing parameters
5226 // with no explicit address space with the address space of the arguments
5228 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5230 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
5231 SourceLocation(), FDecl, false,
5232 SourceLocation(), FDecl->getType(),
5233 Fn->getValueKind(), FDecl);
5236 } else if (isa<MemberExpr>(NakedFn))
5237 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5239 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5240 if (CallingNDeclIndirectly &&
5241 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5245 // CheckEnableIf assumes that the we're passing in a sane number of args for
5246 // FD, but that doesn't always hold true here. This is because, in some
5247 // cases, we'll emit a diag about an ill-formed function call, but then
5248 // we'll continue on as if the function call wasn't ill-formed. So, if the
5249 // number of args looks incorrect, don't do enable_if checks; we should've
5250 // already emitted an error about the bad call.
5251 if (FD->hasAttr<EnableIfAttr>() &&
5252 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5253 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5254 Diag(Fn->getLocStart(),
5255 isa<CXXMethodDecl>(FD) ?
5256 diag::err_ovl_no_viable_member_function_in_call :
5257 diag::err_ovl_no_viable_function_in_call)
5258 << FD << FD->getSourceRange();
5259 Diag(FD->getLocation(),
5260 diag::note_ovl_candidate_disabled_by_enable_if_attr)
5261 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5266 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5267 ExecConfig, IsExecConfig);
5270 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5272 /// __builtin_astype( value, dst type )
5274 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5275 SourceLocation BuiltinLoc,
5276 SourceLocation RParenLoc) {
5277 ExprValueKind VK = VK_RValue;
5278 ExprObjectKind OK = OK_Ordinary;
5279 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5280 QualType SrcTy = E->getType();
5281 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5282 return ExprError(Diag(BuiltinLoc,
5283 diag::err_invalid_astype_of_different_size)
5286 << E->getSourceRange());
5287 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5290 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5291 /// provided arguments.
5293 /// __builtin_convertvector( value, dst type )
5295 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5296 SourceLocation BuiltinLoc,
5297 SourceLocation RParenLoc) {
5298 TypeSourceInfo *TInfo;
5299 GetTypeFromParser(ParsedDestTy, &TInfo);
5300 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5303 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5304 /// i.e. an expression not of \p OverloadTy. The expression should
5305 /// unary-convert to an expression of function-pointer or
5306 /// block-pointer type.
5308 /// \param NDecl the declaration being called, if available
5310 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5311 SourceLocation LParenLoc,
5312 ArrayRef<Expr *> Args,
5313 SourceLocation RParenLoc,
5314 Expr *Config, bool IsExecConfig) {
5315 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5316 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5318 // Functions with 'interrupt' attribute cannot be called directly.
5319 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5320 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5324 // Promote the function operand.
5325 // We special-case function promotion here because we only allow promoting
5326 // builtin functions to function pointers in the callee of a call.
5329 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5330 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5331 CK_BuiltinFnToFnPtr).get();
5333 Result = CallExprUnaryConversions(Fn);
5335 if (Result.isInvalid())
5339 // Make the call expr early, before semantic checks. This guarantees cleanup
5340 // of arguments and function on error.
5343 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5344 cast<CallExpr>(Config), Args,
5345 Context.BoolTy, VK_RValue,
5348 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5349 VK_RValue, RParenLoc);
5351 if (!getLangOpts().CPlusPlus) {
5352 // C cannot always handle TypoExpr nodes in builtin calls and direct
5353 // function calls as their argument checking don't necessarily handle
5354 // dependent types properly, so make sure any TypoExprs have been
5356 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5357 if (!Result.isUsable()) return ExprError();
5358 TheCall = dyn_cast<CallExpr>(Result.get());
5359 if (!TheCall) return Result;
5360 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5363 // Bail out early if calling a builtin with custom typechecking.
5364 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5365 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5368 const FunctionType *FuncT;
5369 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5370 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5371 // have type pointer to function".
5372 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5374 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5375 << Fn->getType() << Fn->getSourceRange());
5376 } else if (const BlockPointerType *BPT =
5377 Fn->getType()->getAs<BlockPointerType>()) {
5378 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5380 // Handle calls to expressions of unknown-any type.
5381 if (Fn->getType() == Context.UnknownAnyTy) {
5382 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5383 if (rewrite.isInvalid()) return ExprError();
5385 TheCall->setCallee(Fn);
5389 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5390 << Fn->getType() << Fn->getSourceRange());
5393 if (getLangOpts().CUDA) {
5395 // CUDA: Kernel calls must be to global functions
5396 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5397 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5398 << FDecl->getName() << Fn->getSourceRange());
5400 // CUDA: Kernel function must have 'void' return type
5401 if (!FuncT->getReturnType()->isVoidType())
5402 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5403 << Fn->getType() << Fn->getSourceRange());
5405 // CUDA: Calls to global functions must be configured
5406 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5407 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5408 << FDecl->getName() << Fn->getSourceRange());
5412 // Check for a valid return type
5413 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5417 // We know the result type of the call, set it.
5418 TheCall->setType(FuncT->getCallResultType(Context));
5419 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5421 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5423 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5427 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5430 // Check if we have too few/too many template arguments, based
5431 // on our knowledge of the function definition.
5432 const FunctionDecl *Def = nullptr;
5433 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5434 Proto = Def->getType()->getAs<FunctionProtoType>();
5435 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5436 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5437 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5440 // If the function we're calling isn't a function prototype, but we have
5441 // a function prototype from a prior declaratiom, use that prototype.
5442 if (!FDecl->hasPrototype())
5443 Proto = FDecl->getType()->getAs<FunctionProtoType>();
5446 // Promote the arguments (C99 6.5.2.2p6).
5447 for (unsigned i = 0, e = Args.size(); i != e; i++) {
5448 Expr *Arg = Args[i];
5450 if (Proto && i < Proto->getNumParams()) {
5451 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5452 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5454 PerformCopyInitialization(Entity, SourceLocation(), Arg);
5455 if (ArgE.isInvalid())
5458 Arg = ArgE.getAs<Expr>();
5461 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5463 if (ArgE.isInvalid())
5466 Arg = ArgE.getAs<Expr>();
5469 if (RequireCompleteType(Arg->getLocStart(),
5471 diag::err_call_incomplete_argument, Arg))
5474 TheCall->setArg(i, Arg);
5478 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5479 if (!Method->isStatic())
5480 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5481 << Fn->getSourceRange());
5483 // Check for sentinels
5485 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5487 // Do special checking on direct calls to functions.
5489 if (CheckFunctionCall(FDecl, TheCall, Proto))
5493 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5495 if (CheckPointerCall(NDecl, TheCall, Proto))
5498 if (CheckOtherCall(TheCall, Proto))
5502 return MaybeBindToTemporary(TheCall);
5506 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5507 SourceLocation RParenLoc, Expr *InitExpr) {
5508 assert(Ty && "ActOnCompoundLiteral(): missing type");
5509 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5511 TypeSourceInfo *TInfo;
5512 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5514 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5516 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5520 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5521 SourceLocation RParenLoc, Expr *LiteralExpr) {
5522 QualType literalType = TInfo->getType();
5524 if (literalType->isArrayType()) {
5525 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5526 diag::err_illegal_decl_array_incomplete_type,
5527 SourceRange(LParenLoc,
5528 LiteralExpr->getSourceRange().getEnd())))
5530 if (literalType->isVariableArrayType())
5531 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5532 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5533 } else if (!literalType->isDependentType() &&
5534 RequireCompleteType(LParenLoc, literalType,
5535 diag::err_typecheck_decl_incomplete_type,
5536 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5539 InitializedEntity Entity
5540 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5541 InitializationKind Kind
5542 = InitializationKind::CreateCStyleCast(LParenLoc,
5543 SourceRange(LParenLoc, RParenLoc),
5545 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5546 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5548 if (Result.isInvalid())
5550 LiteralExpr = Result.get();
5552 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5554 !LiteralExpr->isTypeDependent() &&
5555 !LiteralExpr->isValueDependent() &&
5556 !literalType->isDependentType()) { // 6.5.2.5p3
5557 if (CheckForConstantInitializer(LiteralExpr, literalType))
5561 // In C, compound literals are l-values for some reason.
5562 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5564 return MaybeBindToTemporary(
5565 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5566 VK, LiteralExpr, isFileScope));
5570 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5571 SourceLocation RBraceLoc) {
5572 // Immediately handle non-overload placeholders. Overloads can be
5573 // resolved contextually, but everything else here can't.
5574 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5575 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5576 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5578 // Ignore failures; dropping the entire initializer list because
5579 // of one failure would be terrible for indexing/etc.
5580 if (result.isInvalid()) continue;
5582 InitArgList[I] = result.get();
5586 // Semantic analysis for initializers is done by ActOnDeclarator() and
5587 // CheckInitializer() - it requires knowledge of the object being intialized.
5589 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5591 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5595 /// Do an explicit extend of the given block pointer if we're in ARC.
5596 void Sema::maybeExtendBlockObject(ExprResult &E) {
5597 assert(E.get()->getType()->isBlockPointerType());
5598 assert(E.get()->isRValue());
5600 // Only do this in an r-value context.
5601 if (!getLangOpts().ObjCAutoRefCount) return;
5603 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5604 CK_ARCExtendBlockObject, E.get(),
5605 /*base path*/ nullptr, VK_RValue);
5606 Cleanup.setExprNeedsCleanups(true);
5609 /// Prepare a conversion of the given expression to an ObjC object
5611 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5612 QualType type = E.get()->getType();
5613 if (type->isObjCObjectPointerType()) {
5615 } else if (type->isBlockPointerType()) {
5616 maybeExtendBlockObject(E);
5617 return CK_BlockPointerToObjCPointerCast;
5619 assert(type->isPointerType());
5620 return CK_CPointerToObjCPointerCast;
5624 /// Prepares for a scalar cast, performing all the necessary stages
5625 /// except the final cast and returning the kind required.
5626 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5627 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5628 // Also, callers should have filtered out the invalid cases with
5629 // pointers. Everything else should be possible.
5631 QualType SrcTy = Src.get()->getType();
5632 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5635 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5636 case Type::STK_MemberPointer:
5637 llvm_unreachable("member pointer type in C");
5639 case Type::STK_CPointer:
5640 case Type::STK_BlockPointer:
5641 case Type::STK_ObjCObjectPointer:
5642 switch (DestTy->getScalarTypeKind()) {
5643 case Type::STK_CPointer: {
5644 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5645 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5646 if (SrcAS != DestAS)
5647 return CK_AddressSpaceConversion;
5650 case Type::STK_BlockPointer:
5651 return (SrcKind == Type::STK_BlockPointer
5652 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5653 case Type::STK_ObjCObjectPointer:
5654 if (SrcKind == Type::STK_ObjCObjectPointer)
5656 if (SrcKind == Type::STK_CPointer)
5657 return CK_CPointerToObjCPointerCast;
5658 maybeExtendBlockObject(Src);
5659 return CK_BlockPointerToObjCPointerCast;
5660 case Type::STK_Bool:
5661 return CK_PointerToBoolean;
5662 case Type::STK_Integral:
5663 return CK_PointerToIntegral;
5664 case Type::STK_Floating:
5665 case Type::STK_FloatingComplex:
5666 case Type::STK_IntegralComplex:
5667 case Type::STK_MemberPointer:
5668 llvm_unreachable("illegal cast from pointer");
5670 llvm_unreachable("Should have returned before this");
5672 case Type::STK_Bool: // casting from bool is like casting from an integer
5673 case Type::STK_Integral:
5674 switch (DestTy->getScalarTypeKind()) {
5675 case Type::STK_CPointer:
5676 case Type::STK_ObjCObjectPointer:
5677 case Type::STK_BlockPointer:
5678 if (Src.get()->isNullPointerConstant(Context,
5679 Expr::NPC_ValueDependentIsNull))
5680 return CK_NullToPointer;
5681 return CK_IntegralToPointer;
5682 case Type::STK_Bool:
5683 return CK_IntegralToBoolean;
5684 case Type::STK_Integral:
5685 return CK_IntegralCast;
5686 case Type::STK_Floating:
5687 return CK_IntegralToFloating;
5688 case Type::STK_IntegralComplex:
5689 Src = ImpCastExprToType(Src.get(),
5690 DestTy->castAs<ComplexType>()->getElementType(),
5692 return CK_IntegralRealToComplex;
5693 case Type::STK_FloatingComplex:
5694 Src = ImpCastExprToType(Src.get(),
5695 DestTy->castAs<ComplexType>()->getElementType(),
5696 CK_IntegralToFloating);
5697 return CK_FloatingRealToComplex;
5698 case Type::STK_MemberPointer:
5699 llvm_unreachable("member pointer type in C");
5701 llvm_unreachable("Should have returned before this");
5703 case Type::STK_Floating:
5704 switch (DestTy->getScalarTypeKind()) {
5705 case Type::STK_Floating:
5706 return CK_FloatingCast;
5707 case Type::STK_Bool:
5708 return CK_FloatingToBoolean;
5709 case Type::STK_Integral:
5710 return CK_FloatingToIntegral;
5711 case Type::STK_FloatingComplex:
5712 Src = ImpCastExprToType(Src.get(),
5713 DestTy->castAs<ComplexType>()->getElementType(),
5715 return CK_FloatingRealToComplex;
5716 case Type::STK_IntegralComplex:
5717 Src = ImpCastExprToType(Src.get(),
5718 DestTy->castAs<ComplexType>()->getElementType(),
5719 CK_FloatingToIntegral);
5720 return CK_IntegralRealToComplex;
5721 case Type::STK_CPointer:
5722 case Type::STK_ObjCObjectPointer:
5723 case Type::STK_BlockPointer:
5724 llvm_unreachable("valid float->pointer cast?");
5725 case Type::STK_MemberPointer:
5726 llvm_unreachable("member pointer type in C");
5728 llvm_unreachable("Should have returned before this");
5730 case Type::STK_FloatingComplex:
5731 switch (DestTy->getScalarTypeKind()) {
5732 case Type::STK_FloatingComplex:
5733 return CK_FloatingComplexCast;
5734 case Type::STK_IntegralComplex:
5735 return CK_FloatingComplexToIntegralComplex;
5736 case Type::STK_Floating: {
5737 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5738 if (Context.hasSameType(ET, DestTy))
5739 return CK_FloatingComplexToReal;
5740 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5741 return CK_FloatingCast;
5743 case Type::STK_Bool:
5744 return CK_FloatingComplexToBoolean;
5745 case Type::STK_Integral:
5746 Src = ImpCastExprToType(Src.get(),
5747 SrcTy->castAs<ComplexType>()->getElementType(),
5748 CK_FloatingComplexToReal);
5749 return CK_FloatingToIntegral;
5750 case Type::STK_CPointer:
5751 case Type::STK_ObjCObjectPointer:
5752 case Type::STK_BlockPointer:
5753 llvm_unreachable("valid complex float->pointer cast?");
5754 case Type::STK_MemberPointer:
5755 llvm_unreachable("member pointer type in C");
5757 llvm_unreachable("Should have returned before this");
5759 case Type::STK_IntegralComplex:
5760 switch (DestTy->getScalarTypeKind()) {
5761 case Type::STK_FloatingComplex:
5762 return CK_IntegralComplexToFloatingComplex;
5763 case Type::STK_IntegralComplex:
5764 return CK_IntegralComplexCast;
5765 case Type::STK_Integral: {
5766 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5767 if (Context.hasSameType(ET, DestTy))
5768 return CK_IntegralComplexToReal;
5769 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5770 return CK_IntegralCast;
5772 case Type::STK_Bool:
5773 return CK_IntegralComplexToBoolean;
5774 case Type::STK_Floating:
5775 Src = ImpCastExprToType(Src.get(),
5776 SrcTy->castAs<ComplexType>()->getElementType(),
5777 CK_IntegralComplexToReal);
5778 return CK_IntegralToFloating;
5779 case Type::STK_CPointer:
5780 case Type::STK_ObjCObjectPointer:
5781 case Type::STK_BlockPointer:
5782 llvm_unreachable("valid complex int->pointer cast?");
5783 case Type::STK_MemberPointer:
5784 llvm_unreachable("member pointer type in C");
5786 llvm_unreachable("Should have returned before this");
5789 llvm_unreachable("Unhandled scalar cast");
5792 static bool breakDownVectorType(QualType type, uint64_t &len,
5793 QualType &eltType) {
5794 // Vectors are simple.
5795 if (const VectorType *vecType = type->getAs<VectorType>()) {
5796 len = vecType->getNumElements();
5797 eltType = vecType->getElementType();
5798 assert(eltType->isScalarType());
5802 // We allow lax conversion to and from non-vector types, but only if
5803 // they're real types (i.e. non-complex, non-pointer scalar types).
5804 if (!type->isRealType()) return false;
5811 /// Are the two types lax-compatible vector types? That is, given
5812 /// that one of them is a vector, do they have equal storage sizes,
5813 /// where the storage size is the number of elements times the element
5816 /// This will also return false if either of the types is neither a
5817 /// vector nor a real type.
5818 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5819 assert(destTy->isVectorType() || srcTy->isVectorType());
5821 // Disallow lax conversions between scalars and ExtVectors (these
5822 // conversions are allowed for other vector types because common headers
5823 // depend on them). Most scalar OP ExtVector cases are handled by the
5824 // splat path anyway, which does what we want (convert, not bitcast).
5825 // What this rules out for ExtVectors is crazy things like char4*float.
5826 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5827 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5829 uint64_t srcLen, destLen;
5830 QualType srcEltTy, destEltTy;
5831 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5832 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5834 // ASTContext::getTypeSize will return the size rounded up to a
5835 // power of 2, so instead of using that, we need to use the raw
5836 // element size multiplied by the element count.
5837 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5838 uint64_t destEltSize = Context.getTypeSize(destEltTy);
5840 return (srcLen * srcEltSize == destLen * destEltSize);
5843 /// Is this a legal conversion between two types, one of which is
5844 /// known to be a vector type?
5845 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5846 assert(destTy->isVectorType() || srcTy->isVectorType());
5848 if (!Context.getLangOpts().LaxVectorConversions)
5850 return areLaxCompatibleVectorTypes(srcTy, destTy);
5853 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5855 assert(VectorTy->isVectorType() && "Not a vector type!");
5857 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5858 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5859 return Diag(R.getBegin(),
5860 Ty->isVectorType() ?
5861 diag::err_invalid_conversion_between_vectors :
5862 diag::err_invalid_conversion_between_vector_and_integer)
5863 << VectorTy << Ty << R;
5865 return Diag(R.getBegin(),
5866 diag::err_invalid_conversion_between_vector_and_scalar)
5867 << VectorTy << Ty << R;
5873 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5874 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5876 if (DestElemTy == SplattedExpr->getType())
5877 return SplattedExpr;
5879 assert(DestElemTy->isFloatingType() ||
5880 DestElemTy->isIntegralOrEnumerationType());
5883 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5884 // OpenCL requires that we convert `true` boolean expressions to -1, but
5885 // only when splatting vectors.
5886 if (DestElemTy->isFloatingType()) {
5887 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5888 // in two steps: boolean to signed integral, then to floating.
5889 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5890 CK_BooleanToSignedIntegral);
5891 SplattedExpr = CastExprRes.get();
5892 CK = CK_IntegralToFloating;
5894 CK = CK_BooleanToSignedIntegral;
5897 ExprResult CastExprRes = SplattedExpr;
5898 CK = PrepareScalarCast(CastExprRes, DestElemTy);
5899 if (CastExprRes.isInvalid())
5901 SplattedExpr = CastExprRes.get();
5903 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5906 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5907 Expr *CastExpr, CastKind &Kind) {
5908 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5910 QualType SrcTy = CastExpr->getType();
5912 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5913 // an ExtVectorType.
5914 // In OpenCL, casts between vectors of different types are not allowed.
5915 // (See OpenCL 6.2).
5916 if (SrcTy->isVectorType()) {
5917 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5918 || (getLangOpts().OpenCL &&
5919 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5920 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5921 << DestTy << SrcTy << R;
5928 // All non-pointer scalars can be cast to ExtVector type. The appropriate
5929 // conversion will take place first from scalar to elt type, and then
5930 // splat from elt type to vector.
5931 if (SrcTy->isPointerType())
5932 return Diag(R.getBegin(),
5933 diag::err_invalid_conversion_between_vector_and_scalar)
5934 << DestTy << SrcTy << R;
5936 Kind = CK_VectorSplat;
5937 return prepareVectorSplat(DestTy, CastExpr);
5941 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5942 Declarator &D, ParsedType &Ty,
5943 SourceLocation RParenLoc, Expr *CastExpr) {
5944 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5945 "ActOnCastExpr(): missing type or expr");
5947 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5948 if (D.isInvalidType())
5951 if (getLangOpts().CPlusPlus) {
5952 // Check that there are no default arguments (C++ only).
5953 CheckExtraCXXDefaultArguments(D);
5955 // Make sure any TypoExprs have been dealt with.
5956 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5957 if (!Res.isUsable())
5959 CastExpr = Res.get();
5962 checkUnusedDeclAttributes(D);
5964 QualType castType = castTInfo->getType();
5965 Ty = CreateParsedType(castType, castTInfo);
5967 bool isVectorLiteral = false;
5969 // Check for an altivec or OpenCL literal,
5970 // i.e. all the elements are integer constants.
5971 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5972 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5973 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5974 && castType->isVectorType() && (PE || PLE)) {
5975 if (PLE && PLE->getNumExprs() == 0) {
5976 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5979 if (PE || PLE->getNumExprs() == 1) {
5980 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5981 if (!E->getType()->isVectorType())
5982 isVectorLiteral = true;
5985 isVectorLiteral = true;
5988 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5989 // then handle it as such.
5990 if (isVectorLiteral)
5991 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5993 // If the Expr being casted is a ParenListExpr, handle it specially.
5994 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5995 // sequence of BinOp comma operators.
5996 if (isa<ParenListExpr>(CastExpr)) {
5997 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5998 if (Result.isInvalid()) return ExprError();
5999 CastExpr = Result.get();
6002 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6003 !getSourceManager().isInSystemMacro(LParenLoc))
6004 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6006 CheckTollFreeBridgeCast(castType, CastExpr);
6008 CheckObjCBridgeRelatedCast(castType, CastExpr);
6010 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6013 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6014 SourceLocation RParenLoc, Expr *E,
6015 TypeSourceInfo *TInfo) {
6016 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6017 "Expected paren or paren list expression");
6022 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6023 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6024 LiteralLParenLoc = PE->getLParenLoc();
6025 LiteralRParenLoc = PE->getRParenLoc();
6026 exprs = PE->getExprs();
6027 numExprs = PE->getNumExprs();
6028 } else { // isa<ParenExpr> by assertion at function entrance
6029 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6030 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6031 subExpr = cast<ParenExpr>(E)->getSubExpr();
6036 QualType Ty = TInfo->getType();
6037 assert(Ty->isVectorType() && "Expected vector type");
6039 SmallVector<Expr *, 8> initExprs;
6040 const VectorType *VTy = Ty->getAs<VectorType>();
6041 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6043 // '(...)' form of vector initialization in AltiVec: the number of
6044 // initializers must be one or must match the size of the vector.
6045 // If a single value is specified in the initializer then it will be
6046 // replicated to all the components of the vector
6047 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6048 // The number of initializers must be one or must match the size of the
6049 // vector. If a single value is specified in the initializer then it will
6050 // be replicated to all the components of the vector
6051 if (numExprs == 1) {
6052 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6053 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6054 if (Literal.isInvalid())
6056 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6057 PrepareScalarCast(Literal, ElemTy));
6058 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6060 else if (numExprs < numElems) {
6061 Diag(E->getExprLoc(),
6062 diag::err_incorrect_number_of_vector_initializers);
6066 initExprs.append(exprs, exprs + numExprs);
6069 // For OpenCL, when the number of initializers is a single value,
6070 // it will be replicated to all components of the vector.
6071 if (getLangOpts().OpenCL &&
6072 VTy->getVectorKind() == VectorType::GenericVector &&
6074 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6075 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6076 if (Literal.isInvalid())
6078 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6079 PrepareScalarCast(Literal, ElemTy));
6080 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6083 initExprs.append(exprs, exprs + numExprs);
6085 // FIXME: This means that pretty-printing the final AST will produce curly
6086 // braces instead of the original commas.
6087 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6088 initExprs, LiteralRParenLoc);
6090 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6093 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6094 /// the ParenListExpr into a sequence of comma binary operators.
6096 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6097 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6101 ExprResult Result(E->getExpr(0));
6103 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6104 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6107 if (Result.isInvalid()) return ExprError();
6109 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6112 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6115 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6119 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6120 /// constant and the other is not a pointer. Returns true if a diagnostic is
6122 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6123 SourceLocation QuestionLoc) {
6124 Expr *NullExpr = LHSExpr;
6125 Expr *NonPointerExpr = RHSExpr;
6126 Expr::NullPointerConstantKind NullKind =
6127 NullExpr->isNullPointerConstant(Context,
6128 Expr::NPC_ValueDependentIsNotNull);
6130 if (NullKind == Expr::NPCK_NotNull) {
6132 NonPointerExpr = LHSExpr;
6134 NullExpr->isNullPointerConstant(Context,
6135 Expr::NPC_ValueDependentIsNotNull);
6138 if (NullKind == Expr::NPCK_NotNull)
6141 if (NullKind == Expr::NPCK_ZeroExpression)
6144 if (NullKind == Expr::NPCK_ZeroLiteral) {
6145 // In this case, check to make sure that we got here from a "NULL"
6146 // string in the source code.
6147 NullExpr = NullExpr->IgnoreParenImpCasts();
6148 SourceLocation loc = NullExpr->getExprLoc();
6149 if (!findMacroSpelling(loc, "NULL"))
6153 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6154 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6155 << NonPointerExpr->getType() << DiagType
6156 << NonPointerExpr->getSourceRange();
6160 /// \brief Return false if the condition expression is valid, true otherwise.
6161 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6162 QualType CondTy = Cond->getType();
6164 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6165 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6166 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6167 << CondTy << Cond->getSourceRange();
6172 if (CondTy->isScalarType()) return false;
6174 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6175 << CondTy << Cond->getSourceRange();
6179 /// \brief Handle when one or both operands are void type.
6180 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6182 Expr *LHSExpr = LHS.get();
6183 Expr *RHSExpr = RHS.get();
6185 if (!LHSExpr->getType()->isVoidType())
6186 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6187 << RHSExpr->getSourceRange();
6188 if (!RHSExpr->getType()->isVoidType())
6189 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6190 << LHSExpr->getSourceRange();
6191 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6192 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6193 return S.Context.VoidTy;
6196 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6198 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6199 QualType PointerTy) {
6200 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6201 !NullExpr.get()->isNullPointerConstant(S.Context,
6202 Expr::NPC_ValueDependentIsNull))
6205 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6209 /// \brief Checks compatibility between two pointers and return the resulting
6211 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6213 SourceLocation Loc) {
6214 QualType LHSTy = LHS.get()->getType();
6215 QualType RHSTy = RHS.get()->getType();
6217 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6218 // Two identical pointers types are always compatible.
6222 QualType lhptee, rhptee;
6224 // Get the pointee types.
6225 bool IsBlockPointer = false;
6226 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6227 lhptee = LHSBTy->getPointeeType();
6228 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6229 IsBlockPointer = true;
6231 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6232 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6235 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6236 // differently qualified versions of compatible types, the result type is
6237 // a pointer to an appropriately qualified version of the composite
6240 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6241 // clause doesn't make sense for our extensions. E.g. address space 2 should
6242 // be incompatible with address space 3: they may live on different devices or
6244 Qualifiers lhQual = lhptee.getQualifiers();
6245 Qualifiers rhQual = rhptee.getQualifiers();
6247 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6248 lhQual.removeCVRQualifiers();
6249 rhQual.removeCVRQualifiers();
6251 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6252 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6255 // 1. If LHS and RHS types match exactly and:
6256 // (a) AS match => use standard C rules, no bitcast or addrspacecast
6257 // (b) AS overlap => generate addrspacecast
6258 // (c) AS don't overlap => give an error
6259 // 2. if LHS and RHS types don't match:
6260 // (a) AS match => use standard C rules, generate bitcast
6261 // (b) AS overlap => generate addrspacecast instead of bitcast
6262 // (c) AS don't overlap => give an error
6264 // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6265 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6267 // OpenCL cases 1c, 2a, 2b, and 2c.
6268 if (CompositeTy.isNull()) {
6269 // In this situation, we assume void* type. No especially good
6270 // reason, but this is what gcc does, and we do have to pick
6271 // to get a consistent AST.
6272 QualType incompatTy;
6273 if (S.getLangOpts().OpenCL) {
6274 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6275 // spaces is disallowed.
6276 unsigned ResultAddrSpace;
6277 if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6279 ResultAddrSpace = lhQual.getAddressSpace();
6280 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6282 ResultAddrSpace = rhQual.getAddressSpace();
6286 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6287 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6288 << RHS.get()->getSourceRange();
6292 // Continue handling cases 2a and 2b.
6293 incompatTy = S.Context.getPointerType(
6294 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6295 LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6296 (lhQual.getAddressSpace() != ResultAddrSpace)
6297 ? CK_AddressSpaceConversion /* 2b */
6298 : CK_BitCast /* 2a */);
6299 RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6300 (rhQual.getAddressSpace() != ResultAddrSpace)
6301 ? CK_AddressSpaceConversion /* 2b */
6302 : CK_BitCast /* 2a */);
6304 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6305 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6306 << RHS.get()->getSourceRange();
6307 incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6308 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6309 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6314 // The pointer types are compatible.
6315 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6316 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6318 ResultTy = S.Context.getBlockPointerType(ResultTy);
6320 // Cases 1a and 1b for OpenCL.
6321 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6322 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6323 ? CK_BitCast /* 1a */
6324 : CK_AddressSpaceConversion /* 1b */;
6325 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6326 ? CK_BitCast /* 1a */
6327 : CK_AddressSpaceConversion /* 1b */;
6328 ResultTy = S.Context.getPointerType(ResultTy);
6331 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6332 // if the target type does not change.
6333 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6334 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6338 /// \brief Return the resulting type when the operands are both block pointers.
6339 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6342 SourceLocation Loc) {
6343 QualType LHSTy = LHS.get()->getType();
6344 QualType RHSTy = RHS.get()->getType();
6346 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6347 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6348 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6349 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6350 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6353 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6354 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6355 << RHS.get()->getSourceRange();
6359 // We have 2 block pointer types.
6360 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6363 /// \brief Return the resulting type when the operands are both pointers.
6365 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6367 SourceLocation Loc) {
6368 // get the pointer types
6369 QualType LHSTy = LHS.get()->getType();
6370 QualType RHSTy = RHS.get()->getType();
6372 // get the "pointed to" types
6373 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6374 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6376 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6377 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6378 // Figure out necessary qualifiers (C99 6.5.15p6)
6379 QualType destPointee
6380 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6381 QualType destType = S.Context.getPointerType(destPointee);
6382 // Add qualifiers if necessary.
6383 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6384 // Promote to void*.
6385 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6388 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6389 QualType destPointee
6390 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6391 QualType destType = S.Context.getPointerType(destPointee);
6392 // Add qualifiers if necessary.
6393 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6394 // Promote to void*.
6395 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6399 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6402 /// \brief Return false if the first expression is not an integer and the second
6403 /// expression is not a pointer, true otherwise.
6404 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6405 Expr* PointerExpr, SourceLocation Loc,
6406 bool IsIntFirstExpr) {
6407 if (!PointerExpr->getType()->isPointerType() ||
6408 !Int.get()->getType()->isIntegerType())
6411 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6412 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6414 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6415 << Expr1->getType() << Expr2->getType()
6416 << Expr1->getSourceRange() << Expr2->getSourceRange();
6417 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6418 CK_IntegralToPointer);
6422 /// \brief Simple conversion between integer and floating point types.
6424 /// Used when handling the OpenCL conditional operator where the
6425 /// condition is a vector while the other operands are scalar.
6427 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6428 /// types are either integer or floating type. Between the two
6429 /// operands, the type with the higher rank is defined as the "result
6430 /// type". The other operand needs to be promoted to the same type. No
6431 /// other type promotion is allowed. We cannot use
6432 /// UsualArithmeticConversions() for this purpose, since it always
6433 /// promotes promotable types.
6434 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6436 SourceLocation QuestionLoc) {
6437 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6438 if (LHS.isInvalid())
6440 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6441 if (RHS.isInvalid())
6444 // For conversion purposes, we ignore any qualifiers.
6445 // For example, "const float" and "float" are equivalent.
6447 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6449 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6451 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6452 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6453 << LHSType << LHS.get()->getSourceRange();
6457 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6458 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6459 << RHSType << RHS.get()->getSourceRange();
6463 // If both types are identical, no conversion is needed.
6464 if (LHSType == RHSType)
6467 // Now handle "real" floating types (i.e. float, double, long double).
6468 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6469 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6470 /*IsCompAssign = */ false);
6472 // Finally, we have two differing integer types.
6473 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6474 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6477 /// \brief Convert scalar operands to a vector that matches the
6478 /// condition in length.
6480 /// Used when handling the OpenCL conditional operator where the
6481 /// condition is a vector while the other operands are scalar.
6483 /// We first compute the "result type" for the scalar operands
6484 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6485 /// into a vector of that type where the length matches the condition
6486 /// vector type. s6.11.6 requires that the element types of the result
6487 /// and the condition must have the same number of bits.
6489 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6490 QualType CondTy, SourceLocation QuestionLoc) {
6491 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6492 if (ResTy.isNull()) return QualType();
6494 const VectorType *CV = CondTy->getAs<VectorType>();
6497 // Determine the vector result type
6498 unsigned NumElements = CV->getNumElements();
6499 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6501 // Ensure that all types have the same number of bits
6502 if (S.Context.getTypeSize(CV->getElementType())
6503 != S.Context.getTypeSize(ResTy)) {
6504 // Since VectorTy is created internally, it does not pretty print
6505 // with an OpenCL name. Instead, we just print a description.
6506 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6507 SmallString<64> Str;
6508 llvm::raw_svector_ostream OS(Str);
6509 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6510 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6511 << CondTy << OS.str();
6515 // Convert operands to the vector result type
6516 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6517 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6522 /// \brief Return false if this is a valid OpenCL condition vector
6523 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6524 SourceLocation QuestionLoc) {
6525 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6527 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6529 QualType EleTy = CondTy->getElementType();
6530 if (EleTy->isIntegerType()) return false;
6532 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6533 << Cond->getType() << Cond->getSourceRange();
6537 /// \brief Return false if the vector condition type and the vector
6538 /// result type are compatible.
6540 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6541 /// number of elements, and their element types have the same number
6543 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6544 SourceLocation QuestionLoc) {
6545 const VectorType *CV = CondTy->getAs<VectorType>();
6546 const VectorType *RV = VecResTy->getAs<VectorType>();
6549 if (CV->getNumElements() != RV->getNumElements()) {
6550 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6551 << CondTy << VecResTy;
6555 QualType CVE = CV->getElementType();
6556 QualType RVE = RV->getElementType();
6558 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6559 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6560 << CondTy << VecResTy;
6567 /// \brief Return the resulting type for the conditional operator in
6568 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6569 /// s6.3.i) when the condition is a vector type.
6571 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6572 ExprResult &LHS, ExprResult &RHS,
6573 SourceLocation QuestionLoc) {
6574 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6575 if (Cond.isInvalid())
6577 QualType CondTy = Cond.get()->getType();
6579 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6582 // If either operand is a vector then find the vector type of the
6583 // result as specified in OpenCL v1.1 s6.3.i.
6584 if (LHS.get()->getType()->isVectorType() ||
6585 RHS.get()->getType()->isVectorType()) {
6586 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6587 /*isCompAssign*/false,
6588 /*AllowBothBool*/true,
6589 /*AllowBoolConversions*/false);
6590 if (VecResTy.isNull()) return QualType();
6591 // The result type must match the condition type as specified in
6592 // OpenCL v1.1 s6.11.6.
6593 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6598 // Both operands are scalar.
6599 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6602 /// \brief Return true if the Expr is block type
6603 static bool checkBlockType(Sema &S, const Expr *E) {
6604 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6605 QualType Ty = CE->getCallee()->getType();
6606 if (Ty->isBlockPointerType()) {
6607 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6614 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6615 /// In that case, LHS = cond.
6617 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6618 ExprResult &RHS, ExprValueKind &VK,
6620 SourceLocation QuestionLoc) {
6622 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6623 if (!LHSResult.isUsable()) return QualType();
6626 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6627 if (!RHSResult.isUsable()) return QualType();
6630 // C++ is sufficiently different to merit its own checker.
6631 if (getLangOpts().CPlusPlus)
6632 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6637 // The OpenCL operator with a vector condition is sufficiently
6638 // different to merit its own checker.
6639 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6640 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6642 // First, check the condition.
6643 Cond = UsualUnaryConversions(Cond.get());
6644 if (Cond.isInvalid())
6646 if (checkCondition(*this, Cond.get(), QuestionLoc))
6649 // Now check the two expressions.
6650 if (LHS.get()->getType()->isVectorType() ||
6651 RHS.get()->getType()->isVectorType())
6652 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6653 /*AllowBothBool*/true,
6654 /*AllowBoolConversions*/false);
6656 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6657 if (LHS.isInvalid() || RHS.isInvalid())
6660 QualType LHSTy = LHS.get()->getType();
6661 QualType RHSTy = RHS.get()->getType();
6663 // Diagnose attempts to convert between __float128 and long double where
6664 // such conversions currently can't be handled.
6665 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6667 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6668 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6672 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6673 // selection operator (?:).
6674 if (getLangOpts().OpenCL &&
6675 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6679 // If both operands have arithmetic type, do the usual arithmetic conversions
6680 // to find a common type: C99 6.5.15p3,5.
6681 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6682 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6683 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6688 // If both operands are the same structure or union type, the result is that
6690 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6691 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6692 if (LHSRT->getDecl() == RHSRT->getDecl())
6693 // "If both the operands have structure or union type, the result has
6694 // that type." This implies that CV qualifiers are dropped.
6695 return LHSTy.getUnqualifiedType();
6696 // FIXME: Type of conditional expression must be complete in C mode.
6699 // C99 6.5.15p5: "If both operands have void type, the result has void type."
6700 // The following || allows only one side to be void (a GCC-ism).
6701 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6702 return checkConditionalVoidType(*this, LHS, RHS);
6705 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6706 // the type of the other operand."
6707 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6708 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6710 // All objective-c pointer type analysis is done here.
6711 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6713 if (LHS.isInvalid() || RHS.isInvalid())
6715 if (!compositeType.isNull())
6716 return compositeType;
6719 // Handle block pointer types.
6720 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6721 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6724 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6725 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6726 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6729 // GCC compatibility: soften pointer/integer mismatch. Note that
6730 // null pointers have been filtered out by this point.
6731 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6732 /*isIntFirstExpr=*/true))
6734 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6735 /*isIntFirstExpr=*/false))
6738 // Emit a better diagnostic if one of the expressions is a null pointer
6739 // constant and the other is not a pointer type. In this case, the user most
6740 // likely forgot to take the address of the other expression.
6741 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6744 // Otherwise, the operands are not compatible.
6745 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6746 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6747 << RHS.get()->getSourceRange();
6751 /// FindCompositeObjCPointerType - Helper method to find composite type of
6752 /// two objective-c pointer types of the two input expressions.
6753 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6754 SourceLocation QuestionLoc) {
6755 QualType LHSTy = LHS.get()->getType();
6756 QualType RHSTy = RHS.get()->getType();
6758 // Handle things like Class and struct objc_class*. Here we case the result
6759 // to the pseudo-builtin, because that will be implicitly cast back to the
6760 // redefinition type if an attempt is made to access its fields.
6761 if (LHSTy->isObjCClassType() &&
6762 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6763 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6766 if (RHSTy->isObjCClassType() &&
6767 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6768 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6771 // And the same for struct objc_object* / id
6772 if (LHSTy->isObjCIdType() &&
6773 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6774 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6777 if (RHSTy->isObjCIdType() &&
6778 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6779 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6782 // And the same for struct objc_selector* / SEL
6783 if (Context.isObjCSelType(LHSTy) &&
6784 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6785 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6788 if (Context.isObjCSelType(RHSTy) &&
6789 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6790 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6793 // Check constraints for Objective-C object pointers types.
6794 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6796 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6797 // Two identical object pointer types are always compatible.
6800 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6801 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6802 QualType compositeType = LHSTy;
6804 // If both operands are interfaces and either operand can be
6805 // assigned to the other, use that type as the composite
6806 // type. This allows
6807 // xxx ? (A*) a : (B*) b
6808 // where B is a subclass of A.
6810 // Additionally, as for assignment, if either type is 'id'
6811 // allow silent coercion. Finally, if the types are
6812 // incompatible then make sure to use 'id' as the composite
6813 // type so the result is acceptable for sending messages to.
6815 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6816 // It could return the composite type.
6817 if (!(compositeType =
6818 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6819 // Nothing more to do.
6820 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6821 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6822 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6823 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6824 } else if ((LHSTy->isObjCQualifiedIdType() ||
6825 RHSTy->isObjCQualifiedIdType()) &&
6826 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6827 // Need to handle "id<xx>" explicitly.
6828 // GCC allows qualified id and any Objective-C type to devolve to
6829 // id. Currently localizing to here until clear this should be
6830 // part of ObjCQualifiedIdTypesAreCompatible.
6831 compositeType = Context.getObjCIdType();
6832 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6833 compositeType = Context.getObjCIdType();
6835 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6837 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6838 QualType incompatTy = Context.getObjCIdType();
6839 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6840 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6843 // The object pointer types are compatible.
6844 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6845 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6846 return compositeType;
6848 // Check Objective-C object pointer types and 'void *'
6849 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6850 if (getLangOpts().ObjCAutoRefCount) {
6851 // ARC forbids the implicit conversion of object pointers to 'void *',
6852 // so these types are not compatible.
6853 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6854 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6858 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6859 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6860 QualType destPointee
6861 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6862 QualType destType = Context.getPointerType(destPointee);
6863 // Add qualifiers if necessary.
6864 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6865 // Promote to void*.
6866 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6869 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6870 if (getLangOpts().ObjCAutoRefCount) {
6871 // ARC forbids the implicit conversion of object pointers to 'void *',
6872 // so these types are not compatible.
6873 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6874 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6878 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6879 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6880 QualType destPointee
6881 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6882 QualType destType = Context.getPointerType(destPointee);
6883 // Add qualifiers if necessary.
6884 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6885 // Promote to void*.
6886 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6892 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6893 /// ParenRange in parentheses.
6894 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6895 const PartialDiagnostic &Note,
6896 SourceRange ParenRange) {
6897 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6898 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6900 Self.Diag(Loc, Note)
6901 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6902 << FixItHint::CreateInsertion(EndLoc, ")");
6904 // We can't display the parentheses, so just show the bare note.
6905 Self.Diag(Loc, Note) << ParenRange;
6909 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6910 return BinaryOperator::isAdditiveOp(Opc) ||
6911 BinaryOperator::isMultiplicativeOp(Opc) ||
6912 BinaryOperator::isShiftOp(Opc);
6915 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6916 /// expression, either using a built-in or overloaded operator,
6917 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6919 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6921 // Don't strip parenthesis: we should not warn if E is in parenthesis.
6922 E = E->IgnoreImpCasts();
6923 E = E->IgnoreConversionOperator();
6924 E = E->IgnoreImpCasts();
6926 // Built-in binary operator.
6927 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6928 if (IsArithmeticOp(OP->getOpcode())) {
6929 *Opcode = OP->getOpcode();
6930 *RHSExprs = OP->getRHS();
6935 // Overloaded operator.
6936 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6937 if (Call->getNumArgs() != 2)
6940 // Make sure this is really a binary operator that is safe to pass into
6941 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6942 OverloadedOperatorKind OO = Call->getOperator();
6943 if (OO < OO_Plus || OO > OO_Arrow ||
6944 OO == OO_PlusPlus || OO == OO_MinusMinus)
6947 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6948 if (IsArithmeticOp(OpKind)) {
6950 *RHSExprs = Call->getArg(1);
6958 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6959 /// or is a logical expression such as (x==y) which has int type, but is
6960 /// commonly interpreted as boolean.
6961 static bool ExprLooksBoolean(Expr *E) {
6962 E = E->IgnoreParenImpCasts();
6964 if (E->getType()->isBooleanType())
6966 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6967 return OP->isComparisonOp() || OP->isLogicalOp();
6968 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6969 return OP->getOpcode() == UO_LNot;
6970 if (E->getType()->isPointerType())
6976 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6977 /// and binary operator are mixed in a way that suggests the programmer assumed
6978 /// the conditional operator has higher precedence, for example:
6979 /// "int x = a + someBinaryCondition ? 1 : 2".
6980 static void DiagnoseConditionalPrecedence(Sema &Self,
6981 SourceLocation OpLoc,
6985 BinaryOperatorKind CondOpcode;
6988 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6990 if (!ExprLooksBoolean(CondRHS))
6993 // The condition is an arithmetic binary expression, with a right-
6994 // hand side that looks boolean, so warn.
6996 Self.Diag(OpLoc, diag::warn_precedence_conditional)
6997 << Condition->getSourceRange()
6998 << BinaryOperator::getOpcodeStr(CondOpcode);
7000 SuggestParentheses(Self, OpLoc,
7001 Self.PDiag(diag::note_precedence_silence)
7002 << BinaryOperator::getOpcodeStr(CondOpcode),
7003 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7005 SuggestParentheses(Self, OpLoc,
7006 Self.PDiag(diag::note_precedence_conditional_first),
7007 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7010 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7011 /// in the case of a the GNU conditional expr extension.
7012 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7013 SourceLocation ColonLoc,
7014 Expr *CondExpr, Expr *LHSExpr,
7016 if (!getLangOpts().CPlusPlus) {
7017 // C cannot handle TypoExpr nodes in the condition because it
7018 // doesn't handle dependent types properly, so make sure any TypoExprs have
7019 // been dealt with before checking the operands.
7020 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7021 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7022 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7024 if (!CondResult.isUsable())
7028 if (!LHSResult.isUsable())
7032 if (!RHSResult.isUsable())
7035 CondExpr = CondResult.get();
7036 LHSExpr = LHSResult.get();
7037 RHSExpr = RHSResult.get();
7040 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7041 // was the condition.
7042 OpaqueValueExpr *opaqueValue = nullptr;
7043 Expr *commonExpr = nullptr;
7045 commonExpr = CondExpr;
7046 // Lower out placeholder types first. This is important so that we don't
7047 // try to capture a placeholder. This happens in few cases in C++; such
7048 // as Objective-C++'s dictionary subscripting syntax.
7049 if (commonExpr->hasPlaceholderType()) {
7050 ExprResult result = CheckPlaceholderExpr(commonExpr);
7051 if (!result.isUsable()) return ExprError();
7052 commonExpr = result.get();
7054 // We usually want to apply unary conversions *before* saving, except
7055 // in the special case of a C++ l-value conditional.
7056 if (!(getLangOpts().CPlusPlus
7057 && !commonExpr->isTypeDependent()
7058 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7059 && commonExpr->isGLValue()
7060 && commonExpr->isOrdinaryOrBitFieldObject()
7061 && RHSExpr->isOrdinaryOrBitFieldObject()
7062 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7063 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7064 if (commonRes.isInvalid())
7066 commonExpr = commonRes.get();
7069 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7070 commonExpr->getType(),
7071 commonExpr->getValueKind(),
7072 commonExpr->getObjectKind(),
7074 LHSExpr = CondExpr = opaqueValue;
7077 ExprValueKind VK = VK_RValue;
7078 ExprObjectKind OK = OK_Ordinary;
7079 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7080 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7081 VK, OK, QuestionLoc);
7082 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7086 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7089 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7092 return new (Context)
7093 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7094 RHS.get(), result, VK, OK);
7096 return new (Context) BinaryConditionalOperator(
7097 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7098 ColonLoc, result, VK, OK);
7101 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7102 // being closely modeled after the C99 spec:-). The odd characteristic of this
7103 // routine is it effectively iqnores the qualifiers on the top level pointee.
7104 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7105 // FIXME: add a couple examples in this comment.
7106 static Sema::AssignConvertType
7107 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7108 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7109 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7111 // get the "pointed to" type (ignoring qualifiers at the top level)
7112 const Type *lhptee, *rhptee;
7113 Qualifiers lhq, rhq;
7114 std::tie(lhptee, lhq) =
7115 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7116 std::tie(rhptee, rhq) =
7117 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7119 Sema::AssignConvertType ConvTy = Sema::Compatible;
7121 // C99 6.5.16.1p1: This following citation is common to constraints
7122 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7123 // qualifiers of the type *pointed to* by the right;
7125 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7126 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7127 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7128 // Ignore lifetime for further calculation.
7129 lhq.removeObjCLifetime();
7130 rhq.removeObjCLifetime();
7133 if (!lhq.compatiblyIncludes(rhq)) {
7134 // Treat address-space mismatches as fatal. TODO: address subspaces
7135 if (!lhq.isAddressSpaceSupersetOf(rhq))
7136 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7138 // It's okay to add or remove GC or lifetime qualifiers when converting to
7140 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7141 .compatiblyIncludes(
7142 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7143 && (lhptee->isVoidType() || rhptee->isVoidType()))
7146 // Treat lifetime mismatches as fatal.
7147 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7148 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7150 // For GCC/MS compatibility, other qualifier mismatches are treated
7151 // as still compatible in C.
7152 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7155 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7156 // incomplete type and the other is a pointer to a qualified or unqualified
7157 // version of void...
7158 if (lhptee->isVoidType()) {
7159 if (rhptee->isIncompleteOrObjectType())
7162 // As an extension, we allow cast to/from void* to function pointer.
7163 assert(rhptee->isFunctionType());
7164 return Sema::FunctionVoidPointer;
7167 if (rhptee->isVoidType()) {
7168 if (lhptee->isIncompleteOrObjectType())
7171 // As an extension, we allow cast to/from void* to function pointer.
7172 assert(lhptee->isFunctionType());
7173 return Sema::FunctionVoidPointer;
7176 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7177 // unqualified versions of compatible types, ...
7178 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7179 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7180 // Check if the pointee types are compatible ignoring the sign.
7181 // We explicitly check for char so that we catch "char" vs
7182 // "unsigned char" on systems where "char" is unsigned.
7183 if (lhptee->isCharType())
7184 ltrans = S.Context.UnsignedCharTy;
7185 else if (lhptee->hasSignedIntegerRepresentation())
7186 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7188 if (rhptee->isCharType())
7189 rtrans = S.Context.UnsignedCharTy;
7190 else if (rhptee->hasSignedIntegerRepresentation())
7191 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7193 if (ltrans == rtrans) {
7194 // Types are compatible ignoring the sign. Qualifier incompatibility
7195 // takes priority over sign incompatibility because the sign
7196 // warning can be disabled.
7197 if (ConvTy != Sema::Compatible)
7200 return Sema::IncompatiblePointerSign;
7203 // If we are a multi-level pointer, it's possible that our issue is simply
7204 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7205 // the eventual target type is the same and the pointers have the same
7206 // level of indirection, this must be the issue.
7207 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7209 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7210 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7211 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7213 if (lhptee == rhptee)
7214 return Sema::IncompatibleNestedPointerQualifiers;
7217 // General pointer incompatibility takes priority over qualifiers.
7218 return Sema::IncompatiblePointer;
7220 if (!S.getLangOpts().CPlusPlus &&
7221 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
7222 return Sema::IncompatiblePointer;
7226 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7227 /// block pointer types are compatible or whether a block and normal pointer
7228 /// are compatible. It is more restrict than comparing two function pointer
7230 static Sema::AssignConvertType
7231 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7233 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7234 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7236 QualType lhptee, rhptee;
7238 // get the "pointed to" type (ignoring qualifiers at the top level)
7239 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7240 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7242 // In C++, the types have to match exactly.
7243 if (S.getLangOpts().CPlusPlus)
7244 return Sema::IncompatibleBlockPointer;
7246 Sema::AssignConvertType ConvTy = Sema::Compatible;
7248 // For blocks we enforce that qualifiers are identical.
7249 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7250 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7252 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7253 return Sema::IncompatibleBlockPointer;
7258 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7259 /// for assignment compatibility.
7260 static Sema::AssignConvertType
7261 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7263 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7264 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7266 if (LHSType->isObjCBuiltinType()) {
7267 // Class is not compatible with ObjC object pointers.
7268 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7269 !RHSType->isObjCQualifiedClassType())
7270 return Sema::IncompatiblePointer;
7271 return Sema::Compatible;
7273 if (RHSType->isObjCBuiltinType()) {
7274 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7275 !LHSType->isObjCQualifiedClassType())
7276 return Sema::IncompatiblePointer;
7277 return Sema::Compatible;
7279 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7280 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7282 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7283 // make an exception for id<P>
7284 !LHSType->isObjCQualifiedIdType())
7285 return Sema::CompatiblePointerDiscardsQualifiers;
7287 if (S.Context.typesAreCompatible(LHSType, RHSType))
7288 return Sema::Compatible;
7289 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7290 return Sema::IncompatibleObjCQualifiedId;
7291 return Sema::IncompatiblePointer;
7294 Sema::AssignConvertType
7295 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7296 QualType LHSType, QualType RHSType) {
7297 // Fake up an opaque expression. We don't actually care about what
7298 // cast operations are required, so if CheckAssignmentConstraints
7299 // adds casts to this they'll be wasted, but fortunately that doesn't
7300 // usually happen on valid code.
7301 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7302 ExprResult RHSPtr = &RHSExpr;
7303 CastKind K = CK_Invalid;
7305 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7308 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7309 /// has code to accommodate several GCC extensions when type checking
7310 /// pointers. Here are some objectionable examples that GCC considers warnings:
7314 /// struct foo *pfoo;
7316 /// pint = pshort; // warning: assignment from incompatible pointer type
7317 /// a = pint; // warning: assignment makes integer from pointer without a cast
7318 /// pint = a; // warning: assignment makes pointer from integer without a cast
7319 /// pint = pfoo; // warning: assignment from incompatible pointer type
7321 /// As a result, the code for dealing with pointers is more complex than the
7322 /// C99 spec dictates.
7324 /// Sets 'Kind' for any result kind except Incompatible.
7325 Sema::AssignConvertType
7326 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7327 CastKind &Kind, bool ConvertRHS) {
7328 QualType RHSType = RHS.get()->getType();
7329 QualType OrigLHSType = LHSType;
7331 // Get canonical types. We're not formatting these types, just comparing
7333 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7334 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7336 // Common case: no conversion required.
7337 if (LHSType == RHSType) {
7342 // If we have an atomic type, try a non-atomic assignment, then just add an
7343 // atomic qualification step.
7344 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7345 Sema::AssignConvertType result =
7346 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7347 if (result != Compatible)
7349 if (Kind != CK_NoOp && ConvertRHS)
7350 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7351 Kind = CK_NonAtomicToAtomic;
7355 // If the left-hand side is a reference type, then we are in a
7356 // (rare!) case where we've allowed the use of references in C,
7357 // e.g., as a parameter type in a built-in function. In this case,
7358 // just make sure that the type referenced is compatible with the
7359 // right-hand side type. The caller is responsible for adjusting
7360 // LHSType so that the resulting expression does not have reference
7362 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7363 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7364 Kind = CK_LValueBitCast;
7367 return Incompatible;
7370 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7371 // to the same ExtVector type.
7372 if (LHSType->isExtVectorType()) {
7373 if (RHSType->isExtVectorType())
7374 return Incompatible;
7375 if (RHSType->isArithmeticType()) {
7376 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7378 RHS = prepareVectorSplat(LHSType, RHS.get());
7379 Kind = CK_VectorSplat;
7384 // Conversions to or from vector type.
7385 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7386 if (LHSType->isVectorType() && RHSType->isVectorType()) {
7387 // Allow assignments of an AltiVec vector type to an equivalent GCC
7388 // vector type and vice versa
7389 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7394 // If we are allowing lax vector conversions, and LHS and RHS are both
7395 // vectors, the total size only needs to be the same. This is a bitcast;
7396 // no bits are changed but the result type is different.
7397 if (isLaxVectorConversion(RHSType, LHSType)) {
7399 return IncompatibleVectors;
7403 // When the RHS comes from another lax conversion (e.g. binops between
7404 // scalars and vectors) the result is canonicalized as a vector. When the
7405 // LHS is also a vector, the lax is allowed by the condition above. Handle
7406 // the case where LHS is a scalar.
7407 if (LHSType->isScalarType()) {
7408 const VectorType *VecType = RHSType->getAs<VectorType>();
7409 if (VecType && VecType->getNumElements() == 1 &&
7410 isLaxVectorConversion(RHSType, LHSType)) {
7411 ExprResult *VecExpr = &RHS;
7412 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7418 return Incompatible;
7421 // Diagnose attempts to convert between __float128 and long double where
7422 // such conversions currently can't be handled.
7423 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7424 return Incompatible;
7426 // Arithmetic conversions.
7427 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7428 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7430 Kind = PrepareScalarCast(RHS, LHSType);
7434 // Conversions to normal pointers.
7435 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7437 if (isa<PointerType>(RHSType)) {
7438 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7439 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7440 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7441 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7445 if (RHSType->isIntegerType()) {
7446 Kind = CK_IntegralToPointer; // FIXME: null?
7447 return IntToPointer;
7450 // C pointers are not compatible with ObjC object pointers,
7451 // with two exceptions:
7452 if (isa<ObjCObjectPointerType>(RHSType)) {
7453 // - conversions to void*
7454 if (LHSPointer->getPointeeType()->isVoidType()) {
7459 // - conversions from 'Class' to the redefinition type
7460 if (RHSType->isObjCClassType() &&
7461 Context.hasSameType(LHSType,
7462 Context.getObjCClassRedefinitionType())) {
7468 return IncompatiblePointer;
7472 if (RHSType->getAs<BlockPointerType>()) {
7473 if (LHSPointer->getPointeeType()->isVoidType()) {
7479 return Incompatible;
7482 // Conversions to block pointers.
7483 if (isa<BlockPointerType>(LHSType)) {
7485 if (RHSType->isBlockPointerType()) {
7487 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7490 // int or null -> T^
7491 if (RHSType->isIntegerType()) {
7492 Kind = CK_IntegralToPointer; // FIXME: null
7493 return IntToBlockPointer;
7497 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7498 Kind = CK_AnyPointerToBlockPointerCast;
7503 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7504 if (RHSPT->getPointeeType()->isVoidType()) {
7505 Kind = CK_AnyPointerToBlockPointerCast;
7509 return Incompatible;
7512 // Conversions to Objective-C pointers.
7513 if (isa<ObjCObjectPointerType>(LHSType)) {
7515 if (RHSType->isObjCObjectPointerType()) {
7517 Sema::AssignConvertType result =
7518 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7519 if (getLangOpts().ObjCAutoRefCount &&
7520 result == Compatible &&
7521 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7522 result = IncompatibleObjCWeakRef;
7526 // int or null -> A*
7527 if (RHSType->isIntegerType()) {
7528 Kind = CK_IntegralToPointer; // FIXME: null
7529 return IntToPointer;
7532 // In general, C pointers are not compatible with ObjC object pointers,
7533 // with two exceptions:
7534 if (isa<PointerType>(RHSType)) {
7535 Kind = CK_CPointerToObjCPointerCast;
7537 // - conversions from 'void*'
7538 if (RHSType->isVoidPointerType()) {
7542 // - conversions to 'Class' from its redefinition type
7543 if (LHSType->isObjCClassType() &&
7544 Context.hasSameType(RHSType,
7545 Context.getObjCClassRedefinitionType())) {
7549 return IncompatiblePointer;
7552 // Only under strict condition T^ is compatible with an Objective-C pointer.
7553 if (RHSType->isBlockPointerType() &&
7554 LHSType->isBlockCompatibleObjCPointerType(Context)) {
7556 maybeExtendBlockObject(RHS);
7557 Kind = CK_BlockPointerToObjCPointerCast;
7561 return Incompatible;
7564 // Conversions from pointers that are not covered by the above.
7565 if (isa<PointerType>(RHSType)) {
7567 if (LHSType == Context.BoolTy) {
7568 Kind = CK_PointerToBoolean;
7573 if (LHSType->isIntegerType()) {
7574 Kind = CK_PointerToIntegral;
7575 return PointerToInt;
7578 return Incompatible;
7581 // Conversions from Objective-C pointers that are not covered by the above.
7582 if (isa<ObjCObjectPointerType>(RHSType)) {
7584 if (LHSType == Context.BoolTy) {
7585 Kind = CK_PointerToBoolean;
7590 if (LHSType->isIntegerType()) {
7591 Kind = CK_PointerToIntegral;
7592 return PointerToInt;
7595 return Incompatible;
7598 // struct A -> struct B
7599 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7600 if (Context.typesAreCompatible(LHSType, RHSType)) {
7606 return Incompatible;
7609 /// \brief Constructs a transparent union from an expression that is
7610 /// used to initialize the transparent union.
7611 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7612 ExprResult &EResult, QualType UnionType,
7614 // Build an initializer list that designates the appropriate member
7615 // of the transparent union.
7616 Expr *E = EResult.get();
7617 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7618 E, SourceLocation());
7619 Initializer->setType(UnionType);
7620 Initializer->setInitializedFieldInUnion(Field);
7622 // Build a compound literal constructing a value of the transparent
7623 // union type from this initializer list.
7624 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7625 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7626 VK_RValue, Initializer, false);
7629 Sema::AssignConvertType
7630 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7632 QualType RHSType = RHS.get()->getType();
7634 // If the ArgType is a Union type, we want to handle a potential
7635 // transparent_union GCC extension.
7636 const RecordType *UT = ArgType->getAsUnionType();
7637 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7638 return Incompatible;
7640 // The field to initialize within the transparent union.
7641 RecordDecl *UD = UT->getDecl();
7642 FieldDecl *InitField = nullptr;
7643 // It's compatible if the expression matches any of the fields.
7644 for (auto *it : UD->fields()) {
7645 if (it->getType()->isPointerType()) {
7646 // If the transparent union contains a pointer type, we allow:
7648 // 2) null pointer constant
7649 if (RHSType->isPointerType())
7650 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7651 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7656 if (RHS.get()->isNullPointerConstant(Context,
7657 Expr::NPC_ValueDependentIsNull)) {
7658 RHS = ImpCastExprToType(RHS.get(), it->getType(),
7665 CastKind Kind = CK_Invalid;
7666 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7668 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7675 return Incompatible;
7677 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7681 Sema::AssignConvertType
7682 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7684 bool DiagnoseCFAudited,
7686 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7687 // we can't avoid *all* modifications at the moment, so we need some somewhere
7688 // to put the updated value.
7689 ExprResult LocalRHS = CallerRHS;
7690 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7692 if (getLangOpts().CPlusPlus) {
7693 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7694 // C++ 5.17p3: If the left operand is not of class type, the
7695 // expression is implicitly converted (C++ 4) to the
7696 // cv-unqualified type of the left operand.
7699 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7702 ImplicitConversionSequence ICS =
7703 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7704 /*SuppressUserConversions=*/false,
7705 /*AllowExplicit=*/false,
7706 /*InOverloadResolution=*/false,
7708 /*AllowObjCWritebackConversion=*/false);
7709 if (ICS.isFailure())
7710 return Incompatible;
7711 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7714 if (Res.isInvalid())
7715 return Incompatible;
7716 Sema::AssignConvertType result = Compatible;
7717 if (getLangOpts().ObjCAutoRefCount &&
7718 !CheckObjCARCUnavailableWeakConversion(LHSType,
7719 RHS.get()->getType()))
7720 result = IncompatibleObjCWeakRef;
7725 // FIXME: Currently, we fall through and treat C++ classes like C
7727 // FIXME: We also fall through for atomics; not sure what should
7728 // happen there, though.
7729 } else if (RHS.get()->getType() == Context.OverloadTy) {
7730 // As a set of extensions to C, we support overloading on functions. These
7731 // functions need to be resolved here.
7733 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7734 RHS.get(), LHSType, /*Complain=*/false, DAP))
7735 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7737 return Incompatible;
7740 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7741 // a null pointer constant.
7742 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7743 LHSType->isBlockPointerType()) &&
7744 RHS.get()->isNullPointerConstant(Context,
7745 Expr::NPC_ValueDependentIsNull)) {
7746 if (Diagnose || ConvertRHS) {
7749 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7750 /*IgnoreBaseAccess=*/false, Diagnose);
7752 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7757 // This check seems unnatural, however it is necessary to ensure the proper
7758 // conversion of functions/arrays. If the conversion were done for all
7759 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7760 // expressions that suppress this implicit conversion (&, sizeof).
7762 // Suppress this for references: C++ 8.5.3p5.
7763 if (!LHSType->isReferenceType()) {
7764 // FIXME: We potentially allocate here even if ConvertRHS is false.
7765 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7766 if (RHS.isInvalid())
7767 return Incompatible;
7770 Expr *PRE = RHS.get()->IgnoreParenCasts();
7771 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7772 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7773 if (PDecl && !PDecl->hasDefinition()) {
7774 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7775 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7779 CastKind Kind = CK_Invalid;
7780 Sema::AssignConvertType result =
7781 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7783 // C99 6.5.16.1p2: The value of the right operand is converted to the
7784 // type of the assignment expression.
7785 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7786 // so that we can use references in built-in functions even in C.
7787 // The getNonReferenceType() call makes sure that the resulting expression
7788 // does not have reference type.
7789 if (result != Incompatible && RHS.get()->getType() != LHSType) {
7790 QualType Ty = LHSType.getNonLValueExprType(Context);
7791 Expr *E = RHS.get();
7793 // Check for various Objective-C errors. If we are not reporting
7794 // diagnostics and just checking for errors, e.g., during overload
7795 // resolution, return Incompatible to indicate the failure.
7796 if (getLangOpts().ObjCAutoRefCount &&
7797 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7798 Diagnose, DiagnoseCFAudited) != ACR_okay) {
7800 return Incompatible;
7802 if (getLangOpts().ObjC1 &&
7803 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7804 E->getType(), E, Diagnose) ||
7805 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7807 return Incompatible;
7808 // Replace the expression with a corrected version and continue so we
7809 // can find further errors.
7815 RHS = ImpCastExprToType(E, Ty, Kind);
7820 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7822 Diag(Loc, diag::err_typecheck_invalid_operands)
7823 << LHS.get()->getType() << RHS.get()->getType()
7824 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7828 /// Try to convert a value of non-vector type to a vector type by converting
7829 /// the type to the element type of the vector and then performing a splat.
7830 /// If the language is OpenCL, we only use conversions that promote scalar
7831 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7834 /// \param scalar - if non-null, actually perform the conversions
7835 /// \return true if the operation fails (but without diagnosing the failure)
7836 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7838 QualType vectorEltTy,
7839 QualType vectorTy) {
7840 // The conversion to apply to the scalar before splatting it,
7842 CastKind scalarCast = CK_Invalid;
7844 if (vectorEltTy->isIntegralType(S.Context)) {
7845 if (!scalarTy->isIntegralType(S.Context))
7847 if (S.getLangOpts().OpenCL &&
7848 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7850 scalarCast = CK_IntegralCast;
7851 } else if (vectorEltTy->isRealFloatingType()) {
7852 if (scalarTy->isRealFloatingType()) {
7853 if (S.getLangOpts().OpenCL &&
7854 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7856 scalarCast = CK_FloatingCast;
7858 else if (scalarTy->isIntegralType(S.Context))
7859 scalarCast = CK_IntegralToFloating;
7866 // Adjust scalar if desired.
7868 if (scalarCast != CK_Invalid)
7869 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7870 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7875 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7876 SourceLocation Loc, bool IsCompAssign,
7878 bool AllowBoolConversions) {
7879 if (!IsCompAssign) {
7880 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7881 if (LHS.isInvalid())
7884 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7885 if (RHS.isInvalid())
7888 // For conversion purposes, we ignore any qualifiers.
7889 // For example, "const float" and "float" are equivalent.
7890 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7891 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7893 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7894 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7895 assert(LHSVecType || RHSVecType);
7897 // AltiVec-style "vector bool op vector bool" combinations are allowed
7898 // for some operators but not others.
7899 if (!AllowBothBool &&
7900 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7901 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7902 return InvalidOperands(Loc, LHS, RHS);
7904 // If the vector types are identical, return.
7905 if (Context.hasSameType(LHSType, RHSType))
7908 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7909 if (LHSVecType && RHSVecType &&
7910 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7911 if (isa<ExtVectorType>(LHSVecType)) {
7912 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7917 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7921 // AllowBoolConversions says that bool and non-bool AltiVec vectors
7922 // can be mixed, with the result being the non-bool type. The non-bool
7923 // operand must have integer element type.
7924 if (AllowBoolConversions && LHSVecType && RHSVecType &&
7925 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7926 (Context.getTypeSize(LHSVecType->getElementType()) ==
7927 Context.getTypeSize(RHSVecType->getElementType()))) {
7928 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7929 LHSVecType->getElementType()->isIntegerType() &&
7930 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7931 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7934 if (!IsCompAssign &&
7935 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7936 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7937 RHSVecType->getElementType()->isIntegerType()) {
7938 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7943 // If there's an ext-vector type and a scalar, try to convert the scalar to
7944 // the vector element type and splat.
7945 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7946 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7947 LHSVecType->getElementType(), LHSType))
7950 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7951 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7952 LHSType, RHSVecType->getElementType(),
7957 // If we're allowing lax vector conversions, only the total (data) size needs
7958 // to be the same. If one of the types is scalar, the result is always the
7959 // vector type. Don't allow this if the scalar operand is an lvalue.
7960 QualType VecType = LHSVecType ? LHSType : RHSType;
7961 QualType ScalarType = LHSVecType ? RHSType : LHSType;
7962 ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS;
7963 if (isLaxVectorConversion(ScalarType, VecType) &&
7964 !ScalarExpr->get()->isLValue()) {
7965 *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast);
7969 // Okay, the expression is invalid.
7971 // If there's a non-vector, non-real operand, diagnose that.
7972 if ((!RHSVecType && !RHSType->isRealType()) ||
7973 (!LHSVecType && !LHSType->isRealType())) {
7974 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7975 << LHSType << RHSType
7976 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7980 // OpenCL V1.1 6.2.6.p1:
7981 // If the operands are of more than one vector type, then an error shall
7982 // occur. Implicit conversions between vector types are not permitted, per
7984 if (getLangOpts().OpenCL &&
7985 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7986 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7987 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7992 // Otherwise, use the generic diagnostic.
7993 Diag(Loc, diag::err_typecheck_vector_not_convertable)
7994 << LHSType << RHSType
7995 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7999 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8000 // expression. These are mainly cases where the null pointer is used as an
8001 // integer instead of a pointer.
8002 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8003 SourceLocation Loc, bool IsCompare) {
8004 // The canonical way to check for a GNU null is with isNullPointerConstant,
8005 // but we use a bit of a hack here for speed; this is a relatively
8006 // hot path, and isNullPointerConstant is slow.
8007 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8008 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8010 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8012 // Avoid analyzing cases where the result will either be invalid (and
8013 // diagnosed as such) or entirely valid and not something to warn about.
8014 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8015 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8018 // Comparison operations would not make sense with a null pointer no matter
8019 // what the other expression is.
8021 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8022 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8023 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8027 // The rest of the operations only make sense with a null pointer
8028 // if the other expression is a pointer.
8029 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8030 NonNullType->canDecayToPointerType())
8033 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8034 << LHSNull /* LHS is NULL */ << NonNullType
8035 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8038 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8040 SourceLocation Loc, bool IsDiv) {
8041 // Check for division/remainder by zero.
8042 llvm::APSInt RHSValue;
8043 if (!RHS.get()->isValueDependent() &&
8044 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8045 S.DiagRuntimeBehavior(Loc, RHS.get(),
8046 S.PDiag(diag::warn_remainder_division_by_zero)
8047 << IsDiv << RHS.get()->getSourceRange());
8050 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8052 bool IsCompAssign, bool IsDiv) {
8053 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8055 if (LHS.get()->getType()->isVectorType() ||
8056 RHS.get()->getType()->isVectorType())
8057 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8058 /*AllowBothBool*/getLangOpts().AltiVec,
8059 /*AllowBoolConversions*/false);
8061 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8062 if (LHS.isInvalid() || RHS.isInvalid())
8066 if (compType.isNull() || !compType->isArithmeticType())
8067 return InvalidOperands(Loc, LHS, RHS);
8069 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8073 QualType Sema::CheckRemainderOperands(
8074 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8075 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8077 if (LHS.get()->getType()->isVectorType() ||
8078 RHS.get()->getType()->isVectorType()) {
8079 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8080 RHS.get()->getType()->hasIntegerRepresentation())
8081 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8082 /*AllowBothBool*/getLangOpts().AltiVec,
8083 /*AllowBoolConversions*/false);
8084 return InvalidOperands(Loc, LHS, RHS);
8087 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8088 if (LHS.isInvalid() || RHS.isInvalid())
8091 if (compType.isNull() || !compType->isIntegerType())
8092 return InvalidOperands(Loc, LHS, RHS);
8093 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8097 /// \brief Diagnose invalid arithmetic on two void pointers.
8098 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8099 Expr *LHSExpr, Expr *RHSExpr) {
8100 S.Diag(Loc, S.getLangOpts().CPlusPlus
8101 ? diag::err_typecheck_pointer_arith_void_type
8102 : diag::ext_gnu_void_ptr)
8103 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8104 << RHSExpr->getSourceRange();
8107 /// \brief Diagnose invalid arithmetic on a void pointer.
8108 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8110 S.Diag(Loc, S.getLangOpts().CPlusPlus
8111 ? diag::err_typecheck_pointer_arith_void_type
8112 : diag::ext_gnu_void_ptr)
8113 << 0 /* one pointer */ << Pointer->getSourceRange();
8116 /// \brief Diagnose invalid arithmetic on two function pointers.
8117 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8118 Expr *LHS, Expr *RHS) {
8119 assert(LHS->getType()->isAnyPointerType());
8120 assert(RHS->getType()->isAnyPointerType());
8121 S.Diag(Loc, S.getLangOpts().CPlusPlus
8122 ? diag::err_typecheck_pointer_arith_function_type
8123 : diag::ext_gnu_ptr_func_arith)
8124 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8125 // We only show the second type if it differs from the first.
8126 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8128 << RHS->getType()->getPointeeType()
8129 << LHS->getSourceRange() << RHS->getSourceRange();
8132 /// \brief Diagnose invalid arithmetic on a function pointer.
8133 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8135 assert(Pointer->getType()->isAnyPointerType());
8136 S.Diag(Loc, S.getLangOpts().CPlusPlus
8137 ? diag::err_typecheck_pointer_arith_function_type
8138 : diag::ext_gnu_ptr_func_arith)
8139 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8140 << 0 /* one pointer, so only one type */
8141 << Pointer->getSourceRange();
8144 /// \brief Emit error if Operand is incomplete pointer type
8146 /// \returns True if pointer has incomplete type
8147 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8149 QualType ResType = Operand->getType();
8150 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8151 ResType = ResAtomicType->getValueType();
8153 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8154 QualType PointeeTy = ResType->getPointeeType();
8155 return S.RequireCompleteType(Loc, PointeeTy,
8156 diag::err_typecheck_arithmetic_incomplete_type,
8157 PointeeTy, Operand->getSourceRange());
8160 /// \brief Check the validity of an arithmetic pointer operand.
8162 /// If the operand has pointer type, this code will check for pointer types
8163 /// which are invalid in arithmetic operations. These will be diagnosed
8164 /// appropriately, including whether or not the use is supported as an
8167 /// \returns True when the operand is valid to use (even if as an extension).
8168 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8170 QualType ResType = Operand->getType();
8171 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8172 ResType = ResAtomicType->getValueType();
8174 if (!ResType->isAnyPointerType()) return true;
8176 QualType PointeeTy = ResType->getPointeeType();
8177 if (PointeeTy->isVoidType()) {
8178 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8179 return !S.getLangOpts().CPlusPlus;
8181 if (PointeeTy->isFunctionType()) {
8182 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8183 return !S.getLangOpts().CPlusPlus;
8186 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8191 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8194 /// This routine will diagnose any invalid arithmetic on pointer operands much
8195 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8196 /// for emitting a single diagnostic even for operations where both LHS and RHS
8197 /// are (potentially problematic) pointers.
8199 /// \returns True when the operand is valid to use (even if as an extension).
8200 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8201 Expr *LHSExpr, Expr *RHSExpr) {
8202 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8203 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8204 if (!isLHSPointer && !isRHSPointer) return true;
8206 QualType LHSPointeeTy, RHSPointeeTy;
8207 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8208 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8210 // if both are pointers check if operation is valid wrt address spaces
8211 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8212 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8213 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8214 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8216 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8217 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8218 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8223 // Check for arithmetic on pointers to incomplete types.
8224 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8225 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8226 if (isLHSVoidPtr || isRHSVoidPtr) {
8227 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8228 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8229 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8231 return !S.getLangOpts().CPlusPlus;
8234 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8235 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8236 if (isLHSFuncPtr || isRHSFuncPtr) {
8237 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8238 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8240 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8242 return !S.getLangOpts().CPlusPlus;
8245 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8247 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8253 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8255 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8256 Expr *LHSExpr, Expr *RHSExpr) {
8257 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8258 Expr* IndexExpr = RHSExpr;
8260 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8261 IndexExpr = LHSExpr;
8264 bool IsStringPlusInt = StrExpr &&
8265 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8266 if (!IsStringPlusInt || IndexExpr->isValueDependent())
8270 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8271 unsigned StrLenWithNull = StrExpr->getLength() + 1;
8272 if (index.isNonNegative() &&
8273 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8274 index.isUnsigned()))
8278 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8279 Self.Diag(OpLoc, diag::warn_string_plus_int)
8280 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8282 // Only print a fixit for "str" + int, not for int + "str".
8283 if (IndexExpr == RHSExpr) {
8284 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8285 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8286 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8287 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8288 << FixItHint::CreateInsertion(EndLoc, "]");
8290 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8293 /// \brief Emit a warning when adding a char literal to a string.
8294 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8295 Expr *LHSExpr, Expr *RHSExpr) {
8296 const Expr *StringRefExpr = LHSExpr;
8297 const CharacterLiteral *CharExpr =
8298 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8301 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8302 StringRefExpr = RHSExpr;
8305 if (!CharExpr || !StringRefExpr)
8308 const QualType StringType = StringRefExpr->getType();
8310 // Return if not a PointerType.
8311 if (!StringType->isAnyPointerType())
8314 // Return if not a CharacterType.
8315 if (!StringType->getPointeeType()->isAnyCharacterType())
8318 ASTContext &Ctx = Self.getASTContext();
8319 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8321 const QualType CharType = CharExpr->getType();
8322 if (!CharType->isAnyCharacterType() &&
8323 CharType->isIntegerType() &&
8324 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8325 Self.Diag(OpLoc, diag::warn_string_plus_char)
8326 << DiagRange << Ctx.CharTy;
8328 Self.Diag(OpLoc, diag::warn_string_plus_char)
8329 << DiagRange << CharExpr->getType();
8332 // Only print a fixit for str + char, not for char + str.
8333 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8334 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8335 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8336 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8337 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8338 << FixItHint::CreateInsertion(EndLoc, "]");
8340 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8344 /// \brief Emit error when two pointers are incompatible.
8345 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8346 Expr *LHSExpr, Expr *RHSExpr) {
8347 assert(LHSExpr->getType()->isAnyPointerType());
8348 assert(RHSExpr->getType()->isAnyPointerType());
8349 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8350 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8351 << RHSExpr->getSourceRange();
8355 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8356 SourceLocation Loc, BinaryOperatorKind Opc,
8357 QualType* CompLHSTy) {
8358 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8360 if (LHS.get()->getType()->isVectorType() ||
8361 RHS.get()->getType()->isVectorType()) {
8362 QualType compType = CheckVectorOperands(
8363 LHS, RHS, Loc, CompLHSTy,
8364 /*AllowBothBool*/getLangOpts().AltiVec,
8365 /*AllowBoolConversions*/getLangOpts().ZVector);
8366 if (CompLHSTy) *CompLHSTy = compType;
8370 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8371 if (LHS.isInvalid() || RHS.isInvalid())
8374 // Diagnose "string literal" '+' int and string '+' "char literal".
8375 if (Opc == BO_Add) {
8376 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8377 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8380 // handle the common case first (both operands are arithmetic).
8381 if (!compType.isNull() && compType->isArithmeticType()) {
8382 if (CompLHSTy) *CompLHSTy = compType;
8386 // Type-checking. Ultimately the pointer's going to be in PExp;
8387 // note that we bias towards the LHS being the pointer.
8388 Expr *PExp = LHS.get(), *IExp = RHS.get();
8391 if (PExp->getType()->isPointerType()) {
8392 isObjCPointer = false;
8393 } else if (PExp->getType()->isObjCObjectPointerType()) {
8394 isObjCPointer = true;
8396 std::swap(PExp, IExp);
8397 if (PExp->getType()->isPointerType()) {
8398 isObjCPointer = false;
8399 } else if (PExp->getType()->isObjCObjectPointerType()) {
8400 isObjCPointer = true;
8402 return InvalidOperands(Loc, LHS, RHS);
8405 assert(PExp->getType()->isAnyPointerType());
8407 if (!IExp->getType()->isIntegerType())
8408 return InvalidOperands(Loc, LHS, RHS);
8410 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8413 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8416 // Check array bounds for pointer arithemtic
8417 CheckArrayAccess(PExp, IExp);
8420 QualType LHSTy = Context.isPromotableBitField(LHS.get());
8421 if (LHSTy.isNull()) {
8422 LHSTy = LHS.get()->getType();
8423 if (LHSTy->isPromotableIntegerType())
8424 LHSTy = Context.getPromotedIntegerType(LHSTy);
8429 return PExp->getType();
8433 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8435 QualType* CompLHSTy) {
8436 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8438 if (LHS.get()->getType()->isVectorType() ||
8439 RHS.get()->getType()->isVectorType()) {
8440 QualType compType = CheckVectorOperands(
8441 LHS, RHS, Loc, CompLHSTy,
8442 /*AllowBothBool*/getLangOpts().AltiVec,
8443 /*AllowBoolConversions*/getLangOpts().ZVector);
8444 if (CompLHSTy) *CompLHSTy = compType;
8448 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8449 if (LHS.isInvalid() || RHS.isInvalid())
8452 // Enforce type constraints: C99 6.5.6p3.
8454 // Handle the common case first (both operands are arithmetic).
8455 if (!compType.isNull() && compType->isArithmeticType()) {
8456 if (CompLHSTy) *CompLHSTy = compType;
8460 // Either ptr - int or ptr - ptr.
8461 if (LHS.get()->getType()->isAnyPointerType()) {
8462 QualType lpointee = LHS.get()->getType()->getPointeeType();
8464 // Diagnose bad cases where we step over interface counts.
8465 if (LHS.get()->getType()->isObjCObjectPointerType() &&
8466 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8469 // The result type of a pointer-int computation is the pointer type.
8470 if (RHS.get()->getType()->isIntegerType()) {
8471 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8474 // Check array bounds for pointer arithemtic
8475 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8476 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8478 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8479 return LHS.get()->getType();
8482 // Handle pointer-pointer subtractions.
8483 if (const PointerType *RHSPTy
8484 = RHS.get()->getType()->getAs<PointerType>()) {
8485 QualType rpointee = RHSPTy->getPointeeType();
8487 if (getLangOpts().CPlusPlus) {
8488 // Pointee types must be the same: C++ [expr.add]
8489 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8490 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8493 // Pointee types must be compatible C99 6.5.6p3
8494 if (!Context.typesAreCompatible(
8495 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8496 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8497 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8502 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8503 LHS.get(), RHS.get()))
8506 // The pointee type may have zero size. As an extension, a structure or
8507 // union may have zero size or an array may have zero length. In this
8508 // case subtraction does not make sense.
8509 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8510 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8511 if (ElementSize.isZero()) {
8512 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8513 << rpointee.getUnqualifiedType()
8514 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8518 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8519 return Context.getPointerDiffType();
8523 return InvalidOperands(Loc, LHS, RHS);
8526 static bool isScopedEnumerationType(QualType T) {
8527 if (const EnumType *ET = T->getAs<EnumType>())
8528 return ET->getDecl()->isScoped();
8532 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8533 SourceLocation Loc, BinaryOperatorKind Opc,
8535 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8536 // so skip remaining warnings as we don't want to modify values within Sema.
8537 if (S.getLangOpts().OpenCL)
8541 // Check right/shifter operand
8542 if (RHS.get()->isValueDependent() ||
8543 !RHS.get()->EvaluateAsInt(Right, S.Context))
8546 if (Right.isNegative()) {
8547 S.DiagRuntimeBehavior(Loc, RHS.get(),
8548 S.PDiag(diag::warn_shift_negative)
8549 << RHS.get()->getSourceRange());
8552 llvm::APInt LeftBits(Right.getBitWidth(),
8553 S.Context.getTypeSize(LHS.get()->getType()));
8554 if (Right.uge(LeftBits)) {
8555 S.DiagRuntimeBehavior(Loc, RHS.get(),
8556 S.PDiag(diag::warn_shift_gt_typewidth)
8557 << RHS.get()->getSourceRange());
8563 // When left shifting an ICE which is signed, we can check for overflow which
8564 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8565 // integers have defined behavior modulo one more than the maximum value
8566 // representable in the result type, so never warn for those.
8568 if (LHS.get()->isValueDependent() ||
8569 LHSType->hasUnsignedIntegerRepresentation() ||
8570 !LHS.get()->EvaluateAsInt(Left, S.Context))
8573 // If LHS does not have a signed type and non-negative value
8574 // then, the behavior is undefined. Warn about it.
8575 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8576 S.DiagRuntimeBehavior(Loc, LHS.get(),
8577 S.PDiag(diag::warn_shift_lhs_negative)
8578 << LHS.get()->getSourceRange());
8582 llvm::APInt ResultBits =
8583 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8584 if (LeftBits.uge(ResultBits))
8586 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8587 Result = Result.shl(Right);
8589 // Print the bit representation of the signed integer as an unsigned
8590 // hexadecimal number.
8591 SmallString<40> HexResult;
8592 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8594 // If we are only missing a sign bit, this is less likely to result in actual
8595 // bugs -- if the result is cast back to an unsigned type, it will have the
8596 // expected value. Thus we place this behind a different warning that can be
8597 // turned off separately if needed.
8598 if (LeftBits == ResultBits - 1) {
8599 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8600 << HexResult << LHSType
8601 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8605 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8606 << HexResult.str() << Result.getMinSignedBits() << LHSType
8607 << Left.getBitWidth() << LHS.get()->getSourceRange()
8608 << RHS.get()->getSourceRange();
8611 /// \brief Return the resulting type when an OpenCL vector is shifted
8612 /// by a scalar or vector shift amount.
8613 static QualType checkOpenCLVectorShift(Sema &S,
8614 ExprResult &LHS, ExprResult &RHS,
8615 SourceLocation Loc, bool IsCompAssign) {
8616 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8617 if (!LHS.get()->getType()->isVectorType()) {
8618 S.Diag(Loc, diag::err_shift_rhs_only_vector)
8619 << RHS.get()->getType() << LHS.get()->getType()
8620 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8624 if (!IsCompAssign) {
8625 LHS = S.UsualUnaryConversions(LHS.get());
8626 if (LHS.isInvalid()) return QualType();
8629 RHS = S.UsualUnaryConversions(RHS.get());
8630 if (RHS.isInvalid()) return QualType();
8632 QualType LHSType = LHS.get()->getType();
8633 const VectorType *LHSVecTy = LHSType->castAs<VectorType>();
8634 QualType LHSEleType = LHSVecTy->getElementType();
8636 // Note that RHS might not be a vector.
8637 QualType RHSType = RHS.get()->getType();
8638 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8639 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8641 // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8642 if (!LHSEleType->isIntegerType()) {
8643 S.Diag(Loc, diag::err_typecheck_expect_int)
8644 << LHS.get()->getType() << LHS.get()->getSourceRange();
8648 if (!RHSEleType->isIntegerType()) {
8649 S.Diag(Loc, diag::err_typecheck_expect_int)
8650 << RHS.get()->getType() << RHS.get()->getSourceRange();
8655 // OpenCL v1.1 s6.3.j says that for vector types, the operators
8656 // are applied component-wise. So if RHS is a vector, then ensure
8657 // that the number of elements is the same as LHS...
8658 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8659 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8660 << LHS.get()->getType() << RHS.get()->getType()
8661 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8665 // ...else expand RHS to match the number of elements in LHS.
8667 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8668 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8675 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8676 SourceLocation Loc, BinaryOperatorKind Opc,
8677 bool IsCompAssign) {
8678 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8680 // Vector shifts promote their scalar inputs to vector type.
8681 if (LHS.get()->getType()->isVectorType() ||
8682 RHS.get()->getType()->isVectorType()) {
8683 if (LangOpts.OpenCL)
8684 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8685 if (LangOpts.ZVector) {
8686 // The shift operators for the z vector extensions work basically
8687 // like OpenCL shifts, except that neither the LHS nor the RHS is
8688 // allowed to be a "vector bool".
8689 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8690 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8691 return InvalidOperands(Loc, LHS, RHS);
8692 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8693 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8694 return InvalidOperands(Loc, LHS, RHS);
8695 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8697 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8698 /*AllowBothBool*/true,
8699 /*AllowBoolConversions*/false);
8702 // Shifts don't perform usual arithmetic conversions, they just do integer
8703 // promotions on each operand. C99 6.5.7p3
8705 // For the LHS, do usual unary conversions, but then reset them away
8706 // if this is a compound assignment.
8707 ExprResult OldLHS = LHS;
8708 LHS = UsualUnaryConversions(LHS.get());
8709 if (LHS.isInvalid())
8711 QualType LHSType = LHS.get()->getType();
8712 if (IsCompAssign) LHS = OldLHS;
8714 // The RHS is simpler.
8715 RHS = UsualUnaryConversions(RHS.get());
8716 if (RHS.isInvalid())
8718 QualType RHSType = RHS.get()->getType();
8720 // C99 6.5.7p2: Each of the operands shall have integer type.
8721 if (!LHSType->hasIntegerRepresentation() ||
8722 !RHSType->hasIntegerRepresentation())
8723 return InvalidOperands(Loc, LHS, RHS);
8725 // C++0x: Don't allow scoped enums. FIXME: Use something better than
8726 // hasIntegerRepresentation() above instead of this.
8727 if (isScopedEnumerationType(LHSType) ||
8728 isScopedEnumerationType(RHSType)) {
8729 return InvalidOperands(Loc, LHS, RHS);
8731 // Sanity-check shift operands
8732 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8734 // "The type of the result is that of the promoted left operand."
8738 static bool IsWithinTemplateSpecialization(Decl *D) {
8739 if (DeclContext *DC = D->getDeclContext()) {
8740 if (isa<ClassTemplateSpecializationDecl>(DC))
8742 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8743 return FD->isFunctionTemplateSpecialization();
8748 /// If two different enums are compared, raise a warning.
8749 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8751 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8752 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8754 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8757 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8761 // Ignore anonymous enums.
8762 if (!LHSEnumType->getDecl()->getIdentifier())
8764 if (!RHSEnumType->getDecl()->getIdentifier())
8767 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8770 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8771 << LHSStrippedType << RHSStrippedType
8772 << LHS->getSourceRange() << RHS->getSourceRange();
8775 /// \brief Diagnose bad pointer comparisons.
8776 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8777 ExprResult &LHS, ExprResult &RHS,
8779 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8780 : diag::ext_typecheck_comparison_of_distinct_pointers)
8781 << LHS.get()->getType() << RHS.get()->getType()
8782 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8785 /// \brief Returns false if the pointers are converted to a composite type,
8787 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8788 ExprResult &LHS, ExprResult &RHS) {
8789 // C++ [expr.rel]p2:
8790 // [...] Pointer conversions (4.10) and qualification
8791 // conversions (4.4) are performed on pointer operands (or on
8792 // a pointer operand and a null pointer constant) to bring
8793 // them to their composite pointer type. [...]
8795 // C++ [expr.eq]p1 uses the same notion for (in)equality
8796 // comparisons of pointers.
8799 // In addition, pointers to members can be compared, or a pointer to
8800 // member and a null pointer constant. Pointer to member conversions
8801 // (4.11) and qualification conversions (4.4) are performed to bring
8802 // them to a common type. If one operand is a null pointer constant,
8803 // the common type is the type of the other operand. Otherwise, the
8804 // common type is a pointer to member type similar (4.4) to the type
8805 // of one of the operands, with a cv-qualification signature (4.4)
8806 // that is the union of the cv-qualification signatures of the operand
8809 QualType LHSType = LHS.get()->getType();
8810 QualType RHSType = RHS.get()->getType();
8811 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8812 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8814 bool NonStandardCompositeType = false;
8815 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8816 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8818 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8822 if (NonStandardCompositeType)
8823 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8824 << LHSType << RHSType << T << LHS.get()->getSourceRange()
8825 << RHS.get()->getSourceRange();
8827 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8828 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8832 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8836 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8837 : diag::ext_typecheck_comparison_of_fptr_to_void)
8838 << LHS.get()->getType() << RHS.get()->getType()
8839 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8842 static bool isObjCObjectLiteral(ExprResult &E) {
8843 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8844 case Stmt::ObjCArrayLiteralClass:
8845 case Stmt::ObjCDictionaryLiteralClass:
8846 case Stmt::ObjCStringLiteralClass:
8847 case Stmt::ObjCBoxedExprClass:
8850 // Note that ObjCBoolLiteral is NOT an object literal!
8855 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8856 const ObjCObjectPointerType *Type =
8857 LHS->getType()->getAs<ObjCObjectPointerType>();
8859 // If this is not actually an Objective-C object, bail out.
8863 // Get the LHS object's interface type.
8864 QualType InterfaceType = Type->getPointeeType();
8866 // If the RHS isn't an Objective-C object, bail out.
8867 if (!RHS->getType()->isObjCObjectPointerType())
8870 // Try to find the -isEqual: method.
8871 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8872 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8876 if (Type->isObjCIdType()) {
8877 // For 'id', just check the global pool.
8878 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8879 /*receiverId=*/true);
8882 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8890 QualType T = Method->parameters()[0]->getType();
8891 if (!T->isObjCObjectPointerType())
8894 QualType R = Method->getReturnType();
8895 if (!R->isScalarType())
8901 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8902 FromE = FromE->IgnoreParenImpCasts();
8903 switch (FromE->getStmtClass()) {
8906 case Stmt::ObjCStringLiteralClass:
8909 case Stmt::ObjCArrayLiteralClass:
8912 case Stmt::ObjCDictionaryLiteralClass:
8913 // "dictionary literal"
8914 return LK_Dictionary;
8915 case Stmt::BlockExprClass:
8917 case Stmt::ObjCBoxedExprClass: {
8918 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8919 switch (Inner->getStmtClass()) {
8920 case Stmt::IntegerLiteralClass:
8921 case Stmt::FloatingLiteralClass:
8922 case Stmt::CharacterLiteralClass:
8923 case Stmt::ObjCBoolLiteralExprClass:
8924 case Stmt::CXXBoolLiteralExprClass:
8925 // "numeric literal"
8927 case Stmt::ImplicitCastExprClass: {
8928 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8929 // Boolean literals can be represented by implicit casts.
8930 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8943 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8944 ExprResult &LHS, ExprResult &RHS,
8945 BinaryOperator::Opcode Opc){
8948 if (isObjCObjectLiteral(LHS)) {
8949 Literal = LHS.get();
8952 Literal = RHS.get();
8956 // Don't warn on comparisons against nil.
8957 Other = Other->IgnoreParenCasts();
8958 if (Other->isNullPointerConstant(S.getASTContext(),
8959 Expr::NPC_ValueDependentIsNotNull))
8962 // This should be kept in sync with warn_objc_literal_comparison.
8963 // LK_String should always be after the other literals, since it has its own
8965 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8966 assert(LiteralKind != Sema::LK_Block);
8967 if (LiteralKind == Sema::LK_None) {
8968 llvm_unreachable("Unknown Objective-C object literal kind");
8971 if (LiteralKind == Sema::LK_String)
8972 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8973 << Literal->getSourceRange();
8975 S.Diag(Loc, diag::warn_objc_literal_comparison)
8976 << LiteralKind << Literal->getSourceRange();
8978 if (BinaryOperator::isEqualityOp(Opc) &&
8979 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8980 SourceLocation Start = LHS.get()->getLocStart();
8981 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
8982 CharSourceRange OpRange =
8983 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8985 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8986 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8987 << FixItHint::CreateReplacement(OpRange, " isEqual:")
8988 << FixItHint::CreateInsertion(End, "]");
8992 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8995 BinaryOperatorKind Opc) {
8996 // Check that left hand side is !something.
8997 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8998 if (!UO || UO->getOpcode() != UO_LNot) return;
9000 // Only check if the right hand side is non-bool arithmetic type.
9001 if (RHS.get()->isKnownToHaveBooleanValue()) return;
9003 // Make sure that the something in !something is not bool.
9004 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9005 if (SubExpr->isKnownToHaveBooleanValue()) return;
9008 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
9011 // First note suggest !(x < y)
9012 SourceLocation FirstOpen = SubExpr->getLocStart();
9013 SourceLocation FirstClose = RHS.get()->getLocEnd();
9014 FirstClose = S.getLocForEndOfToken(FirstClose);
9015 if (FirstClose.isInvalid())
9016 FirstOpen = SourceLocation();
9017 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9018 << FixItHint::CreateInsertion(FirstOpen, "(")
9019 << FixItHint::CreateInsertion(FirstClose, ")");
9021 // Second note suggests (!x) < y
9022 SourceLocation SecondOpen = LHS.get()->getLocStart();
9023 SourceLocation SecondClose = LHS.get()->getLocEnd();
9024 SecondClose = S.getLocForEndOfToken(SecondClose);
9025 if (SecondClose.isInvalid())
9026 SecondOpen = SourceLocation();
9027 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9028 << FixItHint::CreateInsertion(SecondOpen, "(")
9029 << FixItHint::CreateInsertion(SecondClose, ")");
9032 // Get the decl for a simple expression: a reference to a variable,
9033 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9034 static ValueDecl *getCompareDecl(Expr *E) {
9035 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9036 return DR->getDecl();
9037 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9038 if (Ivar->isFreeIvar())
9039 return Ivar->getDecl();
9041 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9042 if (Mem->isImplicitAccess())
9043 return Mem->getMemberDecl();
9048 // C99 6.5.8, C++ [expr.rel]
9049 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9050 SourceLocation Loc, BinaryOperatorKind Opc,
9051 bool IsRelational) {
9052 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9054 // Handle vector comparisons separately.
9055 if (LHS.get()->getType()->isVectorType() ||
9056 RHS.get()->getType()->isVectorType())
9057 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9059 QualType LHSType = LHS.get()->getType();
9060 QualType RHSType = RHS.get()->getType();
9062 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9063 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9065 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9066 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
9068 if (!LHSType->hasFloatingRepresentation() &&
9069 !(LHSType->isBlockPointerType() && IsRelational) &&
9070 !LHS.get()->getLocStart().isMacroID() &&
9071 !RHS.get()->getLocStart().isMacroID() &&
9072 ActiveTemplateInstantiations.empty()) {
9073 // For non-floating point types, check for self-comparisons of the form
9074 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9075 // often indicate logic errors in the program.
9077 // NOTE: Don't warn about comparison expressions resulting from macro
9078 // expansion. Also don't warn about comparisons which are only self
9079 // comparisons within a template specialization. The warnings should catch
9080 // obvious cases in the definition of the template anyways. The idea is to
9081 // warn when the typed comparison operator will always evaluate to the same
9083 ValueDecl *DL = getCompareDecl(LHSStripped);
9084 ValueDecl *DR = getCompareDecl(RHSStripped);
9085 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9086 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9091 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9092 !DL->getType()->isReferenceType() &&
9093 !DR->getType()->isReferenceType()) {
9094 // what is it always going to eval to?
9095 char always_evals_to;
9097 case BO_EQ: // e.g. array1 == array2
9098 always_evals_to = 0; // false
9100 case BO_NE: // e.g. array1 != array2
9101 always_evals_to = 1; // true
9104 // best we can say is 'a constant'
9105 always_evals_to = 2; // e.g. array1 <= array2
9108 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9110 << always_evals_to);
9113 if (isa<CastExpr>(LHSStripped))
9114 LHSStripped = LHSStripped->IgnoreParenCasts();
9115 if (isa<CastExpr>(RHSStripped))
9116 RHSStripped = RHSStripped->IgnoreParenCasts();
9118 // Warn about comparisons against a string constant (unless the other
9119 // operand is null), the user probably wants strcmp.
9120 Expr *literalString = nullptr;
9121 Expr *literalStringStripped = nullptr;
9122 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9123 !RHSStripped->isNullPointerConstant(Context,
9124 Expr::NPC_ValueDependentIsNull)) {
9125 literalString = LHS.get();
9126 literalStringStripped = LHSStripped;
9127 } else if ((isa<StringLiteral>(RHSStripped) ||
9128 isa<ObjCEncodeExpr>(RHSStripped)) &&
9129 !LHSStripped->isNullPointerConstant(Context,
9130 Expr::NPC_ValueDependentIsNull)) {
9131 literalString = RHS.get();
9132 literalStringStripped = RHSStripped;
9135 if (literalString) {
9136 DiagRuntimeBehavior(Loc, nullptr,
9137 PDiag(diag::warn_stringcompare)
9138 << isa<ObjCEncodeExpr>(literalStringStripped)
9139 << literalString->getSourceRange());
9143 // C99 6.5.8p3 / C99 6.5.9p4
9144 UsualArithmeticConversions(LHS, RHS);
9145 if (LHS.isInvalid() || RHS.isInvalid())
9148 LHSType = LHS.get()->getType();
9149 RHSType = RHS.get()->getType();
9151 // The result of comparisons is 'bool' in C++, 'int' in C.
9152 QualType ResultTy = Context.getLogicalOperationType();
9155 if (LHSType->isRealType() && RHSType->isRealType())
9158 // Check for comparisons of floating point operands using != and ==.
9159 if (LHSType->hasFloatingRepresentation())
9160 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9162 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9166 const Expr::NullPointerConstantKind LHSNullKind =
9167 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9168 const Expr::NullPointerConstantKind RHSNullKind =
9169 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9170 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9171 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9173 if (!IsRelational && LHSIsNull != RHSIsNull) {
9174 bool IsEquality = Opc == BO_EQ;
9176 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9177 RHS.get()->getSourceRange());
9179 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9180 LHS.get()->getSourceRange());
9183 // All of the following pointer-related warnings are GCC extensions, except
9184 // when handling null pointer constants.
9185 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
9186 QualType LCanPointeeTy =
9187 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9188 QualType RCanPointeeTy =
9189 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9191 if (getLangOpts().CPlusPlus) {
9192 if (LCanPointeeTy == RCanPointeeTy)
9194 if (!IsRelational &&
9195 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9196 // Valid unless comparison between non-null pointer and function pointer
9197 // This is a gcc extension compatibility comparison.
9198 // In a SFINAE context, we treat this as a hard error to maintain
9199 // conformance with the C++ standard.
9200 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9201 && !LHSIsNull && !RHSIsNull) {
9202 diagnoseFunctionPointerToVoidComparison(
9203 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9205 if (isSFINAEContext())
9208 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9213 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9218 // C99 6.5.9p2 and C99 6.5.8p2
9219 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9220 RCanPointeeTy.getUnqualifiedType())) {
9221 // Valid unless a relational comparison of function pointers
9222 if (IsRelational && LCanPointeeTy->isFunctionType()) {
9223 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9224 << LHSType << RHSType << LHS.get()->getSourceRange()
9225 << RHS.get()->getSourceRange();
9227 } else if (!IsRelational &&
9228 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9229 // Valid unless comparison between non-null pointer and function pointer
9230 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9231 && !LHSIsNull && !RHSIsNull)
9232 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9236 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9238 if (LCanPointeeTy != RCanPointeeTy) {
9239 // Treat NULL constant as a special case in OpenCL.
9240 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9241 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9242 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9244 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9245 << LHSType << RHSType << 0 /* comparison */
9246 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9249 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9250 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9251 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9253 if (LHSIsNull && !RHSIsNull)
9254 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9256 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9261 if (getLangOpts().CPlusPlus) {
9262 // Comparison of nullptr_t with itself.
9263 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9266 // Comparison of pointers with null pointer constants and equality
9267 // comparisons of member pointers to null pointer constants.
9269 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9271 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9272 RHS = ImpCastExprToType(RHS.get(), LHSType,
9273 LHSType->isMemberPointerType()
9274 ? CK_NullToMemberPointer
9275 : CK_NullToPointer);
9279 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9281 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9282 LHS = ImpCastExprToType(LHS.get(), RHSType,
9283 RHSType->isMemberPointerType()
9284 ? CK_NullToMemberPointer
9285 : CK_NullToPointer);
9289 // Comparison of member pointers.
9290 if (!IsRelational &&
9291 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9292 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9298 // Handle scoped enumeration types specifically, since they don't promote
9300 if (LHS.get()->getType()->isEnumeralType() &&
9301 Context.hasSameUnqualifiedType(LHS.get()->getType(),
9302 RHS.get()->getType()))
9306 // Handle block pointer types.
9307 if (!IsRelational && LHSType->isBlockPointerType() &&
9308 RHSType->isBlockPointerType()) {
9309 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9310 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9312 if (!LHSIsNull && !RHSIsNull &&
9313 !Context.typesAreCompatible(lpointee, rpointee)) {
9314 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9315 << LHSType << RHSType << LHS.get()->getSourceRange()
9316 << RHS.get()->getSourceRange();
9318 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9322 // Allow block pointers to be compared with null pointer constants.
9324 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9325 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9326 if (!LHSIsNull && !RHSIsNull) {
9327 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9328 ->getPointeeType()->isVoidType())
9329 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9330 ->getPointeeType()->isVoidType())))
9331 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9332 << LHSType << RHSType << LHS.get()->getSourceRange()
9333 << RHS.get()->getSourceRange();
9335 if (LHSIsNull && !RHSIsNull)
9336 LHS = ImpCastExprToType(LHS.get(), RHSType,
9337 RHSType->isPointerType() ? CK_BitCast
9338 : CK_AnyPointerToBlockPointerCast);
9340 RHS = ImpCastExprToType(RHS.get(), LHSType,
9341 LHSType->isPointerType() ? CK_BitCast
9342 : CK_AnyPointerToBlockPointerCast);
9346 if (LHSType->isObjCObjectPointerType() ||
9347 RHSType->isObjCObjectPointerType()) {
9348 const PointerType *LPT = LHSType->getAs<PointerType>();
9349 const PointerType *RPT = RHSType->getAs<PointerType>();
9351 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9352 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9354 if (!LPtrToVoid && !RPtrToVoid &&
9355 !Context.typesAreCompatible(LHSType, RHSType)) {
9356 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9359 if (LHSIsNull && !RHSIsNull) {
9360 Expr *E = LHS.get();
9361 if (getLangOpts().ObjCAutoRefCount)
9362 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9363 LHS = ImpCastExprToType(E, RHSType,
9364 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9367 Expr *E = RHS.get();
9368 if (getLangOpts().ObjCAutoRefCount)
9369 CheckObjCARCConversion(SourceRange(), LHSType, E,
9370 CCK_ImplicitConversion, /*Diagnose=*/true,
9371 /*DiagnoseCFAudited=*/false, Opc);
9372 RHS = ImpCastExprToType(E, LHSType,
9373 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9377 if (LHSType->isObjCObjectPointerType() &&
9378 RHSType->isObjCObjectPointerType()) {
9379 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9380 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9382 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9383 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9385 if (LHSIsNull && !RHSIsNull)
9386 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9388 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9392 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9393 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9394 unsigned DiagID = 0;
9395 bool isError = false;
9396 if (LangOpts.DebuggerSupport) {
9397 // Under a debugger, allow the comparison of pointers to integers,
9398 // since users tend to want to compare addresses.
9399 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9400 (RHSIsNull && RHSType->isIntegerType())) {
9401 if (IsRelational && !getLangOpts().CPlusPlus)
9402 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9403 } else if (IsRelational && !getLangOpts().CPlusPlus)
9404 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9405 else if (getLangOpts().CPlusPlus) {
9406 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9409 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9413 << LHSType << RHSType << LHS.get()->getSourceRange()
9414 << RHS.get()->getSourceRange();
9419 if (LHSType->isIntegerType())
9420 LHS = ImpCastExprToType(LHS.get(), RHSType,
9421 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9423 RHS = ImpCastExprToType(RHS.get(), LHSType,
9424 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9428 // Handle block pointers.
9429 if (!IsRelational && RHSIsNull
9430 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9431 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9434 if (!IsRelational && LHSIsNull
9435 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9436 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9440 return InvalidOperands(Loc, LHS, RHS);
9444 // Return a signed type that is of identical size and number of elements.
9445 // For floating point vectors, return an integer type of identical size
9446 // and number of elements.
9447 QualType Sema::GetSignedVectorType(QualType V) {
9448 const VectorType *VTy = V->getAs<VectorType>();
9449 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9450 if (TypeSize == Context.getTypeSize(Context.CharTy))
9451 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9452 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9453 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9454 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9455 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9456 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9457 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9458 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9459 "Unhandled vector element size in vector compare");
9460 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9463 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9464 /// operates on extended vector types. Instead of producing an IntTy result,
9465 /// like a scalar comparison, a vector comparison produces a vector of integer
9467 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9469 bool IsRelational) {
9470 // Check to make sure we're operating on vectors of the same type and width,
9471 // Allowing one side to be a scalar of element type.
9472 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9473 /*AllowBothBool*/true,
9474 /*AllowBoolConversions*/getLangOpts().ZVector);
9478 QualType LHSType = LHS.get()->getType();
9480 // If AltiVec, the comparison results in a numeric type, i.e.
9481 // bool for C++, int for C
9482 if (getLangOpts().AltiVec &&
9483 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9484 return Context.getLogicalOperationType();
9486 // For non-floating point types, check for self-comparisons of the form
9487 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9488 // often indicate logic errors in the program.
9489 if (!LHSType->hasFloatingRepresentation() &&
9490 ActiveTemplateInstantiations.empty()) {
9491 if (DeclRefExpr* DRL
9492 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9493 if (DeclRefExpr* DRR
9494 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9495 if (DRL->getDecl() == DRR->getDecl())
9496 DiagRuntimeBehavior(Loc, nullptr,
9497 PDiag(diag::warn_comparison_always)
9499 << 2 // "a constant"
9503 // Check for comparisons of floating point operands using != and ==.
9504 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9505 assert (RHS.get()->getType()->hasFloatingRepresentation());
9506 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9509 // Return a signed type for the vector.
9510 return GetSignedVectorType(vType);
9513 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9514 SourceLocation Loc) {
9515 // Ensure that either both operands are of the same vector type, or
9516 // one operand is of a vector type and the other is of its element type.
9517 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9518 /*AllowBothBool*/true,
9519 /*AllowBoolConversions*/false);
9521 return InvalidOperands(Loc, LHS, RHS);
9522 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9523 vType->hasFloatingRepresentation())
9524 return InvalidOperands(Loc, LHS, RHS);
9526 return GetSignedVectorType(LHS.get()->getType());
9529 inline QualType Sema::CheckBitwiseOperands(
9530 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9531 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9533 if (LHS.get()->getType()->isVectorType() ||
9534 RHS.get()->getType()->isVectorType()) {
9535 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9536 RHS.get()->getType()->hasIntegerRepresentation())
9537 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9538 /*AllowBothBool*/true,
9539 /*AllowBoolConversions*/getLangOpts().ZVector);
9540 return InvalidOperands(Loc, LHS, RHS);
9543 ExprResult LHSResult = LHS, RHSResult = RHS;
9544 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9546 if (LHSResult.isInvalid() || RHSResult.isInvalid())
9548 LHS = LHSResult.get();
9549 RHS = RHSResult.get();
9551 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9553 return InvalidOperands(Loc, LHS, RHS);
9557 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9559 BinaryOperatorKind Opc) {
9560 // Check vector operands differently.
9561 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9562 return CheckVectorLogicalOperands(LHS, RHS, Loc);
9564 // Diagnose cases where the user write a logical and/or but probably meant a
9565 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
9567 if (LHS.get()->getType()->isIntegerType() &&
9568 !LHS.get()->getType()->isBooleanType() &&
9569 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9570 // Don't warn in macros or template instantiations.
9571 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9572 // If the RHS can be constant folded, and if it constant folds to something
9573 // that isn't 0 or 1 (which indicate a potential logical operation that
9574 // happened to fold to true/false) then warn.
9575 // Parens on the RHS are ignored.
9576 llvm::APSInt Result;
9577 if (RHS.get()->EvaluateAsInt(Result, Context))
9578 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9579 !RHS.get()->getExprLoc().isMacroID()) ||
9580 (Result != 0 && Result != 1)) {
9581 Diag(Loc, diag::warn_logical_instead_of_bitwise)
9582 << RHS.get()->getSourceRange()
9583 << (Opc == BO_LAnd ? "&&" : "||");
9584 // Suggest replacing the logical operator with the bitwise version
9585 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9586 << (Opc == BO_LAnd ? "&" : "|")
9587 << FixItHint::CreateReplacement(SourceRange(
9588 Loc, getLocForEndOfToken(Loc)),
9589 Opc == BO_LAnd ? "&" : "|");
9591 // Suggest replacing "Foo() && kNonZero" with "Foo()"
9592 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9593 << FixItHint::CreateRemoval(
9594 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9595 RHS.get()->getLocEnd()));
9599 if (!Context.getLangOpts().CPlusPlus) {
9600 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9601 // not operate on the built-in scalar and vector float types.
9602 if (Context.getLangOpts().OpenCL &&
9603 Context.getLangOpts().OpenCLVersion < 120) {
9604 if (LHS.get()->getType()->isFloatingType() ||
9605 RHS.get()->getType()->isFloatingType())
9606 return InvalidOperands(Loc, LHS, RHS);
9609 LHS = UsualUnaryConversions(LHS.get());
9610 if (LHS.isInvalid())
9613 RHS = UsualUnaryConversions(RHS.get());
9614 if (RHS.isInvalid())
9617 if (!LHS.get()->getType()->isScalarType() ||
9618 !RHS.get()->getType()->isScalarType())
9619 return InvalidOperands(Loc, LHS, RHS);
9621 return Context.IntTy;
9624 // The following is safe because we only use this method for
9625 // non-overloadable operands.
9627 // C++ [expr.log.and]p1
9628 // C++ [expr.log.or]p1
9629 // The operands are both contextually converted to type bool.
9630 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9631 if (LHSRes.isInvalid())
9632 return InvalidOperands(Loc, LHS, RHS);
9635 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9636 if (RHSRes.isInvalid())
9637 return InvalidOperands(Loc, LHS, RHS);
9640 // C++ [expr.log.and]p2
9641 // C++ [expr.log.or]p2
9642 // The result is a bool.
9643 return Context.BoolTy;
9646 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9647 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9648 if (!ME) return false;
9649 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9650 ObjCMessageExpr *Base =
9651 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9652 if (!Base) return false;
9653 return Base->getMethodDecl() != nullptr;
9656 /// Is the given expression (which must be 'const') a reference to a
9657 /// variable which was originally non-const, but which has become
9658 /// 'const' due to being captured within a block?
9659 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9660 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9661 assert(E->isLValue() && E->getType().isConstQualified());
9662 E = E->IgnoreParens();
9664 // Must be a reference to a declaration from an enclosing scope.
9665 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9666 if (!DRE) return NCCK_None;
9667 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9669 // The declaration must be a variable which is not declared 'const'.
9670 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9671 if (!var) return NCCK_None;
9672 if (var->getType().isConstQualified()) return NCCK_None;
9673 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9675 // Decide whether the first capture was for a block or a lambda.
9676 DeclContext *DC = S.CurContext, *Prev = nullptr;
9677 // Decide whether the first capture was for a block or a lambda.
9679 // For init-capture, it is possible that the variable belongs to the
9680 // template pattern of the current context.
9681 if (auto *FD = dyn_cast<FunctionDecl>(DC))
9682 if (var->isInitCapture() &&
9683 FD->getTemplateInstantiationPattern() == var->getDeclContext())
9685 if (DC == var->getDeclContext())
9688 DC = DC->getParent();
9690 // Unless we have an init-capture, we've gone one step too far.
9691 if (!var->isInitCapture())
9693 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9696 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9697 Ty = Ty.getNonReferenceType();
9698 if (IsDereference && Ty->isPointerType())
9699 Ty = Ty->getPointeeType();
9700 return !Ty.isConstQualified();
9703 /// Emit the "read-only variable not assignable" error and print notes to give
9704 /// more information about why the variable is not assignable, such as pointing
9705 /// to the declaration of a const variable, showing that a method is const, or
9706 /// that the function is returning a const reference.
9707 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9708 SourceLocation Loc) {
9709 // Update err_typecheck_assign_const and note_typecheck_assign_const
9710 // when this enum is changed.
9716 ConstUnknown, // Keep as last element
9719 SourceRange ExprRange = E->getSourceRange();
9721 // Only emit one error on the first const found. All other consts will emit
9722 // a note to the error.
9723 bool DiagnosticEmitted = false;
9725 // Track if the current expression is the result of a derefence, and if the
9726 // next checked expression is the result of a derefence.
9727 bool IsDereference = false;
9728 bool NextIsDereference = false;
9730 // Loop to process MemberExpr chains.
9732 IsDereference = NextIsDereference;
9733 NextIsDereference = false;
9735 E = E->IgnoreParenImpCasts();
9736 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9737 NextIsDereference = ME->isArrow();
9738 const ValueDecl *VD = ME->getMemberDecl();
9739 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9740 // Mutable fields can be modified even if the class is const.
9741 if (Field->isMutable()) {
9742 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9746 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9747 if (!DiagnosticEmitted) {
9748 S.Diag(Loc, diag::err_typecheck_assign_const)
9749 << ExprRange << ConstMember << false /*static*/ << Field
9750 << Field->getType();
9751 DiagnosticEmitted = true;
9753 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9754 << ConstMember << false /*static*/ << Field << Field->getType()
9755 << Field->getSourceRange();
9759 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9760 if (VDecl->getType().isConstQualified()) {
9761 if (!DiagnosticEmitted) {
9762 S.Diag(Loc, diag::err_typecheck_assign_const)
9763 << ExprRange << ConstMember << true /*static*/ << VDecl
9764 << VDecl->getType();
9765 DiagnosticEmitted = true;
9767 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9768 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9769 << VDecl->getSourceRange();
9771 // Static fields do not inherit constness from parents.
9779 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9781 const FunctionDecl *FD = CE->getDirectCallee();
9782 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9783 if (!DiagnosticEmitted) {
9784 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9785 << ConstFunction << FD;
9786 DiagnosticEmitted = true;
9788 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9789 diag::note_typecheck_assign_const)
9790 << ConstFunction << FD << FD->getReturnType()
9791 << FD->getReturnTypeSourceRange();
9793 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9794 // Point to variable declaration.
9795 if (const ValueDecl *VD = DRE->getDecl()) {
9796 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9797 if (!DiagnosticEmitted) {
9798 S.Diag(Loc, diag::err_typecheck_assign_const)
9799 << ExprRange << ConstVariable << VD << VD->getType();
9800 DiagnosticEmitted = true;
9802 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9803 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9806 } else if (isa<CXXThisExpr>(E)) {
9807 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9808 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9809 if (MD->isConst()) {
9810 if (!DiagnosticEmitted) {
9811 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9812 << ConstMethod << MD;
9813 DiagnosticEmitted = true;
9815 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9816 << ConstMethod << MD << MD->getSourceRange();
9822 if (DiagnosticEmitted)
9825 // Can't determine a more specific message, so display the generic error.
9826 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9829 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
9830 /// emit an error and return true. If so, return false.
9831 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9832 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9834 S.CheckShadowingDeclModification(E, Loc);
9836 SourceLocation OrigLoc = Loc;
9837 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9839 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9840 IsLV = Expr::MLV_InvalidMessageExpression;
9841 if (IsLV == Expr::MLV_Valid)
9844 unsigned DiagID = 0;
9845 bool NeedType = false;
9846 switch (IsLV) { // C99 6.5.16p2
9847 case Expr::MLV_ConstQualified:
9848 // Use a specialized diagnostic when we're assigning to an object
9849 // from an enclosing function or block.
9850 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9851 if (NCCK == NCCK_Block)
9852 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9854 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9858 // In ARC, use some specialized diagnostics for occasions where we
9859 // infer 'const'. These are always pseudo-strong variables.
9860 if (S.getLangOpts().ObjCAutoRefCount) {
9861 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9862 if (declRef && isa<VarDecl>(declRef->getDecl())) {
9863 VarDecl *var = cast<VarDecl>(declRef->getDecl());
9865 // Use the normal diagnostic if it's pseudo-__strong but the
9866 // user actually wrote 'const'.
9867 if (var->isARCPseudoStrong() &&
9868 (!var->getTypeSourceInfo() ||
9869 !var->getTypeSourceInfo()->getType().isConstQualified())) {
9870 // There are two pseudo-strong cases:
9872 ObjCMethodDecl *method = S.getCurMethodDecl();
9873 if (method && var == method->getSelfDecl())
9874 DiagID = method->isClassMethod()
9875 ? diag::err_typecheck_arc_assign_self_class_method
9876 : diag::err_typecheck_arc_assign_self;
9878 // - fast enumeration variables
9880 DiagID = diag::err_typecheck_arr_assign_enumeration;
9884 Assign = SourceRange(OrigLoc, OrigLoc);
9885 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9886 // We need to preserve the AST regardless, so migration tool
9893 // If none of the special cases above are triggered, then this is a
9894 // simple const assignment.
9896 DiagnoseConstAssignment(S, E, Loc);
9901 case Expr::MLV_ConstAddrSpace:
9902 DiagnoseConstAssignment(S, E, Loc);
9904 case Expr::MLV_ArrayType:
9905 case Expr::MLV_ArrayTemporary:
9906 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9909 case Expr::MLV_NotObjectType:
9910 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9913 case Expr::MLV_LValueCast:
9914 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9916 case Expr::MLV_Valid:
9917 llvm_unreachable("did not take early return for MLV_Valid");
9918 case Expr::MLV_InvalidExpression:
9919 case Expr::MLV_MemberFunction:
9920 case Expr::MLV_ClassTemporary:
9921 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9923 case Expr::MLV_IncompleteType:
9924 case Expr::MLV_IncompleteVoidType:
9925 return S.RequireCompleteType(Loc, E->getType(),
9926 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9927 case Expr::MLV_DuplicateVectorComponents:
9928 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9930 case Expr::MLV_NoSetterProperty:
9931 llvm_unreachable("readonly properties should be processed differently");
9932 case Expr::MLV_InvalidMessageExpression:
9933 DiagID = diag::error_readonly_message_assignment;
9935 case Expr::MLV_SubObjCPropertySetting:
9936 DiagID = diag::error_no_subobject_property_setting;
9942 Assign = SourceRange(OrigLoc, OrigLoc);
9944 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9946 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9950 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9954 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9955 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9956 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9957 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9958 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9961 // Objective-C instance variables
9962 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9963 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9964 if (OL && OR && OL->getDecl() == OR->getDecl()) {
9965 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9966 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9967 if (RL && RR && RL->getDecl() == RR->getDecl())
9968 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9973 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9975 QualType CompoundType) {
9976 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9978 // Verify that LHS is a modifiable lvalue, and emit error if not.
9979 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9982 QualType LHSType = LHSExpr->getType();
9983 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9985 AssignConvertType ConvTy;
9986 if (CompoundType.isNull()) {
9987 Expr *RHSCheck = RHS.get();
9989 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9991 QualType LHSTy(LHSType);
9992 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9993 if (RHS.isInvalid())
9995 // Special case of NSObject attributes on c-style pointer types.
9996 if (ConvTy == IncompatiblePointer &&
9997 ((Context.isObjCNSObjectType(LHSType) &&
9998 RHSType->isObjCObjectPointerType()) ||
9999 (Context.isObjCNSObjectType(RHSType) &&
10000 LHSType->isObjCObjectPointerType())))
10001 ConvTy = Compatible;
10003 if (ConvTy == Compatible &&
10004 LHSType->isObjCObjectType())
10005 Diag(Loc, diag::err_objc_object_assignment)
10008 // If the RHS is a unary plus or minus, check to see if they = and + are
10009 // right next to each other. If so, the user may have typo'd "x =+ 4"
10010 // instead of "x += 4".
10011 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10012 RHSCheck = ICE->getSubExpr();
10013 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10014 if ((UO->getOpcode() == UO_Plus ||
10015 UO->getOpcode() == UO_Minus) &&
10016 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10017 // Only if the two operators are exactly adjacent.
10018 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10019 // And there is a space or other character before the subexpr of the
10020 // unary +/-. We don't want to warn on "x=-1".
10021 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10022 UO->getSubExpr()->getLocStart().isFileID()) {
10023 Diag(Loc, diag::warn_not_compound_assign)
10024 << (UO->getOpcode() == UO_Plus ? "+" : "-")
10025 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10029 if (ConvTy == Compatible) {
10030 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10031 // Warn about retain cycles where a block captures the LHS, but
10032 // not if the LHS is a simple variable into which the block is
10033 // being stored...unless that variable can be captured by reference!
10034 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10035 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10036 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10037 checkRetainCycles(LHSExpr, RHS.get());
10039 // It is safe to assign a weak reference into a strong variable.
10040 // Although this code can still have problems:
10041 // id x = self.weakProp;
10042 // id y = self.weakProp;
10043 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10044 // paths through the function. This should be revisited if
10045 // -Wrepeated-use-of-weak is made flow-sensitive.
10046 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10047 RHS.get()->getLocStart()))
10048 getCurFunction()->markSafeWeakUse(RHS.get());
10050 } else if (getLangOpts().ObjCAutoRefCount) {
10051 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10055 // Compound assignment "x += y"
10056 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10059 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10060 RHS.get(), AA_Assigning))
10063 CheckForNullPointerDereference(*this, LHSExpr);
10065 // C99 6.5.16p3: The type of an assignment expression is the type of the
10066 // left operand unless the left operand has qualified type, in which case
10067 // it is the unqualified version of the type of the left operand.
10068 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10069 // is converted to the type of the assignment expression (above).
10070 // C++ 5.17p1: the type of the assignment expression is that of its left
10072 return (getLangOpts().CPlusPlus
10073 ? LHSType : LHSType.getUnqualifiedType());
10076 // Only ignore explicit casts to void.
10077 static bool IgnoreCommaOperand(const Expr *E) {
10078 E = E->IgnoreParens();
10080 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10081 if (CE->getCastKind() == CK_ToVoid) {
10089 // Look for instances where it is likely the comma operator is confused with
10090 // another operator. There is a whitelist of acceptable expressions for the
10091 // left hand side of the comma operator, otherwise emit a warning.
10092 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10093 // No warnings in macros
10094 if (Loc.isMacroID())
10097 // Don't warn in template instantiations.
10098 if (!ActiveTemplateInstantiations.empty())
10101 // Scope isn't fine-grained enough to whitelist the specific cases, so
10102 // instead, skip more than needed, then call back into here with the
10103 // CommaVisitor in SemaStmt.cpp.
10104 // The whitelisted locations are the initialization and increment portions
10105 // of a for loop. The additional checks are on the condition of
10106 // if statements, do/while loops, and for loops.
10107 const unsigned ForIncrementFlags =
10108 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10109 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10110 const unsigned ScopeFlags = getCurScope()->getFlags();
10111 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10112 (ScopeFlags & ForInitFlags) == ForInitFlags)
10115 // If there are multiple comma operators used together, get the RHS of the
10116 // of the comma operator as the LHS.
10117 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10118 if (BO->getOpcode() != BO_Comma)
10120 LHS = BO->getRHS();
10123 // Only allow some expressions on LHS to not warn.
10124 if (IgnoreCommaOperand(LHS))
10127 Diag(Loc, diag::warn_comma_operator);
10128 Diag(LHS->getLocStart(), diag::note_cast_to_void)
10129 << LHS->getSourceRange()
10130 << FixItHint::CreateInsertion(LHS->getLocStart(),
10131 LangOpts.CPlusPlus ? "static_cast<void>("
10133 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10138 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10139 SourceLocation Loc) {
10140 LHS = S.CheckPlaceholderExpr(LHS.get());
10141 RHS = S.CheckPlaceholderExpr(RHS.get());
10142 if (LHS.isInvalid() || RHS.isInvalid())
10145 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10146 // operands, but not unary promotions.
10147 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10149 // So we treat the LHS as a ignored value, and in C++ we allow the
10150 // containing site to determine what should be done with the RHS.
10151 LHS = S.IgnoredValueConversions(LHS.get());
10152 if (LHS.isInvalid())
10155 S.DiagnoseUnusedExprResult(LHS.get());
10157 if (!S.getLangOpts().CPlusPlus) {
10158 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10159 if (RHS.isInvalid())
10161 if (!RHS.get()->getType()->isVoidType())
10162 S.RequireCompleteType(Loc, RHS.get()->getType(),
10163 diag::err_incomplete_type);
10166 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10167 S.DiagnoseCommaOperator(LHS.get(), Loc);
10169 return RHS.get()->getType();
10172 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10173 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10174 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10176 ExprObjectKind &OK,
10177 SourceLocation OpLoc,
10178 bool IsInc, bool IsPrefix) {
10179 if (Op->isTypeDependent())
10180 return S.Context.DependentTy;
10182 QualType ResType = Op->getType();
10183 // Atomic types can be used for increment / decrement where the non-atomic
10184 // versions can, so ignore the _Atomic() specifier for the purpose of
10186 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10187 ResType = ResAtomicType->getValueType();
10189 assert(!ResType.isNull() && "no type for increment/decrement expression");
10191 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10192 // Decrement of bool is not allowed.
10194 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10197 // Increment of bool sets it to true, but is deprecated.
10198 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10199 : diag::warn_increment_bool)
10200 << Op->getSourceRange();
10201 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10202 // Error on enum increments and decrements in C++ mode
10203 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10205 } else if (ResType->isRealType()) {
10207 } else if (ResType->isPointerType()) {
10208 // C99 6.5.2.4p2, 6.5.6p2
10209 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10211 } else if (ResType->isObjCObjectPointerType()) {
10212 // On modern runtimes, ObjC pointer arithmetic is forbidden.
10213 // Otherwise, we just need a complete type.
10214 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10215 checkArithmeticOnObjCPointer(S, OpLoc, Op))
10217 } else if (ResType->isAnyComplexType()) {
10218 // C99 does not support ++/-- on complex types, we allow as an extension.
10219 S.Diag(OpLoc, diag::ext_integer_increment_complex)
10220 << ResType << Op->getSourceRange();
10221 } else if (ResType->isPlaceholderType()) {
10222 ExprResult PR = S.CheckPlaceholderExpr(Op);
10223 if (PR.isInvalid()) return QualType();
10224 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10226 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10227 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10228 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10229 (ResType->getAs<VectorType>()->getVectorKind() !=
10230 VectorType::AltiVecBool)) {
10231 // The z vector extensions allow ++ and -- for non-bool vectors.
10232 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10233 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10234 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10236 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10237 << ResType << int(IsInc) << Op->getSourceRange();
10240 // At this point, we know we have a real, complex or pointer type.
10241 // Now make sure the operand is a modifiable lvalue.
10242 if (CheckForModifiableLvalue(Op, OpLoc, S))
10244 // In C++, a prefix increment is the same type as the operand. Otherwise
10245 // (in C or with postfix), the increment is the unqualified type of the
10247 if (IsPrefix && S.getLangOpts().CPlusPlus) {
10249 OK = Op->getObjectKind();
10253 return ResType.getUnqualifiedType();
10258 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10259 /// This routine allows us to typecheck complex/recursive expressions
10260 /// where the declaration is needed for type checking. We only need to
10261 /// handle cases when the expression references a function designator
10262 /// or is an lvalue. Here are some examples:
10264 /// - &*****f => f for f a function designator.
10266 /// - &s.zz[1].yy -> s, if zz is an array
10267 /// - *(x + 1) -> x, if x is an array
10268 /// - &"123"[2] -> 0
10269 /// - & __real__ x -> x
10270 static ValueDecl *getPrimaryDecl(Expr *E) {
10271 switch (E->getStmtClass()) {
10272 case Stmt::DeclRefExprClass:
10273 return cast<DeclRefExpr>(E)->getDecl();
10274 case Stmt::MemberExprClass:
10275 // If this is an arrow operator, the address is an offset from
10276 // the base's value, so the object the base refers to is
10278 if (cast<MemberExpr>(E)->isArrow())
10280 // Otherwise, the expression refers to a part of the base
10281 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10282 case Stmt::ArraySubscriptExprClass: {
10283 // FIXME: This code shouldn't be necessary! We should catch the implicit
10284 // promotion of register arrays earlier.
10285 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10286 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10287 if (ICE->getSubExpr()->getType()->isArrayType())
10288 return getPrimaryDecl(ICE->getSubExpr());
10292 case Stmt::UnaryOperatorClass: {
10293 UnaryOperator *UO = cast<UnaryOperator>(E);
10295 switch(UO->getOpcode()) {
10299 return getPrimaryDecl(UO->getSubExpr());
10304 case Stmt::ParenExprClass:
10305 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10306 case Stmt::ImplicitCastExprClass:
10307 // If the result of an implicit cast is an l-value, we care about
10308 // the sub-expression; otherwise, the result here doesn't matter.
10309 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10318 AO_Vector_Element = 1,
10319 AO_Property_Expansion = 2,
10320 AO_Register_Variable = 3,
10324 /// \brief Diagnose invalid operand for address of operations.
10326 /// \param Type The type of operand which cannot have its address taken.
10327 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10328 Expr *E, unsigned Type) {
10329 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10332 /// CheckAddressOfOperand - The operand of & must be either a function
10333 /// designator or an lvalue designating an object. If it is an lvalue, the
10334 /// object cannot be declared with storage class register or be a bit field.
10335 /// Note: The usual conversions are *not* applied to the operand of the &
10336 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10337 /// In C++, the operand might be an overloaded function name, in which case
10338 /// we allow the '&' but retain the overloaded-function type.
10339 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10340 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10341 if (PTy->getKind() == BuiltinType::Overload) {
10342 Expr *E = OrigOp.get()->IgnoreParens();
10343 if (!isa<OverloadExpr>(E)) {
10344 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10345 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10346 << OrigOp.get()->getSourceRange();
10350 OverloadExpr *Ovl = cast<OverloadExpr>(E);
10351 if (isa<UnresolvedMemberExpr>(Ovl))
10352 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10353 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10354 << OrigOp.get()->getSourceRange();
10358 return Context.OverloadTy;
10361 if (PTy->getKind() == BuiltinType::UnknownAny)
10362 return Context.UnknownAnyTy;
10364 if (PTy->getKind() == BuiltinType::BoundMember) {
10365 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10366 << OrigOp.get()->getSourceRange();
10370 OrigOp = CheckPlaceholderExpr(OrigOp.get());
10371 if (OrigOp.isInvalid()) return QualType();
10374 if (OrigOp.get()->isTypeDependent())
10375 return Context.DependentTy;
10377 assert(!OrigOp.get()->getType()->isPlaceholderType());
10379 // Make sure to ignore parentheses in subsequent checks
10380 Expr *op = OrigOp.get()->IgnoreParens();
10382 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10383 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10384 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10388 if (getLangOpts().C99) {
10389 // Implement C99-only parts of addressof rules.
10390 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10391 if (uOp->getOpcode() == UO_Deref)
10392 // Per C99 6.5.3.2, the address of a deref always returns a valid result
10393 // (assuming the deref expression is valid).
10394 return uOp->getSubExpr()->getType();
10396 // Technically, there should be a check for array subscript
10397 // expressions here, but the result of one is always an lvalue anyway.
10399 ValueDecl *dcl = getPrimaryDecl(op);
10401 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10402 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10403 op->getLocStart()))
10406 Expr::LValueClassification lval = op->ClassifyLValue(Context);
10407 unsigned AddressOfError = AO_No_Error;
10409 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10410 bool sfinae = (bool)isSFINAEContext();
10411 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10412 : diag::ext_typecheck_addrof_temporary)
10413 << op->getType() << op->getSourceRange();
10416 // Materialize the temporary as an lvalue so that we can take its address.
10418 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10419 } else if (isa<ObjCSelectorExpr>(op)) {
10420 return Context.getPointerType(op->getType());
10421 } else if (lval == Expr::LV_MemberFunction) {
10422 // If it's an instance method, make a member pointer.
10423 // The expression must have exactly the form &A::foo.
10425 // If the underlying expression isn't a decl ref, give up.
10426 if (!isa<DeclRefExpr>(op)) {
10427 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10428 << OrigOp.get()->getSourceRange();
10431 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10432 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10434 // The id-expression was parenthesized.
10435 if (OrigOp.get() != DRE) {
10436 Diag(OpLoc, diag::err_parens_pointer_member_function)
10437 << OrigOp.get()->getSourceRange();
10439 // The method was named without a qualifier.
10440 } else if (!DRE->getQualifier()) {
10441 if (MD->getParent()->getName().empty())
10442 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10443 << op->getSourceRange();
10445 SmallString<32> Str;
10446 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10447 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10448 << op->getSourceRange()
10449 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10453 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10454 if (isa<CXXDestructorDecl>(MD))
10455 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10457 QualType MPTy = Context.getMemberPointerType(
10458 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10459 // Under the MS ABI, lock down the inheritance model now.
10460 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10461 (void)isCompleteType(OpLoc, MPTy);
10463 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10465 // The operand must be either an l-value or a function designator
10466 if (!op->getType()->isFunctionType()) {
10467 // Use a special diagnostic for loads from property references.
10468 if (isa<PseudoObjectExpr>(op)) {
10469 AddressOfError = AO_Property_Expansion;
10471 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10472 << op->getType() << op->getSourceRange();
10476 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10477 // The operand cannot be a bit-field
10478 AddressOfError = AO_Bit_Field;
10479 } else if (op->getObjectKind() == OK_VectorComponent) {
10480 // The operand cannot be an element of a vector
10481 AddressOfError = AO_Vector_Element;
10482 } else if (dcl) { // C99 6.5.3.2p1
10483 // We have an lvalue with a decl. Make sure the decl is not declared
10484 // with the register storage-class specifier.
10485 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10486 // in C++ it is not error to take address of a register
10487 // variable (c++03 7.1.1P3)
10488 if (vd->getStorageClass() == SC_Register &&
10489 !getLangOpts().CPlusPlus) {
10490 AddressOfError = AO_Register_Variable;
10492 } else if (isa<MSPropertyDecl>(dcl)) {
10493 AddressOfError = AO_Property_Expansion;
10494 } else if (isa<FunctionTemplateDecl>(dcl)) {
10495 return Context.OverloadTy;
10496 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10497 // Okay: we can take the address of a field.
10498 // Could be a pointer to member, though, if there is an explicit
10499 // scope qualifier for the class.
10500 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10501 DeclContext *Ctx = dcl->getDeclContext();
10502 if (Ctx && Ctx->isRecord()) {
10503 if (dcl->getType()->isReferenceType()) {
10505 diag::err_cannot_form_pointer_to_member_of_reference_type)
10506 << dcl->getDeclName() << dcl->getType();
10510 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10511 Ctx = Ctx->getParent();
10513 QualType MPTy = Context.getMemberPointerType(
10515 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10516 // Under the MS ABI, lock down the inheritance model now.
10517 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10518 (void)isCompleteType(OpLoc, MPTy);
10522 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
10523 llvm_unreachable("Unknown/unexpected decl type");
10526 if (AddressOfError != AO_No_Error) {
10527 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10531 if (lval == Expr::LV_IncompleteVoidType) {
10532 // Taking the address of a void variable is technically illegal, but we
10533 // allow it in cases which are otherwise valid.
10534 // Example: "extern void x; void* y = &x;".
10535 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10538 // If the operand has type "type", the result has type "pointer to type".
10539 if (op->getType()->isObjCObjectType())
10540 return Context.getObjCObjectPointerType(op->getType());
10542 return Context.getPointerType(op->getType());
10545 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10546 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10549 const Decl *D = DRE->getDecl();
10552 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10555 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10556 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10558 if (FunctionScopeInfo *FD = S.getCurFunction())
10559 if (!FD->ModifiedNonNullParams.count(Param))
10560 FD->ModifiedNonNullParams.insert(Param);
10563 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10564 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10565 SourceLocation OpLoc) {
10566 if (Op->isTypeDependent())
10567 return S.Context.DependentTy;
10569 ExprResult ConvResult = S.UsualUnaryConversions(Op);
10570 if (ConvResult.isInvalid())
10572 Op = ConvResult.get();
10573 QualType OpTy = Op->getType();
10576 if (isa<CXXReinterpretCastExpr>(Op)) {
10577 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10578 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10579 Op->getSourceRange());
10582 if (const PointerType *PT = OpTy->getAs<PointerType>())
10584 Result = PT->getPointeeType();
10586 else if (const ObjCObjectPointerType *OPT =
10587 OpTy->getAs<ObjCObjectPointerType>())
10588 Result = OPT->getPointeeType();
10590 ExprResult PR = S.CheckPlaceholderExpr(Op);
10591 if (PR.isInvalid()) return QualType();
10592 if (PR.get() != Op)
10593 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10596 if (Result.isNull()) {
10597 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10598 << OpTy << Op->getSourceRange();
10602 // Note that per both C89 and C99, indirection is always legal, even if Result
10603 // is an incomplete type or void. It would be possible to warn about
10604 // dereferencing a void pointer, but it's completely well-defined, and such a
10605 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10606 // for pointers to 'void' but is fine for any other pointer type:
10608 // C++ [expr.unary.op]p1:
10609 // [...] the expression to which [the unary * operator] is applied shall
10610 // be a pointer to an object type, or a pointer to a function type
10611 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10612 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10613 << OpTy << Op->getSourceRange();
10615 // Dereferences are usually l-values...
10618 // ...except that certain expressions are never l-values in C.
10619 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10625 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10626 BinaryOperatorKind Opc;
10628 default: llvm_unreachable("Unknown binop!");
10629 case tok::periodstar: Opc = BO_PtrMemD; break;
10630 case tok::arrowstar: Opc = BO_PtrMemI; break;
10631 case tok::star: Opc = BO_Mul; break;
10632 case tok::slash: Opc = BO_Div; break;
10633 case tok::percent: Opc = BO_Rem; break;
10634 case tok::plus: Opc = BO_Add; break;
10635 case tok::minus: Opc = BO_Sub; break;
10636 case tok::lessless: Opc = BO_Shl; break;
10637 case tok::greatergreater: Opc = BO_Shr; break;
10638 case tok::lessequal: Opc = BO_LE; break;
10639 case tok::less: Opc = BO_LT; break;
10640 case tok::greaterequal: Opc = BO_GE; break;
10641 case tok::greater: Opc = BO_GT; break;
10642 case tok::exclaimequal: Opc = BO_NE; break;
10643 case tok::equalequal: Opc = BO_EQ; break;
10644 case tok::amp: Opc = BO_And; break;
10645 case tok::caret: Opc = BO_Xor; break;
10646 case tok::pipe: Opc = BO_Or; break;
10647 case tok::ampamp: Opc = BO_LAnd; break;
10648 case tok::pipepipe: Opc = BO_LOr; break;
10649 case tok::equal: Opc = BO_Assign; break;
10650 case tok::starequal: Opc = BO_MulAssign; break;
10651 case tok::slashequal: Opc = BO_DivAssign; break;
10652 case tok::percentequal: Opc = BO_RemAssign; break;
10653 case tok::plusequal: Opc = BO_AddAssign; break;
10654 case tok::minusequal: Opc = BO_SubAssign; break;
10655 case tok::lesslessequal: Opc = BO_ShlAssign; break;
10656 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
10657 case tok::ampequal: Opc = BO_AndAssign; break;
10658 case tok::caretequal: Opc = BO_XorAssign; break;
10659 case tok::pipeequal: Opc = BO_OrAssign; break;
10660 case tok::comma: Opc = BO_Comma; break;
10665 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10666 tok::TokenKind Kind) {
10667 UnaryOperatorKind Opc;
10669 default: llvm_unreachable("Unknown unary op!");
10670 case tok::plusplus: Opc = UO_PreInc; break;
10671 case tok::minusminus: Opc = UO_PreDec; break;
10672 case tok::amp: Opc = UO_AddrOf; break;
10673 case tok::star: Opc = UO_Deref; break;
10674 case tok::plus: Opc = UO_Plus; break;
10675 case tok::minus: Opc = UO_Minus; break;
10676 case tok::tilde: Opc = UO_Not; break;
10677 case tok::exclaim: Opc = UO_LNot; break;
10678 case tok::kw___real: Opc = UO_Real; break;
10679 case tok::kw___imag: Opc = UO_Imag; break;
10680 case tok::kw___extension__: Opc = UO_Extension; break;
10685 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10686 /// This warning is only emitted for builtin assignment operations. It is also
10687 /// suppressed in the event of macro expansions.
10688 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10689 SourceLocation OpLoc) {
10690 if (!S.ActiveTemplateInstantiations.empty())
10692 if (OpLoc.isInvalid() || OpLoc.isMacroID())
10694 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10695 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10696 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10697 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10698 if (!LHSDeclRef || !RHSDeclRef ||
10699 LHSDeclRef->getLocation().isMacroID() ||
10700 RHSDeclRef->getLocation().isMacroID())
10702 const ValueDecl *LHSDecl =
10703 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10704 const ValueDecl *RHSDecl =
10705 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10706 if (LHSDecl != RHSDecl)
10708 if (LHSDecl->getType().isVolatileQualified())
10710 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10711 if (RefTy->getPointeeType().isVolatileQualified())
10714 S.Diag(OpLoc, diag::warn_self_assignment)
10715 << LHSDeclRef->getType()
10716 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10719 /// Check if a bitwise-& is performed on an Objective-C pointer. This
10720 /// is usually indicative of introspection within the Objective-C pointer.
10721 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10722 SourceLocation OpLoc) {
10723 if (!S.getLangOpts().ObjC1)
10726 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10727 const Expr *LHS = L.get();
10728 const Expr *RHS = R.get();
10730 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10731 ObjCPointerExpr = LHS;
10734 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10735 ObjCPointerExpr = RHS;
10739 // This warning is deliberately made very specific to reduce false
10740 // positives with logic that uses '&' for hashing. This logic mainly
10741 // looks for code trying to introspect into tagged pointers, which
10742 // code should generally never do.
10743 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10744 unsigned Diag = diag::warn_objc_pointer_masking;
10745 // Determine if we are introspecting the result of performSelectorXXX.
10746 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10747 // Special case messages to -performSelector and friends, which
10748 // can return non-pointer values boxed in a pointer value.
10749 // Some clients may wish to silence warnings in this subcase.
10750 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10751 Selector S = ME->getSelector();
10752 StringRef SelArg0 = S.getNameForSlot(0);
10753 if (SelArg0.startswith("performSelector"))
10754 Diag = diag::warn_objc_pointer_masking_performSelector;
10757 S.Diag(OpLoc, Diag)
10758 << ObjCPointerExpr->getSourceRange();
10762 static NamedDecl *getDeclFromExpr(Expr *E) {
10765 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10766 return DRE->getDecl();
10767 if (auto *ME = dyn_cast<MemberExpr>(E))
10768 return ME->getMemberDecl();
10769 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10770 return IRE->getDecl();
10774 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10775 /// operator @p Opc at location @c TokLoc. This routine only supports
10776 /// built-in operations; ActOnBinOp handles overloaded operators.
10777 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10778 BinaryOperatorKind Opc,
10779 Expr *LHSExpr, Expr *RHSExpr) {
10780 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10781 // The syntax only allows initializer lists on the RHS of assignment,
10782 // so we don't need to worry about accepting invalid code for
10783 // non-assignment operators.
10785 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10786 // of x = {} is x = T().
10787 InitializationKind Kind =
10788 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10789 InitializedEntity Entity =
10790 InitializedEntity::InitializeTemporary(LHSExpr->getType());
10791 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10792 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10793 if (Init.isInvalid())
10795 RHSExpr = Init.get();
10798 ExprResult LHS = LHSExpr, RHS = RHSExpr;
10799 QualType ResultTy; // Result type of the binary operator.
10800 // The following two variables are used for compound assignment operators
10801 QualType CompLHSTy; // Type of LHS after promotions for computation
10802 QualType CompResultTy; // Type of computation result
10803 ExprValueKind VK = VK_RValue;
10804 ExprObjectKind OK = OK_Ordinary;
10806 if (!getLangOpts().CPlusPlus) {
10807 // C cannot handle TypoExpr nodes on either side of a binop because it
10808 // doesn't handle dependent types properly, so make sure any TypoExprs have
10809 // been dealt with before checking the operands.
10810 LHS = CorrectDelayedTyposInExpr(LHSExpr);
10811 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10812 if (Opc != BO_Assign)
10813 return ExprResult(E);
10814 // Avoid correcting the RHS to the same Expr as the LHS.
10815 Decl *D = getDeclFromExpr(E);
10816 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10818 if (!LHS.isUsable() || !RHS.isUsable())
10819 return ExprError();
10822 if (getLangOpts().OpenCL) {
10823 QualType LHSTy = LHSExpr->getType();
10824 QualType RHSTy = RHSExpr->getType();
10825 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10826 // the ATOMIC_VAR_INIT macro.
10827 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
10828 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10829 if (BO_Assign == Opc)
10830 Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10832 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10833 return ExprError();
10836 // OpenCL special types - image, sampler, pipe, and blocks are to be used
10837 // only with a builtin functions and therefore should be disallowed here.
10838 if (LHSTy->isImageType() || RHSTy->isImageType() ||
10839 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
10840 LHSTy->isPipeType() || RHSTy->isPipeType() ||
10841 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
10842 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10843 return ExprError();
10849 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10850 if (getLangOpts().CPlusPlus &&
10851 LHS.get()->getObjectKind() != OK_ObjCProperty) {
10852 VK = LHS.get()->getValueKind();
10853 OK = LHS.get()->getObjectKind();
10855 if (!ResultTy.isNull()) {
10856 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10857 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10859 RecordModifiableNonNullParam(*this, LHS.get());
10863 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10864 Opc == BO_PtrMemI);
10868 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10872 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10875 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10878 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10882 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10888 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10892 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10895 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10898 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10902 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10906 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10907 Opc == BO_DivAssign);
10908 CompLHSTy = CompResultTy;
10909 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10910 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10913 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10914 CompLHSTy = CompResultTy;
10915 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10916 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10919 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10920 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10921 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10924 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10925 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10926 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10930 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10931 CompLHSTy = CompResultTy;
10932 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10933 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10936 case BO_OrAssign: // fallthrough
10937 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10939 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10940 CompLHSTy = CompResultTy;
10941 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10942 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10945 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10946 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10947 VK = RHS.get()->getValueKind();
10948 OK = RHS.get()->getObjectKind();
10952 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10953 return ExprError();
10955 // Check for array bounds violations for both sides of the BinaryOperator
10956 CheckArrayAccess(LHS.get());
10957 CheckArrayAccess(RHS.get());
10959 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10960 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10961 &Context.Idents.get("object_setClass"),
10962 SourceLocation(), LookupOrdinaryName);
10963 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10964 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
10965 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10966 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10967 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10968 FixItHint::CreateInsertion(RHSLocEnd, ")");
10971 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10973 else if (const ObjCIvarRefExpr *OIRE =
10974 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10975 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10977 if (CompResultTy.isNull())
10978 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10979 OK, OpLoc, FPFeatures.fp_contract);
10980 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10983 OK = LHS.get()->getObjectKind();
10985 return new (Context) CompoundAssignOperator(
10986 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10987 OpLoc, FPFeatures.fp_contract);
10990 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10991 /// operators are mixed in a way that suggests that the programmer forgot that
10992 /// comparison operators have higher precedence. The most typical example of
10993 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
10994 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10995 SourceLocation OpLoc, Expr *LHSExpr,
10997 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10998 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11000 // Check that one of the sides is a comparison operator and the other isn't.
11001 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11002 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11003 if (isLeftComp == isRightComp)
11006 // Bitwise operations are sometimes used as eager logical ops.
11007 // Don't diagnose this.
11008 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11009 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11010 if (isLeftBitwise || isRightBitwise)
11013 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11015 : SourceRange(OpLoc, RHSExpr->getLocEnd());
11016 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11017 SourceRange ParensRange = isLeftComp ?
11018 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11019 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11021 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11022 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11023 SuggestParentheses(Self, OpLoc,
11024 Self.PDiag(diag::note_precedence_silence) << OpStr,
11025 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11026 SuggestParentheses(Self, OpLoc,
11027 Self.PDiag(diag::note_precedence_bitwise_first)
11028 << BinaryOperator::getOpcodeStr(Opc),
11032 /// \brief It accepts a '&&' expr that is inside a '||' one.
11033 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11034 /// in parentheses.
11036 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11037 BinaryOperator *Bop) {
11038 assert(Bop->getOpcode() == BO_LAnd);
11039 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11040 << Bop->getSourceRange() << OpLoc;
11041 SuggestParentheses(Self, Bop->getOperatorLoc(),
11042 Self.PDiag(diag::note_precedence_silence)
11043 << Bop->getOpcodeStr(),
11044 Bop->getSourceRange());
11047 /// \brief Returns true if the given expression can be evaluated as a constant
11049 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11051 return !E->isValueDependent() &&
11052 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11055 /// \brief Returns true if the given expression can be evaluated as a constant
11057 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11059 return !E->isValueDependent() &&
11060 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11063 /// \brief Look for '&&' in the left hand of a '||' expr.
11064 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11065 Expr *LHSExpr, Expr *RHSExpr) {
11066 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11067 if (Bop->getOpcode() == BO_LAnd) {
11068 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11069 if (EvaluatesAsFalse(S, RHSExpr))
11071 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11072 if (!EvaluatesAsTrue(S, Bop->getLHS()))
11073 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11074 } else if (Bop->getOpcode() == BO_LOr) {
11075 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11076 // If it's "a || b && 1 || c" we didn't warn earlier for
11077 // "a || b && 1", but warn now.
11078 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11079 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11085 /// \brief Look for '&&' in the right hand of a '||' expr.
11086 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11087 Expr *LHSExpr, Expr *RHSExpr) {
11088 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11089 if (Bop->getOpcode() == BO_LAnd) {
11090 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11091 if (EvaluatesAsFalse(S, LHSExpr))
11093 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11094 if (!EvaluatesAsTrue(S, Bop->getRHS()))
11095 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11100 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11101 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11102 /// the '&' expression in parentheses.
11103 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11104 SourceLocation OpLoc, Expr *SubExpr) {
11105 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11106 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11107 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11108 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11109 << Bop->getSourceRange() << OpLoc;
11110 SuggestParentheses(S, Bop->getOperatorLoc(),
11111 S.PDiag(diag::note_precedence_silence)
11112 << Bop->getOpcodeStr(),
11113 Bop->getSourceRange());
11118 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11119 Expr *SubExpr, StringRef Shift) {
11120 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11121 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11122 StringRef Op = Bop->getOpcodeStr();
11123 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11124 << Bop->getSourceRange() << OpLoc << Shift << Op;
11125 SuggestParentheses(S, Bop->getOperatorLoc(),
11126 S.PDiag(diag::note_precedence_silence) << Op,
11127 Bop->getSourceRange());
11132 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11133 Expr *LHSExpr, Expr *RHSExpr) {
11134 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11138 FunctionDecl *FD = OCE->getDirectCallee();
11139 if (!FD || !FD->isOverloadedOperator())
11142 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11143 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11146 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11147 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11148 << (Kind == OO_LessLess);
11149 SuggestParentheses(S, OCE->getOperatorLoc(),
11150 S.PDiag(diag::note_precedence_silence)
11151 << (Kind == OO_LessLess ? "<<" : ">>"),
11152 OCE->getSourceRange());
11153 SuggestParentheses(S, OpLoc,
11154 S.PDiag(diag::note_evaluate_comparison_first),
11155 SourceRange(OCE->getArg(1)->getLocStart(),
11156 RHSExpr->getLocEnd()));
11159 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11161 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11162 SourceLocation OpLoc, Expr *LHSExpr,
11164 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11165 if (BinaryOperator::isBitwiseOp(Opc))
11166 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11168 // Diagnose "arg1 & arg2 | arg3"
11169 if ((Opc == BO_Or || Opc == BO_Xor) &&
11170 !OpLoc.isMacroID()/* Don't warn in macros. */) {
11171 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11172 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11175 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11176 // We don't warn for 'assert(a || b && "bad")' since this is safe.
11177 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11178 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11179 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11182 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11183 || Opc == BO_Shr) {
11184 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11185 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11186 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11189 // Warn on overloaded shift operators and comparisons, such as:
11191 if (BinaryOperator::isComparisonOp(Opc))
11192 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11195 // Binary Operators. 'Tok' is the token for the operator.
11196 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11197 tok::TokenKind Kind,
11198 Expr *LHSExpr, Expr *RHSExpr) {
11199 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11200 assert(LHSExpr && "ActOnBinOp(): missing left expression");
11201 assert(RHSExpr && "ActOnBinOp(): missing right expression");
11203 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11204 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11206 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11209 /// Build an overloaded binary operator expression in the given scope.
11210 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11211 BinaryOperatorKind Opc,
11212 Expr *LHS, Expr *RHS) {
11213 // Find all of the overloaded operators visible from this
11214 // point. We perform both an operator-name lookup from the local
11215 // scope and an argument-dependent lookup based on the types of
11217 UnresolvedSet<16> Functions;
11218 OverloadedOperatorKind OverOp
11219 = BinaryOperator::getOverloadedOperator(Opc);
11220 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11221 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11222 RHS->getType(), Functions);
11224 // Build the (potentially-overloaded, potentially-dependent)
11225 // binary operation.
11226 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11229 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11230 BinaryOperatorKind Opc,
11231 Expr *LHSExpr, Expr *RHSExpr) {
11232 // We want to end up calling one of checkPseudoObjectAssignment
11233 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11234 // both expressions are overloadable or either is type-dependent),
11235 // or CreateBuiltinBinOp (in any other case). We also want to get
11236 // any placeholder types out of the way.
11238 // Handle pseudo-objects in the LHS.
11239 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11240 // Assignments with a pseudo-object l-value need special analysis.
11241 if (pty->getKind() == BuiltinType::PseudoObject &&
11242 BinaryOperator::isAssignmentOp(Opc))
11243 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11245 // Don't resolve overloads if the other type is overloadable.
11246 if (pty->getKind() == BuiltinType::Overload) {
11247 // We can't actually test that if we still have a placeholder,
11248 // though. Fortunately, none of the exceptions we see in that
11249 // code below are valid when the LHS is an overload set. Note
11250 // that an overload set can be dependently-typed, but it never
11251 // instantiates to having an overloadable type.
11252 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11253 if (resolvedRHS.isInvalid()) return ExprError();
11254 RHSExpr = resolvedRHS.get();
11256 if (RHSExpr->isTypeDependent() ||
11257 RHSExpr->getType()->isOverloadableType())
11258 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11261 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11262 if (LHS.isInvalid()) return ExprError();
11263 LHSExpr = LHS.get();
11266 // Handle pseudo-objects in the RHS.
11267 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11268 // An overload in the RHS can potentially be resolved by the type
11269 // being assigned to.
11270 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11271 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11272 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11274 if (LHSExpr->getType()->isOverloadableType())
11275 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11277 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11280 // Don't resolve overloads if the other type is overloadable.
11281 if (pty->getKind() == BuiltinType::Overload &&
11282 LHSExpr->getType()->isOverloadableType())
11283 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11285 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11286 if (!resolvedRHS.isUsable()) return ExprError();
11287 RHSExpr = resolvedRHS.get();
11290 if (getLangOpts().CPlusPlus) {
11291 // If either expression is type-dependent, always build an
11293 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11294 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11296 // Otherwise, build an overloaded op if either expression has an
11297 // overloadable type.
11298 if (LHSExpr->getType()->isOverloadableType() ||
11299 RHSExpr->getType()->isOverloadableType())
11300 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11303 // Build a built-in binary operation.
11304 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11307 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11308 UnaryOperatorKind Opc,
11310 ExprResult Input = InputExpr;
11311 ExprValueKind VK = VK_RValue;
11312 ExprObjectKind OK = OK_Ordinary;
11313 QualType resultType;
11314 if (getLangOpts().OpenCL) {
11315 QualType Ty = InputExpr->getType();
11316 // The only legal unary operation for atomics is '&'.
11317 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11318 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11319 // only with a builtin functions and therefore should be disallowed here.
11320 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11321 || Ty->isBlockPointerType())) {
11322 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11323 << InputExpr->getType()
11324 << Input.get()->getSourceRange());
11332 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11334 Opc == UO_PreInc ||
11336 Opc == UO_PreInc ||
11340 resultType = CheckAddressOfOperand(Input, OpLoc);
11341 RecordModifiableNonNullParam(*this, InputExpr);
11344 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11345 if (Input.isInvalid()) return ExprError();
11346 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11351 Input = UsualUnaryConversions(Input.get());
11352 if (Input.isInvalid()) return ExprError();
11353 resultType = Input.get()->getType();
11354 if (resultType->isDependentType())
11356 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11358 else if (resultType->isVectorType() &&
11359 // The z vector extensions don't allow + or - with bool vectors.
11360 (!Context.getLangOpts().ZVector ||
11361 resultType->getAs<VectorType>()->getVectorKind() !=
11362 VectorType::AltiVecBool))
11364 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11366 resultType->isPointerType())
11369 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11370 << resultType << Input.get()->getSourceRange());
11372 case UO_Not: // bitwise complement
11373 Input = UsualUnaryConversions(Input.get());
11374 if (Input.isInvalid())
11375 return ExprError();
11376 resultType = Input.get()->getType();
11377 if (resultType->isDependentType())
11379 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11380 if (resultType->isComplexType() || resultType->isComplexIntegerType())
11381 // C99 does not support '~' for complex conjugation.
11382 Diag(OpLoc, diag::ext_integer_complement_complex)
11383 << resultType << Input.get()->getSourceRange();
11384 else if (resultType->hasIntegerRepresentation())
11386 else if (resultType->isExtVectorType()) {
11387 if (Context.getLangOpts().OpenCL) {
11388 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11389 // on vector float types.
11390 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11391 if (!T->isIntegerType())
11392 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11393 << resultType << Input.get()->getSourceRange());
11397 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11398 << resultType << Input.get()->getSourceRange());
11402 case UO_LNot: // logical negation
11403 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11404 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11405 if (Input.isInvalid()) return ExprError();
11406 resultType = Input.get()->getType();
11408 // Though we still have to promote half FP to float...
11409 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11410 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11411 resultType = Context.FloatTy;
11414 if (resultType->isDependentType())
11416 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11417 // C99 6.5.3.3p1: ok, fallthrough;
11418 if (Context.getLangOpts().CPlusPlus) {
11419 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11420 // operand contextually converted to bool.
11421 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11422 ScalarTypeToBooleanCastKind(resultType));
11423 } else if (Context.getLangOpts().OpenCL &&
11424 Context.getLangOpts().OpenCLVersion < 120) {
11425 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11426 // operate on scalar float types.
11427 if (!resultType->isIntegerType())
11428 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11429 << resultType << Input.get()->getSourceRange());
11431 } else if (resultType->isExtVectorType()) {
11432 if (Context.getLangOpts().OpenCL &&
11433 Context.getLangOpts().OpenCLVersion < 120) {
11434 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11435 // operate on vector float types.
11436 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11437 if (!T->isIntegerType())
11438 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11439 << resultType << Input.get()->getSourceRange());
11441 // Vector logical not returns the signed variant of the operand type.
11442 resultType = GetSignedVectorType(resultType);
11445 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11446 << resultType << Input.get()->getSourceRange());
11449 // LNot always has type int. C99 6.5.3.3p5.
11450 // In C++, it's bool. C++ 5.3.1p8
11451 resultType = Context.getLogicalOperationType();
11455 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11456 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11457 // complex l-values to ordinary l-values and all other values to r-values.
11458 if (Input.isInvalid()) return ExprError();
11459 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11460 if (Input.get()->getValueKind() != VK_RValue &&
11461 Input.get()->getObjectKind() == OK_Ordinary)
11462 VK = Input.get()->getValueKind();
11463 } else if (!getLangOpts().CPlusPlus) {
11464 // In C, a volatile scalar is read by __imag. In C++, it is not.
11465 Input = DefaultLvalueConversion(Input.get());
11470 resultType = Input.get()->getType();
11471 VK = Input.get()->getValueKind();
11472 OK = Input.get()->getObjectKind();
11475 if (resultType.isNull() || Input.isInvalid())
11476 return ExprError();
11478 // Check for array bounds violations in the operand of the UnaryOperator,
11479 // except for the '*' and '&' operators that have to be handled specially
11480 // by CheckArrayAccess (as there are special cases like &array[arraysize]
11481 // that are explicitly defined as valid by the standard).
11482 if (Opc != UO_AddrOf && Opc != UO_Deref)
11483 CheckArrayAccess(Input.get());
11485 return new (Context)
11486 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11489 /// \brief Determine whether the given expression is a qualified member
11490 /// access expression, of a form that could be turned into a pointer to member
11491 /// with the address-of operator.
11492 static bool isQualifiedMemberAccess(Expr *E) {
11493 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11494 if (!DRE->getQualifier())
11497 ValueDecl *VD = DRE->getDecl();
11498 if (!VD->isCXXClassMember())
11501 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11503 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11504 return Method->isInstance();
11509 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11510 if (!ULE->getQualifier())
11513 for (NamedDecl *D : ULE->decls()) {
11514 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11515 if (Method->isInstance())
11518 // Overload set does not contain methods.
11529 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11530 UnaryOperatorKind Opc, Expr *Input) {
11531 // First things first: handle placeholders so that the
11532 // overloaded-operator check considers the right type.
11533 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11534 // Increment and decrement of pseudo-object references.
11535 if (pty->getKind() == BuiltinType::PseudoObject &&
11536 UnaryOperator::isIncrementDecrementOp(Opc))
11537 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11539 // extension is always a builtin operator.
11540 if (Opc == UO_Extension)
11541 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11543 // & gets special logic for several kinds of placeholder.
11544 // The builtin code knows what to do.
11545 if (Opc == UO_AddrOf &&
11546 (pty->getKind() == BuiltinType::Overload ||
11547 pty->getKind() == BuiltinType::UnknownAny ||
11548 pty->getKind() == BuiltinType::BoundMember))
11549 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11551 // Anything else needs to be handled now.
11552 ExprResult Result = CheckPlaceholderExpr(Input);
11553 if (Result.isInvalid()) return ExprError();
11554 Input = Result.get();
11557 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11558 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11559 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11560 // Find all of the overloaded operators visible from this
11561 // point. We perform both an operator-name lookup from the local
11562 // scope and an argument-dependent lookup based on the types of
11564 UnresolvedSet<16> Functions;
11565 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11566 if (S && OverOp != OO_None)
11567 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11570 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11573 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11576 // Unary Operators. 'Tok' is the token for the operator.
11577 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11578 tok::TokenKind Op, Expr *Input) {
11579 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11582 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11583 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11584 LabelDecl *TheDecl) {
11585 TheDecl->markUsed(Context);
11586 // Create the AST node. The address of a label always has type 'void*'.
11587 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11588 Context.getPointerType(Context.VoidTy));
11591 /// Given the last statement in a statement-expression, check whether
11592 /// the result is a producing expression (like a call to an
11593 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11594 /// release out of the full-expression. Otherwise, return null.
11596 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11597 // Should always be wrapped with one of these.
11598 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11599 if (!cleanups) return nullptr;
11601 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11602 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11605 // Splice out the cast. This shouldn't modify any interesting
11606 // features of the statement.
11607 Expr *producer = cast->getSubExpr();
11608 assert(producer->getType() == cast->getType());
11609 assert(producer->getValueKind() == cast->getValueKind());
11610 cleanups->setSubExpr(producer);
11614 void Sema::ActOnStartStmtExpr() {
11615 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11618 void Sema::ActOnStmtExprError() {
11619 // Note that function is also called by TreeTransform when leaving a
11620 // StmtExpr scope without rebuilding anything.
11622 DiscardCleanupsInEvaluationContext();
11623 PopExpressionEvaluationContext();
11627 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11628 SourceLocation RPLoc) { // "({..})"
11629 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11630 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11632 if (hasAnyUnrecoverableErrorsInThisFunction())
11633 DiscardCleanupsInEvaluationContext();
11634 assert(!Cleanup.exprNeedsCleanups() &&
11635 "cleanups within StmtExpr not correctly bound!");
11636 PopExpressionEvaluationContext();
11638 // FIXME: there are a variety of strange constraints to enforce here, for
11639 // example, it is not possible to goto into a stmt expression apparently.
11640 // More semantic analysis is needed.
11642 // If there are sub-stmts in the compound stmt, take the type of the last one
11643 // as the type of the stmtexpr.
11644 QualType Ty = Context.VoidTy;
11645 bool StmtExprMayBindToTemp = false;
11646 if (!Compound->body_empty()) {
11647 Stmt *LastStmt = Compound->body_back();
11648 LabelStmt *LastLabelStmt = nullptr;
11649 // If LastStmt is a label, skip down through into the body.
11650 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11651 LastLabelStmt = Label;
11652 LastStmt = Label->getSubStmt();
11655 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11656 // Do function/array conversion on the last expression, but not
11657 // lvalue-to-rvalue. However, initialize an unqualified type.
11658 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11659 if (LastExpr.isInvalid())
11660 return ExprError();
11661 Ty = LastExpr.get()->getType().getUnqualifiedType();
11663 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11664 // In ARC, if the final expression ends in a consume, splice
11665 // the consume out and bind it later. In the alternate case
11666 // (when dealing with a retainable type), the result
11667 // initialization will create a produce. In both cases the
11668 // result will be +1, and we'll need to balance that out with
11670 if (Expr *rebuiltLastStmt
11671 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11672 LastExpr = rebuiltLastStmt;
11674 LastExpr = PerformCopyInitialization(
11675 InitializedEntity::InitializeResult(LPLoc,
11682 if (LastExpr.isInvalid())
11683 return ExprError();
11684 if (LastExpr.get() != nullptr) {
11685 if (!LastLabelStmt)
11686 Compound->setLastStmt(LastExpr.get());
11688 LastLabelStmt->setSubStmt(LastExpr.get());
11689 StmtExprMayBindToTemp = true;
11695 // FIXME: Check that expression type is complete/non-abstract; statement
11696 // expressions are not lvalues.
11697 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11698 if (StmtExprMayBindToTemp)
11699 return MaybeBindToTemporary(ResStmtExpr);
11700 return ResStmtExpr;
11703 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11704 TypeSourceInfo *TInfo,
11705 ArrayRef<OffsetOfComponent> Components,
11706 SourceLocation RParenLoc) {
11707 QualType ArgTy = TInfo->getType();
11708 bool Dependent = ArgTy->isDependentType();
11709 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11711 // We must have at least one component that refers to the type, and the first
11712 // one is known to be a field designator. Verify that the ArgTy represents
11713 // a struct/union/class.
11714 if (!Dependent && !ArgTy->isRecordType())
11715 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11716 << ArgTy << TypeRange);
11718 // Type must be complete per C99 7.17p3 because a declaring a variable
11719 // with an incomplete type would be ill-formed.
11721 && RequireCompleteType(BuiltinLoc, ArgTy,
11722 diag::err_offsetof_incomplete_type, TypeRange))
11723 return ExprError();
11725 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11726 // GCC extension, diagnose them.
11727 // FIXME: This diagnostic isn't actually visible because the location is in
11728 // a system header!
11729 if (Components.size() != 1)
11730 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11731 << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11733 bool DidWarnAboutNonPOD = false;
11734 QualType CurrentType = ArgTy;
11735 SmallVector<OffsetOfNode, 4> Comps;
11736 SmallVector<Expr*, 4> Exprs;
11737 for (const OffsetOfComponent &OC : Components) {
11738 if (OC.isBrackets) {
11739 // Offset of an array sub-field. TODO: Should we allow vector elements?
11740 if (!CurrentType->isDependentType()) {
11741 const ArrayType *AT = Context.getAsArrayType(CurrentType);
11743 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11745 CurrentType = AT->getElementType();
11747 CurrentType = Context.DependentTy;
11749 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11750 if (IdxRval.isInvalid())
11751 return ExprError();
11752 Expr *Idx = IdxRval.get();
11754 // The expression must be an integral expression.
11755 // FIXME: An integral constant expression?
11756 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11757 !Idx->getType()->isIntegerType())
11758 return ExprError(Diag(Idx->getLocStart(),
11759 diag::err_typecheck_subscript_not_integer)
11760 << Idx->getSourceRange());
11762 // Record this array index.
11763 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11764 Exprs.push_back(Idx);
11768 // Offset of a field.
11769 if (CurrentType->isDependentType()) {
11770 // We have the offset of a field, but we can't look into the dependent
11771 // type. Just record the identifier of the field.
11772 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11773 CurrentType = Context.DependentTy;
11777 // We need to have a complete type to look into.
11778 if (RequireCompleteType(OC.LocStart, CurrentType,
11779 diag::err_offsetof_incomplete_type))
11780 return ExprError();
11782 // Look for the designated field.
11783 const RecordType *RC = CurrentType->getAs<RecordType>();
11785 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11787 RecordDecl *RD = RC->getDecl();
11789 // C++ [lib.support.types]p5:
11790 // The macro offsetof accepts a restricted set of type arguments in this
11791 // International Standard. type shall be a POD structure or a POD union
11793 // C++11 [support.types]p4:
11794 // If type is not a standard-layout class (Clause 9), the results are
11796 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11797 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11799 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11800 : diag::ext_offsetof_non_pod_type;
11802 if (!IsSafe && !DidWarnAboutNonPOD &&
11803 DiagRuntimeBehavior(BuiltinLoc, nullptr,
11805 << SourceRange(Components[0].LocStart, OC.LocEnd)
11807 DidWarnAboutNonPOD = true;
11810 // Look for the field.
11811 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11812 LookupQualifiedName(R, RD);
11813 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11814 IndirectFieldDecl *IndirectMemberDecl = nullptr;
11816 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11817 MemberDecl = IndirectMemberDecl->getAnonField();
11821 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11822 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11826 // (If the specified member is a bit-field, the behavior is undefined.)
11828 // We diagnose this as an error.
11829 if (MemberDecl->isBitField()) {
11830 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11831 << MemberDecl->getDeclName()
11832 << SourceRange(BuiltinLoc, RParenLoc);
11833 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11834 return ExprError();
11837 RecordDecl *Parent = MemberDecl->getParent();
11838 if (IndirectMemberDecl)
11839 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11841 // If the member was found in a base class, introduce OffsetOfNodes for
11842 // the base class indirections.
11843 CXXBasePaths Paths;
11844 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11846 if (Paths.getDetectedVirtual()) {
11847 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11848 << MemberDecl->getDeclName()
11849 << SourceRange(BuiltinLoc, RParenLoc);
11850 return ExprError();
11853 CXXBasePath &Path = Paths.front();
11854 for (const CXXBasePathElement &B : Path)
11855 Comps.push_back(OffsetOfNode(B.Base));
11858 if (IndirectMemberDecl) {
11859 for (auto *FI : IndirectMemberDecl->chain()) {
11860 assert(isa<FieldDecl>(FI));
11861 Comps.push_back(OffsetOfNode(OC.LocStart,
11862 cast<FieldDecl>(FI), OC.LocEnd));
11865 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11867 CurrentType = MemberDecl->getType().getNonReferenceType();
11870 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11871 Comps, Exprs, RParenLoc);
11874 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11875 SourceLocation BuiltinLoc,
11876 SourceLocation TypeLoc,
11877 ParsedType ParsedArgTy,
11878 ArrayRef<OffsetOfComponent> Components,
11879 SourceLocation RParenLoc) {
11881 TypeSourceInfo *ArgTInfo;
11882 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11883 if (ArgTy.isNull())
11884 return ExprError();
11887 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11889 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11893 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11895 Expr *LHSExpr, Expr *RHSExpr,
11896 SourceLocation RPLoc) {
11897 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11899 ExprValueKind VK = VK_RValue;
11900 ExprObjectKind OK = OK_Ordinary;
11902 bool ValueDependent = false;
11903 bool CondIsTrue = false;
11904 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11905 resType = Context.DependentTy;
11906 ValueDependent = true;
11908 // The conditional expression is required to be a constant expression.
11909 llvm::APSInt condEval(32);
11911 = VerifyIntegerConstantExpression(CondExpr, &condEval,
11912 diag::err_typecheck_choose_expr_requires_constant, false);
11913 if (CondICE.isInvalid())
11914 return ExprError();
11915 CondExpr = CondICE.get();
11916 CondIsTrue = condEval.getZExtValue();
11918 // If the condition is > zero, then the AST type is the same as the LSHExpr.
11919 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11921 resType = ActiveExpr->getType();
11922 ValueDependent = ActiveExpr->isValueDependent();
11923 VK = ActiveExpr->getValueKind();
11924 OK = ActiveExpr->getObjectKind();
11927 return new (Context)
11928 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11929 CondIsTrue, resType->isDependentType(), ValueDependent);
11932 //===----------------------------------------------------------------------===//
11933 // Clang Extensions.
11934 //===----------------------------------------------------------------------===//
11936 /// ActOnBlockStart - This callback is invoked when a block literal is started.
11937 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11938 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11940 if (LangOpts.CPlusPlus) {
11941 Decl *ManglingContextDecl;
11942 if (MangleNumberingContext *MCtx =
11943 getCurrentMangleNumberContext(Block->getDeclContext(),
11944 ManglingContextDecl)) {
11945 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11946 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11950 PushBlockScope(CurScope, Block);
11951 CurContext->addDecl(Block);
11953 PushDeclContext(CurScope, Block);
11955 CurContext = Block;
11957 getCurBlock()->HasImplicitReturnType = true;
11959 // Enter a new evaluation context to insulate the block from any
11960 // cleanups from the enclosing full-expression.
11961 PushExpressionEvaluationContext(PotentiallyEvaluated);
11964 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11966 assert(ParamInfo.getIdentifier() == nullptr &&
11967 "block-id should have no identifier!");
11968 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11969 BlockScopeInfo *CurBlock = getCurBlock();
11971 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11972 QualType T = Sig->getType();
11974 // FIXME: We should allow unexpanded parameter packs here, but that would,
11975 // in turn, make the block expression contain unexpanded parameter packs.
11976 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11977 // Drop the parameters.
11978 FunctionProtoType::ExtProtoInfo EPI;
11979 EPI.HasTrailingReturn = false;
11980 EPI.TypeQuals |= DeclSpec::TQ_const;
11981 T = Context.getFunctionType(Context.DependentTy, None, EPI);
11982 Sig = Context.getTrivialTypeSourceInfo(T);
11985 // GetTypeForDeclarator always produces a function type for a block
11986 // literal signature. Furthermore, it is always a FunctionProtoType
11987 // unless the function was written with a typedef.
11988 assert(T->isFunctionType() &&
11989 "GetTypeForDeclarator made a non-function block signature");
11991 // Look for an explicit signature in that function type.
11992 FunctionProtoTypeLoc ExplicitSignature;
11994 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11995 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11997 // Check whether that explicit signature was synthesized by
11998 // GetTypeForDeclarator. If so, don't save that as part of the
11999 // written signature.
12000 if (ExplicitSignature.getLocalRangeBegin() ==
12001 ExplicitSignature.getLocalRangeEnd()) {
12002 // This would be much cheaper if we stored TypeLocs instead of
12003 // TypeSourceInfos.
12004 TypeLoc Result = ExplicitSignature.getReturnLoc();
12005 unsigned Size = Result.getFullDataSize();
12006 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12007 Sig->getTypeLoc().initializeFullCopy(Result, Size);
12009 ExplicitSignature = FunctionProtoTypeLoc();
12013 CurBlock->TheDecl->setSignatureAsWritten(Sig);
12014 CurBlock->FunctionType = T;
12016 const FunctionType *Fn = T->getAs<FunctionType>();
12017 QualType RetTy = Fn->getReturnType();
12019 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12021 CurBlock->TheDecl->setIsVariadic(isVariadic);
12023 // Context.DependentTy is used as a placeholder for a missing block
12024 // return type. TODO: what should we do with declarators like:
12026 // If the answer is "apply template argument deduction"....
12027 if (RetTy != Context.DependentTy) {
12028 CurBlock->ReturnType = RetTy;
12029 CurBlock->TheDecl->setBlockMissingReturnType(false);
12030 CurBlock->HasImplicitReturnType = false;
12033 // Push block parameters from the declarator if we had them.
12034 SmallVector<ParmVarDecl*, 8> Params;
12035 if (ExplicitSignature) {
12036 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12037 ParmVarDecl *Param = ExplicitSignature.getParam(I);
12038 if (Param->getIdentifier() == nullptr &&
12039 !Param->isImplicit() &&
12040 !Param->isInvalidDecl() &&
12041 !getLangOpts().CPlusPlus)
12042 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12043 Params.push_back(Param);
12046 // Fake up parameter variables if we have a typedef, like
12047 // ^ fntype { ... }
12048 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12049 for (const auto &I : Fn->param_types()) {
12050 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12051 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12052 Params.push_back(Param);
12056 // Set the parameters on the block decl.
12057 if (!Params.empty()) {
12058 CurBlock->TheDecl->setParams(Params);
12059 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12060 /*CheckParameterNames=*/false);
12063 // Finally we can process decl attributes.
12064 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12066 // Put the parameter variables in scope.
12067 for (auto AI : CurBlock->TheDecl->parameters()) {
12068 AI->setOwningFunction(CurBlock->TheDecl);
12070 // If this has an identifier, add it to the scope stack.
12071 if (AI->getIdentifier()) {
12072 CheckShadow(CurBlock->TheScope, AI);
12074 PushOnScopeChains(AI, CurBlock->TheScope);
12079 /// ActOnBlockError - If there is an error parsing a block, this callback
12080 /// is invoked to pop the information about the block from the action impl.
12081 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12082 // Leave the expression-evaluation context.
12083 DiscardCleanupsInEvaluationContext();
12084 PopExpressionEvaluationContext();
12086 // Pop off CurBlock, handle nested blocks.
12088 PopFunctionScopeInfo();
12091 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12092 /// literal was successfully completed. ^(int x){...}
12093 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12094 Stmt *Body, Scope *CurScope) {
12095 // If blocks are disabled, emit an error.
12096 if (!LangOpts.Blocks)
12097 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12099 // Leave the expression-evaluation context.
12100 if (hasAnyUnrecoverableErrorsInThisFunction())
12101 DiscardCleanupsInEvaluationContext();
12102 assert(!Cleanup.exprNeedsCleanups() &&
12103 "cleanups within block not correctly bound!");
12104 PopExpressionEvaluationContext();
12106 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12108 if (BSI->HasImplicitReturnType)
12109 deduceClosureReturnType(*BSI);
12113 QualType RetTy = Context.VoidTy;
12114 if (!BSI->ReturnType.isNull())
12115 RetTy = BSI->ReturnType;
12117 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12120 // Set the captured variables on the block.
12121 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12122 SmallVector<BlockDecl::Capture, 4> Captures;
12123 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12124 if (Cap.isThisCapture())
12126 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12127 Cap.isNested(), Cap.getInitExpr());
12128 Captures.push_back(NewCap);
12130 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12132 // If the user wrote a function type in some form, try to use that.
12133 if (!BSI->FunctionType.isNull()) {
12134 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12136 FunctionType::ExtInfo Ext = FTy->getExtInfo();
12137 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12139 // Turn protoless block types into nullary block types.
12140 if (isa<FunctionNoProtoType>(FTy)) {
12141 FunctionProtoType::ExtProtoInfo EPI;
12143 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12145 // Otherwise, if we don't need to change anything about the function type,
12146 // preserve its sugar structure.
12147 } else if (FTy->getReturnType() == RetTy &&
12148 (!NoReturn || FTy->getNoReturnAttr())) {
12149 BlockTy = BSI->FunctionType;
12151 // Otherwise, make the minimal modifications to the function type.
12153 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12154 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12155 EPI.TypeQuals = 0; // FIXME: silently?
12157 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12160 // If we don't have a function type, just build one from nothing.
12162 FunctionProtoType::ExtProtoInfo EPI;
12163 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12164 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12167 DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12168 BlockTy = Context.getBlockPointerType(BlockTy);
12170 // If needed, diagnose invalid gotos and switches in the block.
12171 if (getCurFunction()->NeedsScopeChecking() &&
12172 !PP.isCodeCompletionEnabled())
12173 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12175 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12177 // Try to apply the named return value optimization. We have to check again
12178 // if we can do this, though, because blocks keep return statements around
12179 // to deduce an implicit return type.
12180 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12181 !BSI->TheDecl->isDependentContext())
12182 computeNRVO(Body, BSI);
12184 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12185 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12186 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12188 // If the block isn't obviously global, i.e. it captures anything at
12189 // all, then we need to do a few things in the surrounding context:
12190 if (Result->getBlockDecl()->hasCaptures()) {
12191 // First, this expression has a new cleanup object.
12192 ExprCleanupObjects.push_back(Result->getBlockDecl());
12193 Cleanup.setExprNeedsCleanups(true);
12195 // It also gets a branch-protected scope if any of the captured
12196 // variables needs destruction.
12197 for (const auto &CI : Result->getBlockDecl()->captures()) {
12198 const VarDecl *var = CI.getVariable();
12199 if (var->getType().isDestructedType() != QualType::DK_none) {
12200 getCurFunction()->setHasBranchProtectedScope();
12209 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12210 SourceLocation RPLoc) {
12211 TypeSourceInfo *TInfo;
12212 GetTypeFromParser(Ty, &TInfo);
12213 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12216 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12217 Expr *E, TypeSourceInfo *TInfo,
12218 SourceLocation RPLoc) {
12219 Expr *OrigExpr = E;
12222 // CUDA device code does not support varargs.
12223 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12224 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12225 CUDAFunctionTarget T = IdentifyCUDATarget(F);
12226 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12227 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12231 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12232 // as Microsoft ABI on an actual Microsoft platform, where
12233 // __builtin_ms_va_list and __builtin_va_list are the same.)
12234 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12235 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12236 QualType MSVaListType = Context.getBuiltinMSVaListType();
12237 if (Context.hasSameType(MSVaListType, E->getType())) {
12238 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12239 return ExprError();
12244 // Get the va_list type
12245 QualType VaListType = Context.getBuiltinVaListType();
12247 if (VaListType->isArrayType()) {
12248 // Deal with implicit array decay; for example, on x86-64,
12249 // va_list is an array, but it's supposed to decay to
12250 // a pointer for va_arg.
12251 VaListType = Context.getArrayDecayedType(VaListType);
12252 // Make sure the input expression also decays appropriately.
12253 ExprResult Result = UsualUnaryConversions(E);
12254 if (Result.isInvalid())
12255 return ExprError();
12257 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12258 // If va_list is a record type and we are compiling in C++ mode,
12259 // check the argument using reference binding.
12260 InitializedEntity Entity = InitializedEntity::InitializeParameter(
12261 Context, Context.getLValueReferenceType(VaListType), false);
12262 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12263 if (Init.isInvalid())
12264 return ExprError();
12265 E = Init.getAs<Expr>();
12267 // Otherwise, the va_list argument must be an l-value because
12268 // it is modified by va_arg.
12269 if (!E->isTypeDependent() &&
12270 CheckForModifiableLvalue(E, BuiltinLoc, *this))
12271 return ExprError();
12275 if (!IsMS && !E->isTypeDependent() &&
12276 !Context.hasSameType(VaListType, E->getType()))
12277 return ExprError(Diag(E->getLocStart(),
12278 diag::err_first_argument_to_va_arg_not_of_type_va_list)
12279 << OrigExpr->getType() << E->getSourceRange());
12281 if (!TInfo->getType()->isDependentType()) {
12282 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12283 diag::err_second_parameter_to_va_arg_incomplete,
12284 TInfo->getTypeLoc()))
12285 return ExprError();
12287 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12289 diag::err_second_parameter_to_va_arg_abstract,
12290 TInfo->getTypeLoc()))
12291 return ExprError();
12293 if (!TInfo->getType().isPODType(Context)) {
12294 Diag(TInfo->getTypeLoc().getBeginLoc(),
12295 TInfo->getType()->isObjCLifetimeType()
12296 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12297 : diag::warn_second_parameter_to_va_arg_not_pod)
12298 << TInfo->getType()
12299 << TInfo->getTypeLoc().getSourceRange();
12302 // Check for va_arg where arguments of the given type will be promoted
12303 // (i.e. this va_arg is guaranteed to have undefined behavior).
12304 QualType PromoteType;
12305 if (TInfo->getType()->isPromotableIntegerType()) {
12306 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12307 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12308 PromoteType = QualType();
12310 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12311 PromoteType = Context.DoubleTy;
12312 if (!PromoteType.isNull())
12313 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12314 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12315 << TInfo->getType()
12317 << TInfo->getTypeLoc().getSourceRange());
12320 QualType T = TInfo->getType().getNonLValueExprType(Context);
12321 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12324 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12325 // The type of __null will be int or long, depending on the size of
12326 // pointers on the target.
12328 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12329 if (pw == Context.getTargetInfo().getIntWidth())
12330 Ty = Context.IntTy;
12331 else if (pw == Context.getTargetInfo().getLongWidth())
12332 Ty = Context.LongTy;
12333 else if (pw == Context.getTargetInfo().getLongLongWidth())
12334 Ty = Context.LongLongTy;
12336 llvm_unreachable("I don't know size of pointer!");
12339 return new (Context) GNUNullExpr(Ty, TokenLoc);
12342 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12344 if (!getLangOpts().ObjC1)
12347 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12351 if (!PT->isObjCIdType()) {
12352 // Check if the destination is the 'NSString' interface.
12353 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12354 if (!ID || !ID->getIdentifier()->isStr("NSString"))
12358 // Ignore any parens, implicit casts (should only be
12359 // array-to-pointer decays), and not-so-opaque values. The last is
12360 // important for making this trigger for property assignments.
12361 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12362 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12363 if (OV->getSourceExpr())
12364 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12366 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12367 if (!SL || !SL->isAscii())
12370 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12371 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12372 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12377 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12378 const Expr *SrcExpr) {
12379 if (!DstType->isFunctionPointerType() ||
12380 !SrcExpr->getType()->isFunctionType())
12383 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12387 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12391 return !S.checkAddressOfFunctionIsAvailable(FD,
12393 SrcExpr->getLocStart());
12396 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12397 SourceLocation Loc,
12398 QualType DstType, QualType SrcType,
12399 Expr *SrcExpr, AssignmentAction Action,
12400 bool *Complained) {
12402 *Complained = false;
12404 // Decode the result (notice that AST's are still created for extensions).
12405 bool CheckInferredResultType = false;
12406 bool isInvalid = false;
12407 unsigned DiagKind = 0;
12409 ConversionFixItGenerator ConvHints;
12410 bool MayHaveConvFixit = false;
12411 bool MayHaveFunctionDiff = false;
12412 const ObjCInterfaceDecl *IFace = nullptr;
12413 const ObjCProtocolDecl *PDecl = nullptr;
12417 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12421 DiagKind = diag::ext_typecheck_convert_pointer_int;
12422 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12423 MayHaveConvFixit = true;
12426 DiagKind = diag::ext_typecheck_convert_int_pointer;
12427 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12428 MayHaveConvFixit = true;
12430 case IncompatiblePointer:
12432 (Action == AA_Passing_CFAudited ?
12433 diag::err_arc_typecheck_convert_incompatible_pointer :
12434 diag::ext_typecheck_convert_incompatible_pointer);
12435 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12436 SrcType->isObjCObjectPointerType();
12437 if (Hint.isNull() && !CheckInferredResultType) {
12438 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12440 else if (CheckInferredResultType) {
12441 SrcType = SrcType.getUnqualifiedType();
12442 DstType = DstType.getUnqualifiedType();
12444 MayHaveConvFixit = true;
12446 case IncompatiblePointerSign:
12447 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12449 case FunctionVoidPointer:
12450 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12452 case IncompatiblePointerDiscardsQualifiers: {
12453 // Perform array-to-pointer decay if necessary.
12454 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12456 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12457 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12458 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12459 DiagKind = diag::err_typecheck_incompatible_address_space;
12463 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12464 DiagKind = diag::err_typecheck_incompatible_ownership;
12468 llvm_unreachable("unknown error case for discarding qualifiers!");
12471 case CompatiblePointerDiscardsQualifiers:
12472 // If the qualifiers lost were because we were applying the
12473 // (deprecated) C++ conversion from a string literal to a char*
12474 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
12475 // Ideally, this check would be performed in
12476 // checkPointerTypesForAssignment. However, that would require a
12477 // bit of refactoring (so that the second argument is an
12478 // expression, rather than a type), which should be done as part
12479 // of a larger effort to fix checkPointerTypesForAssignment for
12481 if (getLangOpts().CPlusPlus &&
12482 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12484 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12486 case IncompatibleNestedPointerQualifiers:
12487 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12489 case IntToBlockPointer:
12490 DiagKind = diag::err_int_to_block_pointer;
12492 case IncompatibleBlockPointer:
12493 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12495 case IncompatibleObjCQualifiedId: {
12496 if (SrcType->isObjCQualifiedIdType()) {
12497 const ObjCObjectPointerType *srcOPT =
12498 SrcType->getAs<ObjCObjectPointerType>();
12499 for (auto *srcProto : srcOPT->quals()) {
12503 if (const ObjCInterfaceType *IFaceT =
12504 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12505 IFace = IFaceT->getDecl();
12507 else if (DstType->isObjCQualifiedIdType()) {
12508 const ObjCObjectPointerType *dstOPT =
12509 DstType->getAs<ObjCObjectPointerType>();
12510 for (auto *dstProto : dstOPT->quals()) {
12514 if (const ObjCInterfaceType *IFaceT =
12515 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12516 IFace = IFaceT->getDecl();
12518 DiagKind = diag::warn_incompatible_qualified_id;
12521 case IncompatibleVectors:
12522 DiagKind = diag::warn_incompatible_vectors;
12524 case IncompatibleObjCWeakRef:
12525 DiagKind = diag::err_arc_weak_unavailable_assign;
12528 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12530 *Complained = true;
12534 DiagKind = diag::err_typecheck_convert_incompatible;
12535 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12536 MayHaveConvFixit = true;
12538 MayHaveFunctionDiff = true;
12542 QualType FirstType, SecondType;
12545 case AA_Initializing:
12546 // The destination type comes first.
12547 FirstType = DstType;
12548 SecondType = SrcType;
12553 case AA_Passing_CFAudited:
12554 case AA_Converting:
12557 // The source type comes first.
12558 FirstType = SrcType;
12559 SecondType = DstType;
12563 PartialDiagnostic FDiag = PDiag(DiagKind);
12564 if (Action == AA_Passing_CFAudited)
12565 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12567 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12569 // If we can fix the conversion, suggest the FixIts.
12570 assert(ConvHints.isNull() || Hint.isNull());
12571 if (!ConvHints.isNull()) {
12572 for (FixItHint &H : ConvHints.Hints)
12577 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12579 if (MayHaveFunctionDiff)
12580 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12583 if (DiagKind == diag::warn_incompatible_qualified_id &&
12584 PDecl && IFace && !IFace->hasDefinition())
12585 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12586 << IFace->getName() << PDecl->getName();
12588 if (SecondType == Context.OverloadTy)
12589 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12590 FirstType, /*TakingAddress=*/true);
12592 if (CheckInferredResultType)
12593 EmitRelatedResultTypeNote(SrcExpr);
12595 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12596 EmitRelatedResultTypeNoteForReturn(DstType);
12599 *Complained = true;
12603 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12604 llvm::APSInt *Result) {
12605 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12607 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12608 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12612 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12615 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12616 llvm::APSInt *Result,
12619 class IDDiagnoser : public VerifyICEDiagnoser {
12623 IDDiagnoser(unsigned DiagID)
12624 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12626 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12627 S.Diag(Loc, DiagID) << SR;
12629 } Diagnoser(DiagID);
12631 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12634 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12636 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12640 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12641 VerifyICEDiagnoser &Diagnoser,
12643 SourceLocation DiagLoc = E->getLocStart();
12645 if (getLangOpts().CPlusPlus11) {
12646 // C++11 [expr.const]p5:
12647 // If an expression of literal class type is used in a context where an
12648 // integral constant expression is required, then that class type shall
12649 // have a single non-explicit conversion function to an integral or
12650 // unscoped enumeration type
12651 ExprResult Converted;
12652 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12654 CXX11ConvertDiagnoser(bool Silent)
12655 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12658 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12659 QualType T) override {
12660 return S.Diag(Loc, diag::err_ice_not_integral) << T;
12663 SemaDiagnosticBuilder diagnoseIncomplete(
12664 Sema &S, SourceLocation Loc, QualType T) override {
12665 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12668 SemaDiagnosticBuilder diagnoseExplicitConv(
12669 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12670 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12673 SemaDiagnosticBuilder noteExplicitConv(
12674 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12675 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12676 << ConvTy->isEnumeralType() << ConvTy;
12679 SemaDiagnosticBuilder diagnoseAmbiguous(
12680 Sema &S, SourceLocation Loc, QualType T) override {
12681 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12684 SemaDiagnosticBuilder noteAmbiguous(
12685 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12686 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12687 << ConvTy->isEnumeralType() << ConvTy;
12690 SemaDiagnosticBuilder diagnoseConversion(
12691 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12692 llvm_unreachable("conversion functions are permitted");
12694 } ConvertDiagnoser(Diagnoser.Suppress);
12696 Converted = PerformContextualImplicitConversion(DiagLoc, E,
12698 if (Converted.isInvalid())
12700 E = Converted.get();
12701 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12702 return ExprError();
12703 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12704 // An ICE must be of integral or unscoped enumeration type.
12705 if (!Diagnoser.Suppress)
12706 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12707 return ExprError();
12710 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12711 // in the non-ICE case.
12712 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12714 *Result = E->EvaluateKnownConstInt(Context);
12718 Expr::EvalResult EvalResult;
12719 SmallVector<PartialDiagnosticAt, 8> Notes;
12720 EvalResult.Diag = &Notes;
12722 // Try to evaluate the expression, and produce diagnostics explaining why it's
12723 // not a constant expression as a side-effect.
12724 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12725 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12727 // In C++11, we can rely on diagnostics being produced for any expression
12728 // which is not a constant expression. If no diagnostics were produced, then
12729 // this is a constant expression.
12730 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12732 *Result = EvalResult.Val.getInt();
12736 // If our only note is the usual "invalid subexpression" note, just point
12737 // the caret at its location rather than producing an essentially
12739 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12740 diag::note_invalid_subexpr_in_const_expr) {
12741 DiagLoc = Notes[0].first;
12745 if (!Folded || !AllowFold) {
12746 if (!Diagnoser.Suppress) {
12747 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12748 for (const PartialDiagnosticAt &Note : Notes)
12749 Diag(Note.first, Note.second);
12752 return ExprError();
12755 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12756 for (const PartialDiagnosticAt &Note : Notes)
12757 Diag(Note.first, Note.second);
12760 *Result = EvalResult.Val.getInt();
12765 // Handle the case where we conclude a expression which we speculatively
12766 // considered to be unevaluated is actually evaluated.
12767 class TransformToPE : public TreeTransform<TransformToPE> {
12768 typedef TreeTransform<TransformToPE> BaseTransform;
12771 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12773 // Make sure we redo semantic analysis
12774 bool AlwaysRebuild() { return true; }
12776 // Make sure we handle LabelStmts correctly.
12777 // FIXME: This does the right thing, but maybe we need a more general
12778 // fix to TreeTransform?
12779 StmtResult TransformLabelStmt(LabelStmt *S) {
12780 S->getDecl()->setStmt(nullptr);
12781 return BaseTransform::TransformLabelStmt(S);
12784 // We need to special-case DeclRefExprs referring to FieldDecls which
12785 // are not part of a member pointer formation; normal TreeTransforming
12786 // doesn't catch this case because of the way we represent them in the AST.
12787 // FIXME: This is a bit ugly; is it really the best way to handle this
12790 // Error on DeclRefExprs referring to FieldDecls.
12791 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12792 if (isa<FieldDecl>(E->getDecl()) &&
12793 !SemaRef.isUnevaluatedContext())
12794 return SemaRef.Diag(E->getLocation(),
12795 diag::err_invalid_non_static_member_use)
12796 << E->getDecl() << E->getSourceRange();
12798 return BaseTransform::TransformDeclRefExpr(E);
12801 // Exception: filter out member pointer formation
12802 ExprResult TransformUnaryOperator(UnaryOperator *E) {
12803 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12806 return BaseTransform::TransformUnaryOperator(E);
12809 ExprResult TransformLambdaExpr(LambdaExpr *E) {
12810 // Lambdas never need to be transformed.
12816 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12817 assert(isUnevaluatedContext() &&
12818 "Should only transform unevaluated expressions");
12819 ExprEvalContexts.back().Context =
12820 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12821 if (isUnevaluatedContext())
12823 return TransformToPE(*this).TransformExpr(E);
12827 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12828 Decl *LambdaContextDecl,
12830 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
12831 LambdaContextDecl, IsDecltype);
12833 if (!MaybeODRUseExprs.empty())
12834 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12838 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12839 ReuseLambdaContextDecl_t,
12841 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12842 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12845 void Sema::PopExpressionEvaluationContext() {
12846 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12847 unsigned NumTypos = Rec.NumTypos;
12849 if (!Rec.Lambdas.empty()) {
12850 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12852 if (Rec.isUnevaluated()) {
12853 // C++11 [expr.prim.lambda]p2:
12854 // A lambda-expression shall not appear in an unevaluated operand
12856 D = diag::err_lambda_unevaluated_operand;
12858 // C++1y [expr.const]p2:
12859 // A conditional-expression e is a core constant expression unless the
12860 // evaluation of e, following the rules of the abstract machine, would
12861 // evaluate [...] a lambda-expression.
12862 D = diag::err_lambda_in_constant_expression;
12864 for (const auto *L : Rec.Lambdas)
12865 Diag(L->getLocStart(), D);
12867 // Mark the capture expressions odr-used. This was deferred
12868 // during lambda expression creation.
12869 for (auto *Lambda : Rec.Lambdas) {
12870 for (auto *C : Lambda->capture_inits())
12871 MarkDeclarationsReferencedInExpr(C);
12876 // When are coming out of an unevaluated context, clear out any
12877 // temporaries that we may have created as part of the evaluation of
12878 // the expression in that context: they aren't relevant because they
12879 // will never be constructed.
12880 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12881 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12882 ExprCleanupObjects.end());
12883 Cleanup = Rec.ParentCleanup;
12884 CleanupVarDeclMarking();
12885 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12886 // Otherwise, merge the contexts together.
12888 Cleanup.mergeFrom(Rec.ParentCleanup);
12889 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12890 Rec.SavedMaybeODRUseExprs.end());
12893 // Pop the current expression evaluation context off the stack.
12894 ExprEvalContexts.pop_back();
12896 if (!ExprEvalContexts.empty())
12897 ExprEvalContexts.back().NumTypos += NumTypos;
12899 assert(NumTypos == 0 && "There are outstanding typos after popping the "
12900 "last ExpressionEvaluationContextRecord");
12903 void Sema::DiscardCleanupsInEvaluationContext() {
12904 ExprCleanupObjects.erase(
12905 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12906 ExprCleanupObjects.end());
12908 MaybeODRUseExprs.clear();
12911 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12912 if (!E->getType()->isVariablyModifiedType())
12914 return TransformToPotentiallyEvaluated(E);
12917 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12918 // Do not mark anything as "used" within a dependent context; wait for
12919 // an instantiation.
12920 if (SemaRef.CurContext->isDependentContext())
12923 switch (SemaRef.ExprEvalContexts.back().Context) {
12924 case Sema::Unevaluated:
12925 case Sema::UnevaluatedAbstract:
12926 // We are in an expression that is not potentially evaluated; do nothing.
12927 // (Depending on how you read the standard, we actually do need to do
12928 // something here for null pointer constants, but the standard's
12929 // definition of a null pointer constant is completely crazy.)
12932 case Sema::DiscardedStatement:
12933 // These are technically a potentially evaluated but they have the effect
12934 // of suppressing use marking.
12937 case Sema::ConstantEvaluated:
12938 case Sema::PotentiallyEvaluated:
12939 // We are in a potentially evaluated expression (or a constant-expression
12940 // in C++03); we need to do implicit template instantiation, implicitly
12941 // define class members, and mark most declarations as used.
12944 case Sema::PotentiallyEvaluatedIfUsed:
12945 // Referenced declarations will only be used if the construct in the
12946 // containing expression is used.
12949 llvm_unreachable("Invalid context");
12952 /// \brief Mark a function referenced, and check whether it is odr-used
12953 /// (C++ [basic.def.odr]p2, C99 6.9p3)
12954 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12955 bool MightBeOdrUse) {
12956 assert(Func && "No function?");
12958 Func->setReferenced();
12960 // C++11 [basic.def.odr]p3:
12961 // A function whose name appears as a potentially-evaluated expression is
12962 // odr-used if it is the unique lookup result or the selected member of a
12963 // set of overloaded functions [...].
12965 // We (incorrectly) mark overload resolution as an unevaluated context, so we
12966 // can just check that here.
12967 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
12969 // Determine whether we require a function definition to exist, per
12970 // C++11 [temp.inst]p3:
12971 // Unless a function template specialization has been explicitly
12972 // instantiated or explicitly specialized, the function template
12973 // specialization is implicitly instantiated when the specialization is
12974 // referenced in a context that requires a function definition to exist.
12976 // We consider constexpr function templates to be referenced in a context
12977 // that requires a definition to exist whenever they are referenced.
12979 // FIXME: This instantiates constexpr functions too frequently. If this is
12980 // really an unevaluated context (and we're not just in the definition of a
12981 // function template or overload resolution or other cases which we
12982 // incorrectly consider to be unevaluated contexts), and we're not in a
12983 // subexpression which we actually need to evaluate (for instance, a
12984 // template argument, array bound or an expression in a braced-init-list),
12985 // we are not permitted to instantiate this constexpr function definition.
12987 // FIXME: This also implicitly defines special members too frequently. They
12988 // are only supposed to be implicitly defined if they are odr-used, but they
12989 // are not odr-used from constant expressions in unevaluated contexts.
12990 // However, they cannot be referenced if they are deleted, and they are
12991 // deleted whenever the implicit definition of the special member would
12992 // fail (with very few exceptions).
12993 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12994 bool NeedDefinition =
12995 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
12996 (MD && !MD->isUserProvided())));
12998 // C++14 [temp.expl.spec]p6:
12999 // If a template [...] is explicitly specialized then that specialization
13000 // shall be declared before the first use of that specialization that would
13001 // cause an implicit instantiation to take place, in every translation unit
13002 // in which such a use occurs
13003 if (NeedDefinition &&
13004 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13005 Func->getMemberSpecializationInfo()))
13006 checkSpecializationVisibility(Loc, Func);
13008 // If we don't need to mark the function as used, and we don't need to
13009 // try to provide a definition, there's nothing more to do.
13010 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13011 (!NeedDefinition || Func->getBody()))
13014 // Note that this declaration has been used.
13015 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13016 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13017 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13018 if (Constructor->isDefaultConstructor()) {
13019 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13021 DefineImplicitDefaultConstructor(Loc, Constructor);
13022 } else if (Constructor->isCopyConstructor()) {
13023 DefineImplicitCopyConstructor(Loc, Constructor);
13024 } else if (Constructor->isMoveConstructor()) {
13025 DefineImplicitMoveConstructor(Loc, Constructor);
13027 } else if (Constructor->getInheritedConstructor()) {
13028 DefineInheritingConstructor(Loc, Constructor);
13030 } else if (CXXDestructorDecl *Destructor =
13031 dyn_cast<CXXDestructorDecl>(Func)) {
13032 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13033 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13034 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13036 DefineImplicitDestructor(Loc, Destructor);
13038 if (Destructor->isVirtual() && getLangOpts().AppleKext)
13039 MarkVTableUsed(Loc, Destructor->getParent());
13040 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13041 if (MethodDecl->isOverloadedOperator() &&
13042 MethodDecl->getOverloadedOperator() == OO_Equal) {
13043 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13044 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13045 if (MethodDecl->isCopyAssignmentOperator())
13046 DefineImplicitCopyAssignment(Loc, MethodDecl);
13047 else if (MethodDecl->isMoveAssignmentOperator())
13048 DefineImplicitMoveAssignment(Loc, MethodDecl);
13050 } else if (isa<CXXConversionDecl>(MethodDecl) &&
13051 MethodDecl->getParent()->isLambda()) {
13052 CXXConversionDecl *Conversion =
13053 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13054 if (Conversion->isLambdaToBlockPointerConversion())
13055 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13057 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13058 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13059 MarkVTableUsed(Loc, MethodDecl->getParent());
13062 // Recursive functions should be marked when used from another function.
13063 // FIXME: Is this really right?
13064 if (CurContext == Func) return;
13066 // Resolve the exception specification for any function which is
13067 // used: CodeGen will need it.
13068 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13069 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13070 ResolveExceptionSpec(Loc, FPT);
13072 // Implicit instantiation of function templates and member functions of
13073 // class templates.
13074 if (Func->isImplicitlyInstantiable()) {
13075 bool AlreadyInstantiated = false;
13076 SourceLocation PointOfInstantiation = Loc;
13077 if (FunctionTemplateSpecializationInfo *SpecInfo
13078 = Func->getTemplateSpecializationInfo()) {
13079 if (SpecInfo->getPointOfInstantiation().isInvalid())
13080 SpecInfo->setPointOfInstantiation(Loc);
13081 else if (SpecInfo->getTemplateSpecializationKind()
13082 == TSK_ImplicitInstantiation) {
13083 AlreadyInstantiated = true;
13084 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13086 } else if (MemberSpecializationInfo *MSInfo
13087 = Func->getMemberSpecializationInfo()) {
13088 if (MSInfo->getPointOfInstantiation().isInvalid())
13089 MSInfo->setPointOfInstantiation(Loc);
13090 else if (MSInfo->getTemplateSpecializationKind()
13091 == TSK_ImplicitInstantiation) {
13092 AlreadyInstantiated = true;
13093 PointOfInstantiation = MSInfo->getPointOfInstantiation();
13097 if (!AlreadyInstantiated || Func->isConstexpr()) {
13098 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13099 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13100 ActiveTemplateInstantiations.size())
13101 PendingLocalImplicitInstantiations.push_back(
13102 std::make_pair(Func, PointOfInstantiation));
13103 else if (Func->isConstexpr())
13104 // Do not defer instantiations of constexpr functions, to avoid the
13105 // expression evaluator needing to call back into Sema if it sees a
13106 // call to such a function.
13107 InstantiateFunctionDefinition(PointOfInstantiation, Func);
13109 PendingInstantiations.push_back(std::make_pair(Func,
13110 PointOfInstantiation));
13111 // Notify the consumer that a function was implicitly instantiated.
13112 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13116 // Walk redefinitions, as some of them may be instantiable.
13117 for (auto i : Func->redecls()) {
13118 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13119 MarkFunctionReferenced(Loc, i, OdrUse);
13123 if (!OdrUse) return;
13125 // Keep track of used but undefined functions.
13126 if (!Func->isDefined()) {
13127 if (mightHaveNonExternalLinkage(Func))
13128 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13129 else if (Func->getMostRecentDecl()->isInlined() &&
13130 !LangOpts.GNUInline &&
13131 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13132 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13135 Func->markUsed(Context);
13139 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13140 VarDecl *var, DeclContext *DC) {
13141 DeclContext *VarDC = var->getDeclContext();
13143 // If the parameter still belongs to the translation unit, then
13144 // we're actually just using one parameter in the declaration of
13146 if (isa<ParmVarDecl>(var) &&
13147 isa<TranslationUnitDecl>(VarDC))
13150 // For C code, don't diagnose about capture if we're not actually in code
13151 // right now; it's impossible to write a non-constant expression outside of
13152 // function context, so we'll get other (more useful) diagnostics later.
13154 // For C++, things get a bit more nasty... it would be nice to suppress this
13155 // diagnostic for certain cases like using a local variable in an array bound
13156 // for a member of a local class, but the correct predicate is not obvious.
13157 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13160 if (isa<CXXMethodDecl>(VarDC) &&
13161 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13162 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
13163 << var->getIdentifier();
13164 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
13165 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
13166 << var->getIdentifier() << fn->getDeclName();
13167 } else if (isa<BlockDecl>(VarDC)) {
13168 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
13169 << var->getIdentifier();
13171 // FIXME: Is there any other context where a local variable can be
13173 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
13174 << var->getIdentifier();
13177 S.Diag(var->getLocation(), diag::note_entity_declared_at)
13178 << var->getIdentifier();
13180 // FIXME: Add additional diagnostic info about class etc. which prevents
13185 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13186 bool &SubCapturesAreNested,
13187 QualType &CaptureType,
13188 QualType &DeclRefType) {
13189 // Check whether we've already captured it.
13190 if (CSI->CaptureMap.count(Var)) {
13191 // If we found a capture, any subcaptures are nested.
13192 SubCapturesAreNested = true;
13194 // Retrieve the capture type for this variable.
13195 CaptureType = CSI->getCapture(Var).getCaptureType();
13197 // Compute the type of an expression that refers to this variable.
13198 DeclRefType = CaptureType.getNonReferenceType();
13200 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13201 // are mutable in the sense that user can change their value - they are
13202 // private instances of the captured declarations.
13203 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13204 if (Cap.isCopyCapture() &&
13205 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13206 !(isa<CapturedRegionScopeInfo>(CSI) &&
13207 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13208 DeclRefType.addConst();
13214 // Only block literals, captured statements, and lambda expressions can
13215 // capture; other scopes don't work.
13216 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13217 SourceLocation Loc,
13218 const bool Diagnose, Sema &S) {
13219 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13220 return getLambdaAwareParentOfDeclContext(DC);
13221 else if (Var->hasLocalStorage()) {
13223 diagnoseUncapturableValueReference(S, Loc, Var, DC);
13228 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13229 // certain types of variables (unnamed, variably modified types etc.)
13230 // so check for eligibility.
13231 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13232 SourceLocation Loc,
13233 const bool Diagnose, Sema &S) {
13235 bool IsBlock = isa<BlockScopeInfo>(CSI);
13236 bool IsLambda = isa<LambdaScopeInfo>(CSI);
13238 // Lambdas are not allowed to capture unnamed variables
13239 // (e.g. anonymous unions).
13240 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13241 // assuming that's the intent.
13242 if (IsLambda && !Var->getDeclName()) {
13244 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13245 S.Diag(Var->getLocation(), diag::note_declared_at);
13250 // Prohibit variably-modified types in blocks; they're difficult to deal with.
13251 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13253 S.Diag(Loc, diag::err_ref_vm_type);
13254 S.Diag(Var->getLocation(), diag::note_previous_decl)
13255 << Var->getDeclName();
13259 // Prohibit structs with flexible array members too.
13260 // We cannot capture what is in the tail end of the struct.
13261 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13262 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13265 S.Diag(Loc, diag::err_ref_flexarray_type);
13267 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13268 << Var->getDeclName();
13269 S.Diag(Var->getLocation(), diag::note_previous_decl)
13270 << Var->getDeclName();
13275 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13276 // Lambdas and captured statements are not allowed to capture __block
13277 // variables; they don't support the expected semantics.
13278 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13280 S.Diag(Loc, diag::err_capture_block_variable)
13281 << Var->getDeclName() << !IsLambda;
13282 S.Diag(Var->getLocation(), diag::note_previous_decl)
13283 << Var->getDeclName();
13291 // Returns true if the capture by block was successful.
13292 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13293 SourceLocation Loc,
13294 const bool BuildAndDiagnose,
13295 QualType &CaptureType,
13296 QualType &DeclRefType,
13299 Expr *CopyExpr = nullptr;
13300 bool ByRef = false;
13302 // Blocks are not allowed to capture arrays.
13303 if (CaptureType->isArrayType()) {
13304 if (BuildAndDiagnose) {
13305 S.Diag(Loc, diag::err_ref_array_type);
13306 S.Diag(Var->getLocation(), diag::note_previous_decl)
13307 << Var->getDeclName();
13312 // Forbid the block-capture of autoreleasing variables.
13313 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13314 if (BuildAndDiagnose) {
13315 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13317 S.Diag(Var->getLocation(), diag::note_previous_decl)
13318 << Var->getDeclName();
13322 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13323 if (HasBlocksAttr || CaptureType->isReferenceType() ||
13324 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13325 // Block capture by reference does not change the capture or
13326 // declaration reference types.
13329 // Block capture by copy introduces 'const'.
13330 CaptureType = CaptureType.getNonReferenceType().withConst();
13331 DeclRefType = CaptureType;
13333 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13334 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13335 // The capture logic needs the destructor, so make sure we mark it.
13336 // Usually this is unnecessary because most local variables have
13337 // their destructors marked at declaration time, but parameters are
13338 // an exception because it's technically only the call site that
13339 // actually requires the destructor.
13340 if (isa<ParmVarDecl>(Var))
13341 S.FinalizeVarWithDestructor(Var, Record);
13343 // Enter a new evaluation context to insulate the copy
13344 // full-expression.
13345 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13347 // According to the blocks spec, the capture of a variable from
13348 // the stack requires a const copy constructor. This is not true
13349 // of the copy/move done to move a __block variable to the heap.
13350 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13351 DeclRefType.withConst(),
13355 = S.PerformCopyInitialization(
13356 InitializedEntity::InitializeBlock(Var->getLocation(),
13357 CaptureType, false),
13360 // Build a full-expression copy expression if initialization
13361 // succeeded and used a non-trivial constructor. Recover from
13362 // errors by pretending that the copy isn't necessary.
13363 if (!Result.isInvalid() &&
13364 !cast<CXXConstructExpr>(Result.get())->getConstructor()
13366 Result = S.MaybeCreateExprWithCleanups(Result);
13367 CopyExpr = Result.get();
13373 // Actually capture the variable.
13374 if (BuildAndDiagnose)
13375 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13376 SourceLocation(), CaptureType, CopyExpr);
13383 /// \brief Capture the given variable in the captured region.
13384 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13386 SourceLocation Loc,
13387 const bool BuildAndDiagnose,
13388 QualType &CaptureType,
13389 QualType &DeclRefType,
13390 const bool RefersToCapturedVariable,
13392 // By default, capture variables by reference.
13394 // Using an LValue reference type is consistent with Lambdas (see below).
13395 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13396 if (S.IsOpenMPCapturedDecl(Var))
13397 DeclRefType = DeclRefType.getUnqualifiedType();
13398 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13402 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13404 CaptureType = DeclRefType;
13406 Expr *CopyExpr = nullptr;
13407 if (BuildAndDiagnose) {
13408 // The current implementation assumes that all variables are captured
13409 // by references. Since there is no capture by copy, no expression
13410 // evaluation will be needed.
13411 RecordDecl *RD = RSI->TheRecordDecl;
13414 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13415 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13416 nullptr, false, ICIS_NoInit);
13417 Field->setImplicit(true);
13418 Field->setAccess(AS_private);
13419 RD->addDecl(Field);
13421 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13422 DeclRefType, VK_LValue, Loc);
13423 Var->setReferenced(true);
13424 Var->markUsed(S.Context);
13427 // Actually capture the variable.
13428 if (BuildAndDiagnose)
13429 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13430 SourceLocation(), CaptureType, CopyExpr);
13436 /// \brief Create a field within the lambda class for the variable
13437 /// being captured.
13438 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13439 QualType FieldType, QualType DeclRefType,
13440 SourceLocation Loc,
13441 bool RefersToCapturedVariable) {
13442 CXXRecordDecl *Lambda = LSI->Lambda;
13444 // Build the non-static data member.
13446 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13447 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13448 nullptr, false, ICIS_NoInit);
13449 Field->setImplicit(true);
13450 Field->setAccess(AS_private);
13451 Lambda->addDecl(Field);
13454 /// \brief Capture the given variable in the lambda.
13455 static bool captureInLambda(LambdaScopeInfo *LSI,
13457 SourceLocation Loc,
13458 const bool BuildAndDiagnose,
13459 QualType &CaptureType,
13460 QualType &DeclRefType,
13461 const bool RefersToCapturedVariable,
13462 const Sema::TryCaptureKind Kind,
13463 SourceLocation EllipsisLoc,
13464 const bool IsTopScope,
13467 // Determine whether we are capturing by reference or by value.
13468 bool ByRef = false;
13469 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13470 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13472 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13475 // Compute the type of the field that will capture this variable.
13477 // C++11 [expr.prim.lambda]p15:
13478 // An entity is captured by reference if it is implicitly or
13479 // explicitly captured but not captured by copy. It is
13480 // unspecified whether additional unnamed non-static data
13481 // members are declared in the closure type for entities
13482 // captured by reference.
13484 // FIXME: It is not clear whether we want to build an lvalue reference
13485 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13486 // to do the former, while EDG does the latter. Core issue 1249 will
13487 // clarify, but for now we follow GCC because it's a more permissive and
13488 // easily defensible position.
13489 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13491 // C++11 [expr.prim.lambda]p14:
13492 // For each entity captured by copy, an unnamed non-static
13493 // data member is declared in the closure type. The
13494 // declaration order of these members is unspecified. The type
13495 // of such a data member is the type of the corresponding
13496 // captured entity if the entity is not a reference to an
13497 // object, or the referenced type otherwise. [Note: If the
13498 // captured entity is a reference to a function, the
13499 // corresponding data member is also a reference to a
13500 // function. - end note ]
13501 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13502 if (!RefType->getPointeeType()->isFunctionType())
13503 CaptureType = RefType->getPointeeType();
13506 // Forbid the lambda copy-capture of autoreleasing variables.
13507 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13508 if (BuildAndDiagnose) {
13509 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13510 S.Diag(Var->getLocation(), diag::note_previous_decl)
13511 << Var->getDeclName();
13516 // Make sure that by-copy captures are of a complete and non-abstract type.
13517 if (BuildAndDiagnose) {
13518 if (!CaptureType->isDependentType() &&
13519 S.RequireCompleteType(Loc, CaptureType,
13520 diag::err_capture_of_incomplete_type,
13521 Var->getDeclName()))
13524 if (S.RequireNonAbstractType(Loc, CaptureType,
13525 diag::err_capture_of_abstract_type))
13530 // Capture this variable in the lambda.
13531 if (BuildAndDiagnose)
13532 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13533 RefersToCapturedVariable);
13535 // Compute the type of a reference to this captured variable.
13537 DeclRefType = CaptureType.getNonReferenceType();
13539 // C++ [expr.prim.lambda]p5:
13540 // The closure type for a lambda-expression has a public inline
13541 // function call operator [...]. This function call operator is
13542 // declared const (9.3.1) if and only if the lambda-expression’s
13543 // parameter-declaration-clause is not followed by mutable.
13544 DeclRefType = CaptureType.getNonReferenceType();
13545 if (!LSI->Mutable && !CaptureType->isReferenceType())
13546 DeclRefType.addConst();
13549 // Add the capture.
13550 if (BuildAndDiagnose)
13551 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13552 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13557 bool Sema::tryCaptureVariable(
13558 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13559 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13560 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13561 // An init-capture is notionally from the context surrounding its
13562 // declaration, but its parent DC is the lambda class.
13563 DeclContext *VarDC = Var->getDeclContext();
13564 if (Var->isInitCapture())
13565 VarDC = VarDC->getParent();
13567 DeclContext *DC = CurContext;
13568 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13569 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13570 // We need to sync up the Declaration Context with the
13571 // FunctionScopeIndexToStopAt
13572 if (FunctionScopeIndexToStopAt) {
13573 unsigned FSIndex = FunctionScopes.size() - 1;
13574 while (FSIndex != MaxFunctionScopesIndex) {
13575 DC = getLambdaAwareParentOfDeclContext(DC);
13581 // If the variable is declared in the current context, there is no need to
13583 if (VarDC == DC) return true;
13585 // Capture global variables if it is required to use private copy of this
13587 bool IsGlobal = !Var->hasLocalStorage();
13588 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13591 // Walk up the stack to determine whether we can capture the variable,
13592 // performing the "simple" checks that don't depend on type. We stop when
13593 // we've either hit the declared scope of the variable or find an existing
13594 // capture of that variable. We start from the innermost capturing-entity
13595 // (the DC) and ensure that all intervening capturing-entities
13596 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13597 // declcontext can either capture the variable or have already captured
13599 CaptureType = Var->getType();
13600 DeclRefType = CaptureType.getNonReferenceType();
13601 bool Nested = false;
13602 bool Explicit = (Kind != TryCapture_Implicit);
13603 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13605 // Only block literals, captured statements, and lambda expressions can
13606 // capture; other scopes don't work.
13607 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13611 // We need to check for the parent *first* because, if we *have*
13612 // private-captured a global variable, we need to recursively capture it in
13613 // intermediate blocks, lambdas, etc.
13616 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13622 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
13623 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13626 // Check whether we've already captured it.
13627 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13630 // If we are instantiating a generic lambda call operator body,
13631 // we do not want to capture new variables. What was captured
13632 // during either a lambdas transformation or initial parsing
13634 if (isGenericLambdaCallOperatorSpecialization(DC)) {
13635 if (BuildAndDiagnose) {
13636 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13637 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13638 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13639 Diag(Var->getLocation(), diag::note_previous_decl)
13640 << Var->getDeclName();
13641 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13643 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13647 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13648 // certain types of variables (unnamed, variably modified types etc.)
13649 // so check for eligibility.
13650 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13653 // Try to capture variable-length arrays types.
13654 if (Var->getType()->isVariablyModifiedType()) {
13655 // We're going to walk down into the type and look for VLA
13657 QualType QTy = Var->getType();
13658 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13659 QTy = PVD->getOriginalType();
13660 captureVariablyModifiedType(Context, QTy, CSI);
13663 if (getLangOpts().OpenMP) {
13664 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13665 // OpenMP private variables should not be captured in outer scope, so
13666 // just break here. Similarly, global variables that are captured in a
13667 // target region should not be captured outside the scope of the region.
13668 if (RSI->CapRegionKind == CR_OpenMP) {
13669 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13670 // When we detect target captures we are looking from inside the
13671 // target region, therefore we need to propagate the capture from the
13672 // enclosing region. Therefore, the capture is not initially nested.
13674 FunctionScopesIndex--;
13676 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13677 Nested = !IsTargetCap;
13678 DeclRefType = DeclRefType.getUnqualifiedType();
13679 CaptureType = Context.getLValueReferenceType(DeclRefType);
13685 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13686 // No capture-default, and this is not an explicit capture
13687 // so cannot capture this variable.
13688 if (BuildAndDiagnose) {
13689 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13690 Diag(Var->getLocation(), diag::note_previous_decl)
13691 << Var->getDeclName();
13692 if (cast<LambdaScopeInfo>(CSI)->Lambda)
13693 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13694 diag::note_lambda_decl);
13695 // FIXME: If we error out because an outer lambda can not implicitly
13696 // capture a variable that an inner lambda explicitly captures, we
13697 // should have the inner lambda do the explicit capture - because
13698 // it makes for cleaner diagnostics later. This would purely be done
13699 // so that the diagnostic does not misleadingly claim that a variable
13700 // can not be captured by a lambda implicitly even though it is captured
13701 // explicitly. Suggestion:
13702 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13703 // at the function head
13704 // - cache the StartingDeclContext - this must be a lambda
13705 // - captureInLambda in the innermost lambda the variable.
13710 FunctionScopesIndex--;
13713 } while (!VarDC->Equals(DC));
13715 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13716 // computing the type of the capture at each step, checking type-specific
13717 // requirements, and adding captures if requested.
13718 // If the variable had already been captured previously, we start capturing
13719 // at the lambda nested within that one.
13720 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13722 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13724 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13725 if (!captureInBlock(BSI, Var, ExprLoc,
13726 BuildAndDiagnose, CaptureType,
13727 DeclRefType, Nested, *this))
13730 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13731 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13732 BuildAndDiagnose, CaptureType,
13733 DeclRefType, Nested, *this))
13737 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13738 if (!captureInLambda(LSI, Var, ExprLoc,
13739 BuildAndDiagnose, CaptureType,
13740 DeclRefType, Nested, Kind, EllipsisLoc,
13741 /*IsTopScope*/I == N - 1, *this))
13749 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13750 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13751 QualType CaptureType;
13752 QualType DeclRefType;
13753 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13754 /*BuildAndDiagnose=*/true, CaptureType,
13755 DeclRefType, nullptr);
13758 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13759 QualType CaptureType;
13760 QualType DeclRefType;
13761 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13762 /*BuildAndDiagnose=*/false, CaptureType,
13763 DeclRefType, nullptr);
13766 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13767 QualType CaptureType;
13768 QualType DeclRefType;
13770 // Determine whether we can capture this variable.
13771 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13772 /*BuildAndDiagnose=*/false, CaptureType,
13773 DeclRefType, nullptr))
13776 return DeclRefType;
13781 // If either the type of the variable or the initializer is dependent,
13782 // return false. Otherwise, determine whether the variable is a constant
13783 // expression. Use this if you need to know if a variable that might or
13784 // might not be dependent is truly a constant expression.
13785 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13786 ASTContext &Context) {
13788 if (Var->getType()->isDependentType())
13790 const VarDecl *DefVD = nullptr;
13791 Var->getAnyInitializer(DefVD);
13794 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13795 Expr *Init = cast<Expr>(Eval->Value);
13796 if (Init->isValueDependent())
13798 return IsVariableAConstantExpression(Var, Context);
13802 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13803 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13804 // an object that satisfies the requirements for appearing in a
13805 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13806 // is immediately applied." This function handles the lvalue-to-rvalue
13807 // conversion part.
13808 MaybeODRUseExprs.erase(E->IgnoreParens());
13810 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13811 // to a variable that is a constant expression, and if so, identify it as
13812 // a reference to a variable that does not involve an odr-use of that
13814 if (LambdaScopeInfo *LSI = getCurLambda()) {
13815 Expr *SansParensExpr = E->IgnoreParens();
13816 VarDecl *Var = nullptr;
13817 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13818 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13819 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13820 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13822 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13823 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13827 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13828 Res = CorrectDelayedTyposInExpr(Res);
13830 if (!Res.isUsable())
13833 // If a constant-expression is a reference to a variable where we delay
13834 // deciding whether it is an odr-use, just assume we will apply the
13835 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
13836 // (a non-type template argument), we have special handling anyway.
13837 UpdateMarkingForLValueToRValue(Res.get());
13841 void Sema::CleanupVarDeclMarking() {
13842 for (Expr *E : MaybeODRUseExprs) {
13844 SourceLocation Loc;
13845 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13846 Var = cast<VarDecl>(DRE->getDecl());
13847 Loc = DRE->getLocation();
13848 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13849 Var = cast<VarDecl>(ME->getMemberDecl());
13850 Loc = ME->getMemberLoc();
13852 llvm_unreachable("Unexpected expression");
13855 MarkVarDeclODRUsed(Var, Loc, *this,
13856 /*MaxFunctionScopeIndex Pointer*/ nullptr);
13859 MaybeODRUseExprs.clear();
13863 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13864 VarDecl *Var, Expr *E) {
13865 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13866 "Invalid Expr argument to DoMarkVarDeclReferenced");
13867 Var->setReferenced();
13869 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13870 bool MarkODRUsed = true;
13872 // If the context is not potentially evaluated, this is not an odr-use and
13873 // does not trigger instantiation.
13874 if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13875 if (SemaRef.isUnevaluatedContext())
13878 // If we don't yet know whether this context is going to end up being an
13879 // evaluated context, and we're referencing a variable from an enclosing
13880 // scope, add a potential capture.
13882 // FIXME: Is this necessary? These contexts are only used for default
13883 // arguments, where local variables can't be used.
13884 const bool RefersToEnclosingScope =
13885 (SemaRef.CurContext != Var->getDeclContext() &&
13886 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13887 if (RefersToEnclosingScope) {
13888 if (LambdaScopeInfo *const LSI =
13889 SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
13890 // If a variable could potentially be odr-used, defer marking it so
13891 // until we finish analyzing the full expression for any
13892 // lvalue-to-rvalue
13893 // or discarded value conversions that would obviate odr-use.
13894 // Add it to the list of potential captures that will be analyzed
13895 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13896 // unless the variable is a reference that was initialized by a constant
13897 // expression (this will never need to be captured or odr-used).
13898 assert(E && "Capture variable should be used in an expression.");
13899 if (!Var->getType()->isReferenceType() ||
13900 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13901 LSI->addPotentialCapture(E->IgnoreParens());
13905 if (!isTemplateInstantiation(TSK))
13908 // Instantiate, but do not mark as odr-used, variable templates.
13909 MarkODRUsed = false;
13912 VarTemplateSpecializationDecl *VarSpec =
13913 dyn_cast<VarTemplateSpecializationDecl>(Var);
13914 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13915 "Can't instantiate a partial template specialization.");
13917 // If this might be a member specialization of a static data member, check
13918 // the specialization is visible. We already did the checks for variable
13919 // template specializations when we created them.
13920 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
13921 SemaRef.checkSpecializationVisibility(Loc, Var);
13923 // Perform implicit instantiation of static data members, static data member
13924 // templates of class templates, and variable template specializations. Delay
13925 // instantiations of variable templates, except for those that could be used
13926 // in a constant expression.
13927 if (isTemplateInstantiation(TSK)) {
13928 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13930 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13931 if (Var->getPointOfInstantiation().isInvalid()) {
13932 // This is a modification of an existing AST node. Notify listeners.
13933 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13934 L->StaticDataMemberInstantiated(Var);
13935 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13936 // Don't bother trying to instantiate it again, unless we might need
13937 // its initializer before we get to the end of the TU.
13938 TryInstantiating = false;
13941 if (Var->getPointOfInstantiation().isInvalid())
13942 Var->setTemplateSpecializationKind(TSK, Loc);
13944 if (TryInstantiating) {
13945 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13946 bool InstantiationDependent = false;
13947 bool IsNonDependent =
13948 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13949 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13952 // Do not instantiate specializations that are still type-dependent.
13953 if (IsNonDependent) {
13954 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13955 // Do not defer instantiations of variables which could be used in a
13956 // constant expression.
13957 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13959 SemaRef.PendingInstantiations
13960 .push_back(std::make_pair(Var, PointOfInstantiation));
13969 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13970 // the requirements for appearing in a constant expression (5.19) and, if
13971 // it is an object, the lvalue-to-rvalue conversion (4.1)
13972 // is immediately applied." We check the first part here, and
13973 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13974 // Note that we use the C++11 definition everywhere because nothing in
13975 // C++03 depends on whether we get the C++03 version correct. The second
13976 // part does not apply to references, since they are not objects.
13977 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13978 // A reference initialized by a constant expression can never be
13979 // odr-used, so simply ignore it.
13980 if (!Var->getType()->isReferenceType())
13981 SemaRef.MaybeODRUseExprs.insert(E);
13983 MarkVarDeclODRUsed(Var, Loc, SemaRef,
13984 /*MaxFunctionScopeIndex ptr*/ nullptr);
13987 /// \brief Mark a variable referenced, and check whether it is odr-used
13988 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
13989 /// used directly for normal expressions referring to VarDecl.
13990 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13991 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13994 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13995 Decl *D, Expr *E, bool MightBeOdrUse) {
13996 if (SemaRef.isInOpenMPDeclareTargetContext())
13997 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
13999 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14000 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14004 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14006 // If this is a call to a method via a cast, also mark the method in the
14007 // derived class used in case codegen can devirtualize the call.
14008 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14011 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14014 // Only attempt to devirtualize if this is truly a virtual call.
14015 bool IsVirtualCall = MD->isVirtual() &&
14016 ME->performsVirtualDispatch(SemaRef.getLangOpts());
14017 if (!IsVirtualCall)
14019 const Expr *Base = ME->getBase();
14020 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14021 if (!MostDerivedClassDecl)
14023 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14024 if (!DM || DM->isPure())
14026 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14029 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14030 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14031 // TODO: update this with DR# once a defect report is filed.
14032 // C++11 defect. The address of a pure member should not be an ODR use, even
14033 // if it's a qualified reference.
14034 bool OdrUse = true;
14035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14036 if (Method->isVirtual())
14038 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14041 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14042 void Sema::MarkMemberReferenced(MemberExpr *E) {
14043 // C++11 [basic.def.odr]p2:
14044 // A non-overloaded function whose name appears as a potentially-evaluated
14045 // expression or a member of a set of candidate functions, if selected by
14046 // overload resolution when referred to from a potentially-evaluated
14047 // expression, is odr-used, unless it is a pure virtual function and its
14048 // name is not explicitly qualified.
14049 bool MightBeOdrUse = true;
14050 if (E->performsVirtualDispatch(getLangOpts())) {
14051 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14052 if (Method->isPure())
14053 MightBeOdrUse = false;
14055 SourceLocation Loc = E->getMemberLoc().isValid() ?
14056 E->getMemberLoc() : E->getLocStart();
14057 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14060 /// \brief Perform marking for a reference to an arbitrary declaration. It
14061 /// marks the declaration referenced, and performs odr-use checking for
14062 /// functions and variables. This method should not be used when building a
14063 /// normal expression which refers to a variable.
14064 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14065 bool MightBeOdrUse) {
14066 if (MightBeOdrUse) {
14067 if (auto *VD = dyn_cast<VarDecl>(D)) {
14068 MarkVariableReferenced(Loc, VD);
14072 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14073 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14076 D->setReferenced();
14080 // Mark all of the declarations referenced
14081 // FIXME: Not fully implemented yet! We need to have a better understanding
14082 // of when we're entering
14083 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14085 SourceLocation Loc;
14088 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14090 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14092 bool TraverseTemplateArgument(const TemplateArgument &Arg);
14093 bool TraverseRecordType(RecordType *T);
14097 bool MarkReferencedDecls::TraverseTemplateArgument(
14098 const TemplateArgument &Arg) {
14099 if (Arg.getKind() == TemplateArgument::Declaration) {
14100 if (Decl *D = Arg.getAsDecl())
14101 S.MarkAnyDeclReferenced(Loc, D, true);
14104 return Inherited::TraverseTemplateArgument(Arg);
14107 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14108 if (ClassTemplateSpecializationDecl *Spec
14109 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14110 const TemplateArgumentList &Args = Spec->getTemplateArgs();
14111 return TraverseTemplateArguments(Args.data(), Args.size());
14117 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14118 MarkReferencedDecls Marker(*this, Loc);
14119 Marker.TraverseType(Context.getCanonicalType(T));
14123 /// \brief Helper class that marks all of the declarations referenced by
14124 /// potentially-evaluated subexpressions as "referenced".
14125 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14127 bool SkipLocalVariables;
14130 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14132 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14133 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14135 void VisitDeclRefExpr(DeclRefExpr *E) {
14136 // If we were asked not to visit local variables, don't.
14137 if (SkipLocalVariables) {
14138 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14139 if (VD->hasLocalStorage())
14143 S.MarkDeclRefReferenced(E);
14146 void VisitMemberExpr(MemberExpr *E) {
14147 S.MarkMemberReferenced(E);
14148 Inherited::VisitMemberExpr(E);
14151 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14152 S.MarkFunctionReferenced(E->getLocStart(),
14153 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14154 Visit(E->getSubExpr());
14157 void VisitCXXNewExpr(CXXNewExpr *E) {
14158 if (E->getOperatorNew())
14159 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14160 if (E->getOperatorDelete())
14161 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14162 Inherited::VisitCXXNewExpr(E);
14165 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14166 if (E->getOperatorDelete())
14167 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14168 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14169 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14170 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14171 S.MarkFunctionReferenced(E->getLocStart(),
14172 S.LookupDestructor(Record));
14175 Inherited::VisitCXXDeleteExpr(E);
14178 void VisitCXXConstructExpr(CXXConstructExpr *E) {
14179 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14180 Inherited::VisitCXXConstructExpr(E);
14183 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14184 Visit(E->getExpr());
14187 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14188 Inherited::VisitImplicitCastExpr(E);
14190 if (E->getCastKind() == CK_LValueToRValue)
14191 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14196 /// \brief Mark any declarations that appear within this expression or any
14197 /// potentially-evaluated subexpressions as "referenced".
14199 /// \param SkipLocalVariables If true, don't mark local variables as
14201 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14202 bool SkipLocalVariables) {
14203 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14206 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14207 /// of the program being compiled.
14209 /// This routine emits the given diagnostic when the code currently being
14210 /// type-checked is "potentially evaluated", meaning that there is a
14211 /// possibility that the code will actually be executable. Code in sizeof()
14212 /// expressions, code used only during overload resolution, etc., are not
14213 /// potentially evaluated. This routine will suppress such diagnostics or,
14214 /// in the absolutely nutty case of potentially potentially evaluated
14215 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14218 /// This routine should be used for all diagnostics that describe the run-time
14219 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14220 /// Failure to do so will likely result in spurious diagnostics or failures
14221 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14222 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14223 const PartialDiagnostic &PD) {
14224 switch (ExprEvalContexts.back().Context) {
14226 case UnevaluatedAbstract:
14227 case DiscardedStatement:
14228 // The argument will never be evaluated, so don't complain.
14231 case ConstantEvaluated:
14232 // Relevant diagnostics should be produced by constant evaluation.
14235 case PotentiallyEvaluated:
14236 case PotentiallyEvaluatedIfUsed:
14237 if (Statement && getCurFunctionOrMethodDecl()) {
14238 FunctionScopes.back()->PossiblyUnreachableDiags.
14239 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14250 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14251 CallExpr *CE, FunctionDecl *FD) {
14252 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14255 // If we're inside a decltype's expression, don't check for a valid return
14256 // type or construct temporaries until we know whether this is the last call.
14257 if (ExprEvalContexts.back().IsDecltype) {
14258 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14262 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14267 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14268 : FD(FD), CE(CE) { }
14270 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14272 S.Diag(Loc, diag::err_call_incomplete_return)
14273 << T << CE->getSourceRange();
14277 S.Diag(Loc, diag::err_call_function_incomplete_return)
14278 << CE->getSourceRange() << FD->getDeclName() << T;
14279 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14280 << FD->getDeclName();
14282 } Diagnoser(FD, CE);
14284 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14290 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14291 // will prevent this condition from triggering, which is what we want.
14292 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14293 SourceLocation Loc;
14295 unsigned diagnostic = diag::warn_condition_is_assignment;
14296 bool IsOrAssign = false;
14298 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14299 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14302 IsOrAssign = Op->getOpcode() == BO_OrAssign;
14304 // Greylist some idioms by putting them into a warning subcategory.
14305 if (ObjCMessageExpr *ME
14306 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14307 Selector Sel = ME->getSelector();
14309 // self = [<foo> init...]
14310 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14311 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14313 // <foo> = [<bar> nextObject]
14314 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14315 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14318 Loc = Op->getOperatorLoc();
14319 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14320 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14323 IsOrAssign = Op->getOperator() == OO_PipeEqual;
14324 Loc = Op->getOperatorLoc();
14325 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14326 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14328 // Not an assignment.
14332 Diag(Loc, diagnostic) << E->getSourceRange();
14334 SourceLocation Open = E->getLocStart();
14335 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14336 Diag(Loc, diag::note_condition_assign_silence)
14337 << FixItHint::CreateInsertion(Open, "(")
14338 << FixItHint::CreateInsertion(Close, ")");
14341 Diag(Loc, diag::note_condition_or_assign_to_comparison)
14342 << FixItHint::CreateReplacement(Loc, "!=");
14344 Diag(Loc, diag::note_condition_assign_to_comparison)
14345 << FixItHint::CreateReplacement(Loc, "==");
14348 /// \brief Redundant parentheses over an equality comparison can indicate
14349 /// that the user intended an assignment used as condition.
14350 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14351 // Don't warn if the parens came from a macro.
14352 SourceLocation parenLoc = ParenE->getLocStart();
14353 if (parenLoc.isInvalid() || parenLoc.isMacroID())
14355 // Don't warn for dependent expressions.
14356 if (ParenE->isTypeDependent())
14359 Expr *E = ParenE->IgnoreParens();
14361 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14362 if (opE->getOpcode() == BO_EQ &&
14363 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14364 == Expr::MLV_Valid) {
14365 SourceLocation Loc = opE->getOperatorLoc();
14367 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14368 SourceRange ParenERange = ParenE->getSourceRange();
14369 Diag(Loc, diag::note_equality_comparison_silence)
14370 << FixItHint::CreateRemoval(ParenERange.getBegin())
14371 << FixItHint::CreateRemoval(ParenERange.getEnd());
14372 Diag(Loc, diag::note_equality_comparison_to_assign)
14373 << FixItHint::CreateReplacement(Loc, "=");
14377 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14378 bool IsConstexpr) {
14379 DiagnoseAssignmentAsCondition(E);
14380 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14381 DiagnoseEqualityWithExtraParens(parenE);
14383 ExprResult result = CheckPlaceholderExpr(E);
14384 if (result.isInvalid()) return ExprError();
14387 if (!E->isTypeDependent()) {
14388 if (getLangOpts().CPlusPlus)
14389 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14391 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14392 if (ERes.isInvalid())
14393 return ExprError();
14396 QualType T = E->getType();
14397 if (!T->isScalarType()) { // C99 6.8.4.1p1
14398 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14399 << T << E->getSourceRange();
14400 return ExprError();
14402 CheckBoolLikeConversion(E, Loc);
14408 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14409 Expr *SubExpr, ConditionKind CK) {
14410 // Empty conditions are valid in for-statements.
14412 return ConditionResult();
14416 case ConditionKind::Boolean:
14417 Cond = CheckBooleanCondition(Loc, SubExpr);
14420 case ConditionKind::ConstexprIf:
14421 Cond = CheckBooleanCondition(Loc, SubExpr, true);
14424 case ConditionKind::Switch:
14425 Cond = CheckSwitchCondition(Loc, SubExpr);
14428 if (Cond.isInvalid())
14429 return ConditionError();
14431 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14432 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14433 if (!FullExpr.get())
14434 return ConditionError();
14436 return ConditionResult(*this, nullptr, FullExpr,
14437 CK == ConditionKind::ConstexprIf);
14441 /// A visitor for rebuilding a call to an __unknown_any expression
14442 /// to have an appropriate type.
14443 struct RebuildUnknownAnyFunction
14444 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14448 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14450 ExprResult VisitStmt(Stmt *S) {
14451 llvm_unreachable("unexpected statement!");
14454 ExprResult VisitExpr(Expr *E) {
14455 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14456 << E->getSourceRange();
14457 return ExprError();
14460 /// Rebuild an expression which simply semantically wraps another
14461 /// expression which it shares the type and value kind of.
14462 template <class T> ExprResult rebuildSugarExpr(T *E) {
14463 ExprResult SubResult = Visit(E->getSubExpr());
14464 if (SubResult.isInvalid()) return ExprError();
14466 Expr *SubExpr = SubResult.get();
14467 E->setSubExpr(SubExpr);
14468 E->setType(SubExpr->getType());
14469 E->setValueKind(SubExpr->getValueKind());
14470 assert(E->getObjectKind() == OK_Ordinary);
14474 ExprResult VisitParenExpr(ParenExpr *E) {
14475 return rebuildSugarExpr(E);
14478 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14479 return rebuildSugarExpr(E);
14482 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14483 ExprResult SubResult = Visit(E->getSubExpr());
14484 if (SubResult.isInvalid()) return ExprError();
14486 Expr *SubExpr = SubResult.get();
14487 E->setSubExpr(SubExpr);
14488 E->setType(S.Context.getPointerType(SubExpr->getType()));
14489 assert(E->getValueKind() == VK_RValue);
14490 assert(E->getObjectKind() == OK_Ordinary);
14494 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14495 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14497 E->setType(VD->getType());
14499 assert(E->getValueKind() == VK_RValue);
14500 if (S.getLangOpts().CPlusPlus &&
14501 !(isa<CXXMethodDecl>(VD) &&
14502 cast<CXXMethodDecl>(VD)->isInstance()))
14503 E->setValueKind(VK_LValue);
14508 ExprResult VisitMemberExpr(MemberExpr *E) {
14509 return resolveDecl(E, E->getMemberDecl());
14512 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14513 return resolveDecl(E, E->getDecl());
14518 /// Given a function expression of unknown-any type, try to rebuild it
14519 /// to have a function type.
14520 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14521 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14522 if (Result.isInvalid()) return ExprError();
14523 return S.DefaultFunctionArrayConversion(Result.get());
14527 /// A visitor for rebuilding an expression of type __unknown_anytype
14528 /// into one which resolves the type directly on the referring
14529 /// expression. Strict preservation of the original source
14530 /// structure is not a goal.
14531 struct RebuildUnknownAnyExpr
14532 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14536 /// The current destination type.
14539 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14540 : S(S), DestType(CastType) {}
14542 ExprResult VisitStmt(Stmt *S) {
14543 llvm_unreachable("unexpected statement!");
14546 ExprResult VisitExpr(Expr *E) {
14547 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14548 << E->getSourceRange();
14549 return ExprError();
14552 ExprResult VisitCallExpr(CallExpr *E);
14553 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14555 /// Rebuild an expression which simply semantically wraps another
14556 /// expression which it shares the type and value kind of.
14557 template <class T> ExprResult rebuildSugarExpr(T *E) {
14558 ExprResult SubResult = Visit(E->getSubExpr());
14559 if (SubResult.isInvalid()) return ExprError();
14560 Expr *SubExpr = SubResult.get();
14561 E->setSubExpr(SubExpr);
14562 E->setType(SubExpr->getType());
14563 E->setValueKind(SubExpr->getValueKind());
14564 assert(E->getObjectKind() == OK_Ordinary);
14568 ExprResult VisitParenExpr(ParenExpr *E) {
14569 return rebuildSugarExpr(E);
14572 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14573 return rebuildSugarExpr(E);
14576 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14577 const PointerType *Ptr = DestType->getAs<PointerType>();
14579 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14580 << E->getSourceRange();
14581 return ExprError();
14583 assert(E->getValueKind() == VK_RValue);
14584 assert(E->getObjectKind() == OK_Ordinary);
14585 E->setType(DestType);
14587 // Build the sub-expression as if it were an object of the pointee type.
14588 DestType = Ptr->getPointeeType();
14589 ExprResult SubResult = Visit(E->getSubExpr());
14590 if (SubResult.isInvalid()) return ExprError();
14591 E->setSubExpr(SubResult.get());
14595 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14597 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14599 ExprResult VisitMemberExpr(MemberExpr *E) {
14600 return resolveDecl(E, E->getMemberDecl());
14603 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14604 return resolveDecl(E, E->getDecl());
14609 /// Rebuilds a call expression which yielded __unknown_anytype.
14610 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14611 Expr *CalleeExpr = E->getCallee();
14615 FK_FunctionPointer,
14620 QualType CalleeType = CalleeExpr->getType();
14621 if (CalleeType == S.Context.BoundMemberTy) {
14622 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14623 Kind = FK_MemberFunction;
14624 CalleeType = Expr::findBoundMemberType(CalleeExpr);
14625 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14626 CalleeType = Ptr->getPointeeType();
14627 Kind = FK_FunctionPointer;
14629 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14630 Kind = FK_BlockPointer;
14632 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14634 // Verify that this is a legal result type of a function.
14635 if (DestType->isArrayType() || DestType->isFunctionType()) {
14636 unsigned diagID = diag::err_func_returning_array_function;
14637 if (Kind == FK_BlockPointer)
14638 diagID = diag::err_block_returning_array_function;
14640 S.Diag(E->getExprLoc(), diagID)
14641 << DestType->isFunctionType() << DestType;
14642 return ExprError();
14645 // Otherwise, go ahead and set DestType as the call's result.
14646 E->setType(DestType.getNonLValueExprType(S.Context));
14647 E->setValueKind(Expr::getValueKindForType(DestType));
14648 assert(E->getObjectKind() == OK_Ordinary);
14650 // Rebuild the function type, replacing the result type with DestType.
14651 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14653 // __unknown_anytype(...) is a special case used by the debugger when
14654 // it has no idea what a function's signature is.
14656 // We want to build this call essentially under the K&R
14657 // unprototyped rules, but making a FunctionNoProtoType in C++
14658 // would foul up all sorts of assumptions. However, we cannot
14659 // simply pass all arguments as variadic arguments, nor can we
14660 // portably just call the function under a non-variadic type; see
14661 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14662 // However, it turns out that in practice it is generally safe to
14663 // call a function declared as "A foo(B,C,D);" under the prototype
14664 // "A foo(B,C,D,...);". The only known exception is with the
14665 // Windows ABI, where any variadic function is implicitly cdecl
14666 // regardless of its normal CC. Therefore we change the parameter
14667 // types to match the types of the arguments.
14669 // This is a hack, but it is far superior to moving the
14670 // corresponding target-specific code from IR-gen to Sema/AST.
14672 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14673 SmallVector<QualType, 8> ArgTypes;
14674 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14675 ArgTypes.reserve(E->getNumArgs());
14676 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14677 Expr *Arg = E->getArg(i);
14678 QualType ArgType = Arg->getType();
14679 if (E->isLValue()) {
14680 ArgType = S.Context.getLValueReferenceType(ArgType);
14681 } else if (E->isXValue()) {
14682 ArgType = S.Context.getRValueReferenceType(ArgType);
14684 ArgTypes.push_back(ArgType);
14686 ParamTypes = ArgTypes;
14688 DestType = S.Context.getFunctionType(DestType, ParamTypes,
14689 Proto->getExtProtoInfo());
14691 DestType = S.Context.getFunctionNoProtoType(DestType,
14692 FnType->getExtInfo());
14695 // Rebuild the appropriate pointer-to-function type.
14697 case FK_MemberFunction:
14701 case FK_FunctionPointer:
14702 DestType = S.Context.getPointerType(DestType);
14705 case FK_BlockPointer:
14706 DestType = S.Context.getBlockPointerType(DestType);
14710 // Finally, we can recurse.
14711 ExprResult CalleeResult = Visit(CalleeExpr);
14712 if (!CalleeResult.isUsable()) return ExprError();
14713 E->setCallee(CalleeResult.get());
14715 // Bind a temporary if necessary.
14716 return S.MaybeBindToTemporary(E);
14719 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14720 // Verify that this is a legal result type of a call.
14721 if (DestType->isArrayType() || DestType->isFunctionType()) {
14722 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14723 << DestType->isFunctionType() << DestType;
14724 return ExprError();
14727 // Rewrite the method result type if available.
14728 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14729 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14730 Method->setReturnType(DestType);
14733 // Change the type of the message.
14734 E->setType(DestType.getNonReferenceType());
14735 E->setValueKind(Expr::getValueKindForType(DestType));
14737 return S.MaybeBindToTemporary(E);
14740 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14741 // The only case we should ever see here is a function-to-pointer decay.
14742 if (E->getCastKind() == CK_FunctionToPointerDecay) {
14743 assert(E->getValueKind() == VK_RValue);
14744 assert(E->getObjectKind() == OK_Ordinary);
14746 E->setType(DestType);
14748 // Rebuild the sub-expression as the pointee (function) type.
14749 DestType = DestType->castAs<PointerType>()->getPointeeType();
14751 ExprResult Result = Visit(E->getSubExpr());
14752 if (!Result.isUsable()) return ExprError();
14754 E->setSubExpr(Result.get());
14756 } else if (E->getCastKind() == CK_LValueToRValue) {
14757 assert(E->getValueKind() == VK_RValue);
14758 assert(E->getObjectKind() == OK_Ordinary);
14760 assert(isa<BlockPointerType>(E->getType()));
14762 E->setType(DestType);
14764 // The sub-expression has to be a lvalue reference, so rebuild it as such.
14765 DestType = S.Context.getLValueReferenceType(DestType);
14767 ExprResult Result = Visit(E->getSubExpr());
14768 if (!Result.isUsable()) return ExprError();
14770 E->setSubExpr(Result.get());
14773 llvm_unreachable("Unhandled cast type!");
14777 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14778 ExprValueKind ValueKind = VK_LValue;
14779 QualType Type = DestType;
14781 // We know how to make this work for certain kinds of decls:
14784 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14785 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14786 DestType = Ptr->getPointeeType();
14787 ExprResult Result = resolveDecl(E, VD);
14788 if (Result.isInvalid()) return ExprError();
14789 return S.ImpCastExprToType(Result.get(), Type,
14790 CK_FunctionToPointerDecay, VK_RValue);
14793 if (!Type->isFunctionType()) {
14794 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14795 << VD << E->getSourceRange();
14796 return ExprError();
14798 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14799 // We must match the FunctionDecl's type to the hack introduced in
14800 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14801 // type. See the lengthy commentary in that routine.
14802 QualType FDT = FD->getType();
14803 const FunctionType *FnType = FDT->castAs<FunctionType>();
14804 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14805 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14806 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14807 SourceLocation Loc = FD->getLocation();
14808 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14809 FD->getDeclContext(),
14810 Loc, Loc, FD->getNameInfo().getName(),
14811 DestType, FD->getTypeSourceInfo(),
14812 SC_None, false/*isInlineSpecified*/,
14813 FD->hasPrototype(),
14814 false/*isConstexprSpecified*/);
14816 if (FD->getQualifier())
14817 NewFD->setQualifierInfo(FD->getQualifierLoc());
14819 SmallVector<ParmVarDecl*, 16> Params;
14820 for (const auto &AI : FT->param_types()) {
14821 ParmVarDecl *Param =
14822 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14823 Param->setScopeInfo(0, Params.size());
14824 Params.push_back(Param);
14826 NewFD->setParams(Params);
14827 DRE->setDecl(NewFD);
14828 VD = DRE->getDecl();
14832 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14833 if (MD->isInstance()) {
14834 ValueKind = VK_RValue;
14835 Type = S.Context.BoundMemberTy;
14838 // Function references aren't l-values in C.
14839 if (!S.getLangOpts().CPlusPlus)
14840 ValueKind = VK_RValue;
14843 } else if (isa<VarDecl>(VD)) {
14844 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14845 Type = RefTy->getPointeeType();
14846 } else if (Type->isFunctionType()) {
14847 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14848 << VD << E->getSourceRange();
14849 return ExprError();
14854 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14855 << VD << E->getSourceRange();
14856 return ExprError();
14859 // Modifying the declaration like this is friendly to IR-gen but
14860 // also really dangerous.
14861 VD->setType(DestType);
14863 E->setValueKind(ValueKind);
14867 /// Check a cast of an unknown-any type. We intentionally only
14868 /// trigger this for C-style casts.
14869 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14870 Expr *CastExpr, CastKind &CastKind,
14871 ExprValueKind &VK, CXXCastPath &Path) {
14872 // The type we're casting to must be either void or complete.
14873 if (!CastType->isVoidType() &&
14874 RequireCompleteType(TypeRange.getBegin(), CastType,
14875 diag::err_typecheck_cast_to_incomplete))
14876 return ExprError();
14878 // Rewrite the casted expression from scratch.
14879 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14880 if (!result.isUsable()) return ExprError();
14882 CastExpr = result.get();
14883 VK = CastExpr->getValueKind();
14884 CastKind = CK_NoOp;
14889 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14890 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14893 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14894 Expr *arg, QualType ¶mType) {
14895 // If the syntactic form of the argument is not an explicit cast of
14896 // any sort, just do default argument promotion.
14897 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14899 ExprResult result = DefaultArgumentPromotion(arg);
14900 if (result.isInvalid()) return ExprError();
14901 paramType = result.get()->getType();
14905 // Otherwise, use the type that was written in the explicit cast.
14906 assert(!arg->hasPlaceholderType());
14907 paramType = castArg->getTypeAsWritten();
14909 // Copy-initialize a parameter of that type.
14910 InitializedEntity entity =
14911 InitializedEntity::InitializeParameter(Context, paramType,
14912 /*consumed*/ false);
14913 return PerformCopyInitialization(entity, callLoc, arg);
14916 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14918 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14920 E = E->IgnoreParenImpCasts();
14921 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14922 E = call->getCallee();
14923 diagID = diag::err_uncasted_call_of_unknown_any;
14929 SourceLocation loc;
14931 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14932 loc = ref->getLocation();
14933 d = ref->getDecl();
14934 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14935 loc = mem->getMemberLoc();
14936 d = mem->getMemberDecl();
14937 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14938 diagID = diag::err_uncasted_call_of_unknown_any;
14939 loc = msg->getSelectorStartLoc();
14940 d = msg->getMethodDecl();
14942 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14943 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14944 << orig->getSourceRange();
14945 return ExprError();
14948 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14949 << E->getSourceRange();
14950 return ExprError();
14953 S.Diag(loc, diagID) << d << orig->getSourceRange();
14955 // Never recoverable.
14956 return ExprError();
14959 /// Check for operands with placeholder types and complain if found.
14960 /// Returns true if there was an error and no recovery was possible.
14961 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14962 if (!getLangOpts().CPlusPlus) {
14963 // C cannot handle TypoExpr nodes on either side of a binop because it
14964 // doesn't handle dependent types properly, so make sure any TypoExprs have
14965 // been dealt with before checking the operands.
14966 ExprResult Result = CorrectDelayedTyposInExpr(E);
14967 if (!Result.isUsable()) return ExprError();
14971 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14972 if (!placeholderType) return E;
14974 switch (placeholderType->getKind()) {
14976 // Overloaded expressions.
14977 case BuiltinType::Overload: {
14978 // Try to resolve a single function template specialization.
14979 // This is obligatory.
14980 ExprResult Result = E;
14981 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
14984 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
14985 // leaves Result unchanged on failure.
14987 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
14990 // If that failed, try to recover with a call.
14991 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
14992 /*complain*/ true);
14996 // Bound member functions.
14997 case BuiltinType::BoundMember: {
14998 ExprResult result = E;
14999 const Expr *BME = E->IgnoreParens();
15000 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15001 // Try to give a nicer diagnostic if it is a bound member that we recognize.
15002 if (isa<CXXPseudoDestructorExpr>(BME)) {
15003 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15004 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15005 if (ME->getMemberNameInfo().getName().getNameKind() ==
15006 DeclarationName::CXXDestructorName)
15007 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15009 tryToRecoverWithCall(result, PD,
15010 /*complain*/ true);
15014 // ARC unbridged casts.
15015 case BuiltinType::ARCUnbridgedCast: {
15016 Expr *realCast = stripARCUnbridgedCast(E);
15017 diagnoseARCUnbridgedCast(realCast);
15021 // Expressions of unknown type.
15022 case BuiltinType::UnknownAny:
15023 return diagnoseUnknownAnyExpr(*this, E);
15026 case BuiltinType::PseudoObject:
15027 return checkPseudoObjectRValue(E);
15029 case BuiltinType::BuiltinFn: {
15030 // Accept __noop without parens by implicitly converting it to a call expr.
15031 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15033 auto *FD = cast<FunctionDecl>(DRE->getDecl());
15034 if (FD->getBuiltinID() == Builtin::BI__noop) {
15035 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15036 CK_BuiltinFnToFnPtr).get();
15037 return new (Context) CallExpr(Context, E, None, Context.IntTy,
15038 VK_RValue, SourceLocation());
15042 Diag(E->getLocStart(), diag::err_builtin_fn_use);
15043 return ExprError();
15046 // Expressions of unknown type.
15047 case BuiltinType::OMPArraySection:
15048 Diag(E->getLocStart(), diag::err_omp_array_section_use);
15049 return ExprError();
15051 // Everything else should be impossible.
15052 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15053 case BuiltinType::Id:
15054 #include "clang/Basic/OpenCLImageTypes.def"
15055 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15056 #define PLACEHOLDER_TYPE(Id, SingletonId)
15057 #include "clang/AST/BuiltinTypes.def"
15061 llvm_unreachable("invalid placeholder type!");
15064 bool Sema::CheckCaseExpression(Expr *E) {
15065 if (E->isTypeDependent())
15067 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15068 return E->getType()->isIntegralOrEnumerationType();
15072 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15074 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15075 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15076 "Unknown Objective-C Boolean value!");
15077 QualType BoolT = Context.ObjCBuiltinBoolTy;
15078 if (!Context.getBOOLDecl()) {
15079 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15080 Sema::LookupOrdinaryName);
15081 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15082 NamedDecl *ND = Result.getFoundDecl();
15083 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15084 Context.setBOOLDecl(TD);
15087 if (Context.getBOOLDecl())
15088 BoolT = Context.getBOOLType();
15089 return new (Context)
15090 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15093 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15094 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15095 SourceLocation RParen) {
15097 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15099 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15100 [&](const AvailabilitySpec &Spec) {
15101 return Spec.getPlatform() == Platform;
15104 VersionTuple Version;
15105 if (Spec != AvailSpecs.end())
15106 Version = Spec->getVersion();
15108 // This is the '*' case in @available. We should diagnose this; the
15109 // programmer should explicitly account for this case if they target this
15111 Diag(AtLoc, diag::warn_available_using_star_case) << RParen << Platform;
15113 return new (Context)
15114 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);