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 "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.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>())
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108 AvailabilityResult Result = D->getAvailability(Message);
110 // For typedefs, if the typedef declaration appears available look
111 // to the underlying type to see if it is more restrictive.
112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113 if (Result == AR_Available) {
114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
116 Result = D->getAvailability(Message);
123 // Forward class declarations get their attributes from their definition.
124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125 if (IDecl->getDefinition()) {
126 D = IDecl->getDefinition();
127 Result = D->getAvailability(Message);
131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132 if (Result == AR_Available) {
133 const DeclContext *DC = ECD->getDeclContext();
134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135 Result = TheEnumDecl->getAvailability(Message);
138 if (Result == AR_NotYetIntroduced) {
139 // Don't do this for enums, they can't be redeclared.
140 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
143 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144 // Objective-C method declarations in categories are not modelled as
145 // redeclarations, so manually look for a redeclaration in a category
147 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
149 // In general, D will point to the most recent redeclaration. However,
150 // for `@class A;` decls, this isn't true -- manually go through the
151 // redecl chain in that case.
152 if (Warn && isa<ObjCInterfaceDecl>(D))
153 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154 Redecl = Redecl->getPreviousDecl())
155 if (!Redecl->hasAttr<AvailabilityAttr>() ||
156 Redecl->getAttr<AvailabilityAttr>()->isInherited())
159 return Warn ? AR_NotYetIntroduced : AR_Available;
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167 const ObjCInterfaceDecl *UnknownObjCClass,
168 bool ObjCPropertyAccess) {
170 // See if this declaration is unavailable, deprecated, or partial.
171 if (AvailabilityResult Result =
172 S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
174 if (Result == AR_NotYetIntroduced) {
175 if (S.getCurFunctionOrMethodDecl()) {
176 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
178 } else if (S.getCurBlock() || S.getCurLambda()) {
179 S.getCurFunction()->HasPotentialAvailabilityViolations = true;
184 const ObjCPropertyDecl *ObjCPDecl = nullptr;
185 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
186 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
187 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
188 if (PDeclResult == Result)
193 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
194 ObjCPDecl, ObjCPropertyAccess);
198 /// \brief Emit a note explaining that this function is deleted.
199 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
200 assert(Decl->isDeleted());
202 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
204 if (Method && Method->isDeleted() && Method->isDefaulted()) {
205 // If the method was explicitly defaulted, point at that declaration.
206 if (!Method->isImplicit())
207 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
209 // Try to diagnose why this special member function was implicitly
210 // deleted. This might fail, if that reason no longer applies.
211 CXXSpecialMember CSM = getSpecialMember(Method);
212 if (CSM != CXXInvalid)
213 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
218 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
219 if (Ctor && Ctor->isInheritingConstructor())
220 return NoteDeletedInheritingConstructor(Ctor);
222 Diag(Decl->getLocation(), diag::note_availability_specified_here)
226 /// \brief Determine whether a FunctionDecl was ever declared with an
227 /// explicit storage class.
228 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
229 for (auto I : D->redecls()) {
230 if (I->getStorageClass() != SC_None)
236 /// \brief Check whether we're in an extern inline function and referring to a
237 /// variable or function with internal linkage (C11 6.7.4p3).
239 /// This is only a warning because we used to silently accept this code, but
240 /// in many cases it will not behave correctly. This is not enabled in C++ mode
241 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
242 /// and so while there may still be user mistakes, most of the time we can't
243 /// prove that there are errors.
244 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
246 SourceLocation Loc) {
247 // This is disabled under C++; there are too many ways for this to fire in
248 // contexts where the warning is a false positive, or where it is technically
249 // correct but benign.
250 if (S.getLangOpts().CPlusPlus)
253 // Check if this is an inlined function or method.
254 FunctionDecl *Current = S.getCurFunctionDecl();
257 if (!Current->isInlined())
259 if (!Current->isExternallyVisible())
262 // Check if the decl has internal linkage.
263 if (D->getFormalLinkage() != InternalLinkage)
266 // Downgrade from ExtWarn to Extension if
267 // (1) the supposedly external inline function is in the main file,
268 // and probably won't be included anywhere else.
269 // (2) the thing we're referencing is a pure function.
270 // (3) the thing we're referencing is another inline function.
271 // This last can give us false negatives, but it's better than warning on
272 // wrappers for simple C library functions.
273 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
274 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
275 if (!DowngradeWarning && UsedFn)
276 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
278 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
279 : diag::ext_internal_in_extern_inline)
280 << /*IsVar=*/!UsedFn << D;
282 S.MaybeSuggestAddingStaticToDecl(Current);
284 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
288 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
289 const FunctionDecl *First = Cur->getFirstDecl();
291 // Suggest "static" on the function, if possible.
292 if (!hasAnyExplicitStorageClass(First)) {
293 SourceLocation DeclBegin = First->getSourceRange().getBegin();
294 Diag(DeclBegin, diag::note_convert_inline_to_static)
295 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
299 /// \brief Determine whether the use of this declaration is valid, and
300 /// emit any corresponding diagnostics.
302 /// This routine diagnoses various problems with referencing
303 /// declarations that can occur when using a declaration. For example,
304 /// it might warn if a deprecated or unavailable declaration is being
305 /// used, or produce an error (and return true) if a C++0x deleted
306 /// function is being used.
308 /// \returns true if there was an error (this declaration cannot be
309 /// referenced), false otherwise.
311 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
312 const ObjCInterfaceDecl *UnknownObjCClass,
313 bool ObjCPropertyAccess) {
314 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
315 // If there were any diagnostics suppressed by template argument deduction,
317 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
318 if (Pos != SuppressedDiagnostics.end()) {
319 for (const PartialDiagnosticAt &Suppressed : Pos->second)
320 Diag(Suppressed.first, Suppressed.second);
322 // Clear out the list of suppressed diagnostics, so that we don't emit
323 // them again for this specialization. However, we don't obsolete this
324 // entry from the table, because we want to avoid ever emitting these
325 // diagnostics again.
329 // C++ [basic.start.main]p3:
330 // The function 'main' shall not be used within a program.
331 if (cast<FunctionDecl>(D)->isMain())
332 Diag(Loc, diag::ext_main_used);
335 // See if this is an auto-typed variable whose initializer we are parsing.
336 if (ParsingInitForAutoVars.count(D)) {
337 if (isa<BindingDecl>(D)) {
338 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
341 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
342 << D->getDeclName() << cast<VarDecl>(D)->getType();
347 // See if this is a deleted function.
348 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
349 if (FD->isDeleted()) {
350 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
351 if (Ctor && Ctor->isInheritingConstructor())
352 Diag(Loc, diag::err_deleted_inherited_ctor_use)
354 << Ctor->getInheritedConstructor().getConstructor()->getParent();
356 Diag(Loc, diag::err_deleted_function_use);
357 NoteDeletedFunction(FD);
361 // If the function has a deduced return type, and we can't deduce it,
362 // then we can't use it either.
363 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
364 DeduceReturnType(FD, Loc))
367 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
370 if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
374 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
375 // Only the variables omp_in and omp_out are allowed in the combiner.
376 // Only the variables omp_priv and omp_orig are allowed in the
377 // initializer-clause.
378 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
379 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
381 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
382 << getCurFunction()->HasOMPDeclareReductionCombiner;
383 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
387 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
390 DiagnoseUnusedOfDecl(*this, D, Loc);
392 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
397 /// \brief Retrieve the message suffix that should be added to a
398 /// diagnostic complaining about the given function being deleted or
400 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
402 if (FD->getAvailability(&Message))
403 return ": " + Message;
405 return std::string();
408 /// DiagnoseSentinelCalls - This routine checks whether a call or
409 /// message-send is to a declaration with the sentinel attribute, and
410 /// if so, it checks that the requirements of the sentinel are
412 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
413 ArrayRef<Expr *> Args) {
414 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
418 // The number of formal parameters of the declaration.
419 unsigned numFormalParams;
421 // The kind of declaration. This is also an index into a %select in
423 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
425 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
426 numFormalParams = MD->param_size();
427 calleeType = CT_Method;
428 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
429 numFormalParams = FD->param_size();
430 calleeType = CT_Function;
431 } else if (isa<VarDecl>(D)) {
432 QualType type = cast<ValueDecl>(D)->getType();
433 const FunctionType *fn = nullptr;
434 if (const PointerType *ptr = type->getAs<PointerType>()) {
435 fn = ptr->getPointeeType()->getAs<FunctionType>();
437 calleeType = CT_Function;
438 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
439 fn = ptr->getPointeeType()->castAs<FunctionType>();
440 calleeType = CT_Block;
445 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
446 numFormalParams = proto->getNumParams();
454 // "nullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned nullPos = attr->getNullPos();
459 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
460 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
462 // The number of arguments which should follow the sentinel.
463 unsigned numArgsAfterSentinel = attr->getSentinel();
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
468 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
469 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
473 // Otherwise, find the sentinel expression.
474 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
475 if (!sentinelExpr) return;
476 if (sentinelExpr->isValueDependent()) return;
477 if (Context.isSentinelNullExpr(sentinelExpr)) return;
479 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
480 // or 'NULL' if those are actually defined in the context. Only use
481 // 'nil' for ObjC methods, where it's much more likely that the
482 // variadic arguments form a list of object pointers.
483 SourceLocation MissingNilLoc
484 = getLocForEndOfToken(sentinelExpr->getLocEnd());
485 std::string NullValue;
486 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
488 else if (getLangOpts().CPlusPlus11)
489 NullValue = "nullptr";
490 else if (PP.isMacroDefined("NULL"))
493 NullValue = "(void*) 0";
495 if (MissingNilLoc.isInvalid())
496 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
498 Diag(MissingNilLoc, diag::warn_missing_sentinel)
500 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
501 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
504 SourceRange Sema::getExprRange(Expr *E) const {
505 return E ? E->getSourceRange() : SourceRange();
508 //===----------------------------------------------------------------------===//
509 // Standard Promotions and Conversions
510 //===----------------------------------------------------------------------===//
512 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
513 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
514 // Handle any placeholder expressions which made it here.
515 if (E->getType()->isPlaceholderType()) {
516 ExprResult result = CheckPlaceholderExpr(E);
517 if (result.isInvalid()) return ExprError();
521 QualType Ty = E->getType();
522 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
524 if (Ty->isFunctionType()) {
525 // If we are here, we are not calling a function but taking
526 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
527 if (getLangOpts().OpenCL) {
529 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
533 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
534 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
535 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
538 E = ImpCastExprToType(E, Context.getPointerType(Ty),
539 CK_FunctionToPointerDecay).get();
540 } else if (Ty->isArrayType()) {
541 // In C90 mode, arrays only promote to pointers if the array expression is
542 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
543 // type 'array of type' is converted to an expression that has type 'pointer
544 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
545 // that has type 'array of type' ...". The relevant change is "an lvalue"
546 // (C90) to "an expression" (C99).
549 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
550 // T" can be converted to an rvalue of type "pointer to T".
552 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
553 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
554 CK_ArrayToPointerDecay).get();
559 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
560 // Check to see if we are dereferencing a null pointer. If so,
561 // and if not volatile-qualified, this is undefined behavior that the
562 // optimizer will delete, so warn about it. People sometimes try to use this
563 // to get a deterministic trap and are surprised by clang's behavior. This
564 // only handles the pattern "*null", which is a very syntactic check.
565 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
566 if (UO->getOpcode() == UO_Deref &&
567 UO->getSubExpr()->IgnoreParenCasts()->
568 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
569 !UO->getType().isVolatileQualified()) {
570 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
571 S.PDiag(diag::warn_indirection_through_null)
572 << UO->getSubExpr()->getSourceRange());
573 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
574 S.PDiag(diag::note_indirection_through_null));
578 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
579 SourceLocation AssignLoc,
581 const ObjCIvarDecl *IV = OIRE->getDecl();
585 DeclarationName MemberName = IV->getDeclName();
586 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
587 if (!Member || !Member->isStr("isa"))
590 const Expr *Base = OIRE->getBase();
591 QualType BaseType = Base->getType();
593 BaseType = BaseType->getPointeeType();
594 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
595 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
596 ObjCInterfaceDecl *ClassDeclared = nullptr;
597 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
598 if (!ClassDeclared->getSuperClass()
599 && (*ClassDeclared->ivar_begin()) == IV) {
601 NamedDecl *ObjectSetClass =
602 S.LookupSingleName(S.TUScope,
603 &S.Context.Idents.get("object_setClass"),
604 SourceLocation(), S.LookupOrdinaryName);
605 if (ObjectSetClass) {
606 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
607 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
608 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
609 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
611 FixItHint::CreateInsertion(RHSLocEnd, ")");
614 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
616 NamedDecl *ObjectGetClass =
617 S.LookupSingleName(S.TUScope,
618 &S.Context.Idents.get("object_getClass"),
619 SourceLocation(), S.LookupOrdinaryName);
621 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
622 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
623 FixItHint::CreateReplacement(
624 SourceRange(OIRE->getOpLoc(),
625 OIRE->getLocEnd()), ")");
627 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
629 S.Diag(IV->getLocation(), diag::note_ivar_decl);
634 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
635 // Handle any placeholder expressions which made it here.
636 if (E->getType()->isPlaceholderType()) {
637 ExprResult result = CheckPlaceholderExpr(E);
638 if (result.isInvalid()) return ExprError();
642 // C++ [conv.lval]p1:
643 // A glvalue of a non-function, non-array type T can be
644 // converted to a prvalue.
645 if (!E->isGLValue()) return E;
647 QualType T = E->getType();
648 assert(!T.isNull() && "r-value conversion on typeless expression?");
650 // We don't want to throw lvalue-to-rvalue casts on top of
651 // expressions of certain types in C++.
652 if (getLangOpts().CPlusPlus &&
653 (E->getType() == Context.OverloadTy ||
654 T->isDependentType() ||
658 // The C standard is actually really unclear on this point, and
659 // DR106 tells us what the result should be but not why. It's
660 // generally best to say that void types just doesn't undergo
661 // lvalue-to-rvalue at all. Note that expressions of unqualified
662 // 'void' type are never l-values, but qualified void can be.
666 // OpenCL usually rejects direct accesses to values of 'half' type.
667 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
669 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
674 CheckForNullPointerDereference(*this, E);
675 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
676 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
677 &Context.Idents.get("object_getClass"),
678 SourceLocation(), LookupOrdinaryName);
680 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
681 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
682 FixItHint::CreateReplacement(
683 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
685 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
687 else if (const ObjCIvarRefExpr *OIRE =
688 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
689 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
691 // C++ [conv.lval]p1:
692 // [...] If T is a non-class type, the type of the prvalue is the
693 // cv-unqualified version of T. Otherwise, the type of the
697 // If the lvalue has qualified type, the value has the unqualified
698 // version of the type of the lvalue; otherwise, the value has the
699 // type of the lvalue.
700 if (T.hasQualifiers())
701 T = T.getUnqualifiedType();
703 // Under the MS ABI, lock down the inheritance model now.
704 if (T->isMemberPointerType() &&
705 Context.getTargetInfo().getCXXABI().isMicrosoft())
706 (void)isCompleteType(E->getExprLoc(), T);
708 UpdateMarkingForLValueToRValue(E);
710 // Loading a __weak object implicitly retains the value, so we need a cleanup to
712 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713 Cleanup.setExprNeedsCleanups(true);
715 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
719 // ... if the lvalue has atomic type, the value has the non-atomic version
720 // of the type of the lvalue ...
721 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
722 T = Atomic->getValueType().getUnqualifiedType();
723 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
730 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
731 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
734 Res = DefaultLvalueConversion(Res.get());
740 /// CallExprUnaryConversions - a special case of an unary conversion
741 /// performed on a function designator of a call expression.
742 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
743 QualType Ty = E->getType();
745 // Only do implicit cast for a function type, but not for a pointer
747 if (Ty->isFunctionType()) {
748 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
749 CK_FunctionToPointerDecay).get();
753 Res = DefaultLvalueConversion(Res.get());
759 /// UsualUnaryConversions - Performs various conversions that are common to most
760 /// operators (C99 6.3). The conversions of array and function types are
761 /// sometimes suppressed. For example, the array->pointer conversion doesn't
762 /// apply if the array is an argument to the sizeof or address (&) operators.
763 /// In these instances, this routine should *not* be called.
764 ExprResult Sema::UsualUnaryConversions(Expr *E) {
765 // First, convert to an r-value.
766 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
771 QualType Ty = E->getType();
772 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
774 // Half FP have to be promoted to float unless it is natively supported
775 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
776 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
778 // Try to perform integral promotions if the object has a theoretically
780 if (Ty->isIntegralOrUnscopedEnumerationType()) {
783 // The following may be used in an expression wherever an int or
784 // unsigned int may be used:
785 // - an object or expression with an integer type whose integer
786 // conversion rank is less than or equal to the rank of int
788 // - A bit-field of type _Bool, int, signed int, or unsigned int.
790 // If an int can represent all values of the original type, the
791 // value is converted to an int; otherwise, it is converted to an
792 // unsigned int. These are called the integer promotions. All
793 // other types are unchanged by the integer promotions.
795 QualType PTy = Context.isPromotableBitField(E);
797 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
800 if (Ty->isPromotableIntegerType()) {
801 QualType PT = Context.getPromotedIntegerType(Ty);
802 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
809 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
810 /// do not have a prototype. Arguments that have type float or __fp16
811 /// are promoted to double. All other argument types are converted by
812 /// UsualUnaryConversions().
813 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
814 QualType Ty = E->getType();
815 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
817 ExprResult Res = UsualUnaryConversions(E);
822 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
824 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
825 if (BTy && (BTy->getKind() == BuiltinType::Half ||
826 BTy->getKind() == BuiltinType::Float)) {
827 if (getLangOpts().OpenCL &&
828 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
829 if (BTy->getKind() == BuiltinType::Half) {
830 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
833 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
837 // C++ performs lvalue-to-rvalue conversion as a default argument
838 // promotion, even on class types, but note:
839 // C++11 [conv.lval]p2:
840 // When an lvalue-to-rvalue conversion occurs in an unevaluated
841 // operand or a subexpression thereof the value contained in the
842 // referenced object is not accessed. Otherwise, if the glvalue
843 // has a class type, the conversion copy-initializes a temporary
844 // of type T from the glvalue and the result of the conversion
845 // is a prvalue for the temporary.
846 // FIXME: add some way to gate this entire thing for correctness in
847 // potentially potentially evaluated contexts.
848 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
849 ExprResult Temp = PerformCopyInitialization(
850 InitializedEntity::InitializeTemporary(E->getType()),
852 if (Temp.isInvalid())
860 /// Determine the degree of POD-ness for an expression.
861 /// Incomplete types are considered POD, since this check can be performed
862 /// when we're in an unevaluated context.
863 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
864 if (Ty->isIncompleteType()) {
865 // C++11 [expr.call]p7:
866 // After these conversions, if the argument does not have arithmetic,
867 // enumeration, pointer, pointer to member, or class type, the program
870 // Since we've already performed array-to-pointer and function-to-pointer
871 // decay, the only such type in C++ is cv void. This also handles
872 // initializer lists as variadic arguments.
873 if (Ty->isVoidType())
876 if (Ty->isObjCObjectType())
881 if (Ty.isCXX98PODType(Context))
884 // C++11 [expr.call]p7:
885 // Passing a potentially-evaluated argument of class type (Clause 9)
886 // having a non-trivial copy constructor, a non-trivial move constructor,
887 // or a non-trivial destructor, with no corresponding parameter,
888 // is conditionally-supported with implementation-defined semantics.
889 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
890 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
891 if (!Record->hasNonTrivialCopyConstructor() &&
892 !Record->hasNonTrivialMoveConstructor() &&
893 !Record->hasNonTrivialDestructor())
894 return VAK_ValidInCXX11;
896 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
899 if (Ty->isObjCObjectType())
902 if (getLangOpts().MSVCCompat)
903 return VAK_MSVCUndefined;
905 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
906 // permitted to reject them. We should consider doing so.
907 return VAK_Undefined;
910 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
911 // Don't allow one to pass an Objective-C interface to a vararg.
912 const QualType &Ty = E->getType();
913 VarArgKind VAK = isValidVarArgType(Ty);
915 // Complain about passing non-POD types through varargs.
917 case VAK_ValidInCXX11:
919 E->getLocStart(), nullptr,
920 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
924 if (Ty->isRecordType()) {
925 // This is unlikely to be what the user intended. If the class has a
926 // 'c_str' member function, the user probably meant to call that.
927 DiagRuntimeBehavior(E->getLocStart(), nullptr,
928 PDiag(diag::warn_pass_class_arg_to_vararg)
929 << Ty << CT << hasCStrMethod(E) << ".c_str()");
934 case VAK_MSVCUndefined:
936 E->getLocStart(), nullptr,
937 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
938 << getLangOpts().CPlusPlus11 << Ty << CT);
942 if (Ty->isObjCObjectType())
944 E->getLocStart(), nullptr,
945 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
948 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
949 << isa<InitListExpr>(E) << Ty << CT;
954 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
955 /// will create a trap if the resulting type is not a POD type.
956 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
957 FunctionDecl *FDecl) {
958 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
959 // Strip the unbridged-cast placeholder expression off, if applicable.
960 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
961 (CT == VariadicMethod ||
962 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
963 E = stripARCUnbridgedCast(E);
965 // Otherwise, do normal placeholder checking.
967 ExprResult ExprRes = CheckPlaceholderExpr(E);
968 if (ExprRes.isInvalid())
974 ExprResult ExprRes = DefaultArgumentPromotion(E);
975 if (ExprRes.isInvalid())
979 // Diagnostics regarding non-POD argument types are
980 // emitted along with format string checking in Sema::CheckFunctionCall().
981 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
982 // Turn this into a trap.
984 SourceLocation TemplateKWLoc;
986 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
988 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
990 if (TrapFn.isInvalid())
993 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
994 E->getLocStart(), None,
996 if (Call.isInvalid())
999 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
1001 if (Comma.isInvalid())
1006 if (!getLangOpts().CPlusPlus &&
1007 RequireCompleteType(E->getExprLoc(), E->getType(),
1008 diag::err_call_incomplete_argument))
1014 /// \brief Converts an integer to complex float type. Helper function of
1015 /// UsualArithmeticConversions()
1017 /// \return false if the integer expression is an integer type and is
1018 /// successfully converted to the complex type.
1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1020 ExprResult &ComplexExpr,
1024 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1025 if (SkipCast) return false;
1026 if (IntTy->isIntegerType()) {
1027 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1029 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1030 CK_FloatingRealToComplex);
1032 assert(IntTy->isComplexIntegerType());
1033 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1034 CK_IntegralComplexToFloatingComplex);
1039 /// \brief Handle arithmetic conversion with complex types. Helper function of
1040 /// UsualArithmeticConversions()
1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1042 ExprResult &RHS, QualType LHSType,
1044 bool IsCompAssign) {
1045 // if we have an integer operand, the result is the complex type.
1046 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1049 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1050 /*skipCast*/IsCompAssign))
1053 // This handles complex/complex, complex/float, or float/complex.
1054 // When both operands are complex, the shorter operand is converted to the
1055 // type of the longer, and that is the type of the result. This corresponds
1056 // to what is done when combining two real floating-point operands.
1057 // The fun begins when size promotion occur across type domains.
1058 // From H&S 6.3.4: When one operand is complex and the other is a real
1059 // floating-point type, the less precise type is converted, within it's
1060 // real or complex domain, to the precision of the other type. For example,
1061 // when combining a "long double" with a "double _Complex", the
1062 // "double _Complex" is promoted to "long double _Complex".
1064 // Compute the rank of the two types, regardless of whether they are complex.
1065 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1067 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1068 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1069 QualType LHSElementType =
1070 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1071 QualType RHSElementType =
1072 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1074 QualType ResultType = S.Context.getComplexType(LHSElementType);
1076 // Promote the precision of the LHS if not an assignment.
1077 ResultType = S.Context.getComplexType(RHSElementType);
1078 if (!IsCompAssign) {
1081 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1083 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1085 } else if (Order > 0) {
1086 // Promote the precision of the RHS.
1088 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1090 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1095 /// \brief Hande arithmetic conversion from integer to float. Helper function
1096 /// of UsualArithmeticConversions()
1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1098 ExprResult &IntExpr,
1099 QualType FloatTy, QualType IntTy,
1100 bool ConvertFloat, bool ConvertInt) {
1101 if (IntTy->isIntegerType()) {
1103 // Convert intExpr to the lhs floating point type.
1104 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1105 CK_IntegralToFloating);
1109 // Convert both sides to the appropriate complex float.
1110 assert(IntTy->isComplexIntegerType());
1111 QualType result = S.Context.getComplexType(FloatTy);
1113 // _Complex int -> _Complex float
1115 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1116 CK_IntegralComplexToFloatingComplex);
1118 // float -> _Complex float
1120 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1121 CK_FloatingRealToComplex);
1126 /// \brief Handle arithmethic conversion with floating point types. Helper
1127 /// function of UsualArithmeticConversions()
1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1129 ExprResult &RHS, QualType LHSType,
1130 QualType RHSType, bool IsCompAssign) {
1131 bool LHSFloat = LHSType->isRealFloatingType();
1132 bool RHSFloat = RHSType->isRealFloatingType();
1134 // If we have two real floating types, convert the smaller operand
1135 // to the bigger result.
1136 if (LHSFloat && RHSFloat) {
1137 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1139 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1143 assert(order < 0 && "illegal float comparison");
1145 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1150 // Half FP has to be promoted to float unless it is natively supported
1151 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1152 LHSType = S.Context.FloatTy;
1154 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1155 /*convertFloat=*/!IsCompAssign,
1156 /*convertInt=*/ true);
1159 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1160 /*convertInt=*/ true,
1161 /*convertFloat=*/!IsCompAssign);
1164 /// \brief Diagnose attempts to convert between __float128 and long double if
1165 /// there is no support for such conversion. Helper function of
1166 /// UsualArithmeticConversions().
1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1169 /* No issue converting if at least one of the types is not a floating point
1170 type or the two types have the same rank.
1172 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1173 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1176 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1177 "The remaining types must be floating point types.");
1179 auto *LHSComplex = LHSType->getAs<ComplexType>();
1180 auto *RHSComplex = RHSType->getAs<ComplexType>();
1182 QualType LHSElemType = LHSComplex ?
1183 LHSComplex->getElementType() : LHSType;
1184 QualType RHSElemType = RHSComplex ?
1185 RHSComplex->getElementType() : RHSType;
1187 // No issue if the two types have the same representation
1188 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1189 &S.Context.getFloatTypeSemantics(RHSElemType))
1192 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1193 RHSElemType == S.Context.LongDoubleTy);
1194 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1195 RHSElemType == S.Context.Float128Ty);
1197 /* We've handled the situation where __float128 and long double have the same
1198 representation. The only other allowable conversion is if long double is
1201 return Float128AndLongDouble &&
1202 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1203 &llvm::APFloat::IEEEdouble());
1206 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1209 /// These helper callbacks are placed in an anonymous namespace to
1210 /// permit their use as function template parameters.
1211 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1212 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1215 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1216 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1217 CK_IntegralComplexCast);
1221 /// \brief Handle integer arithmetic conversions. Helper function of
1222 /// UsualArithmeticConversions()
1223 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1224 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1225 ExprResult &RHS, QualType LHSType,
1226 QualType RHSType, bool IsCompAssign) {
1227 // The rules for this case are in C99 6.3.1.8
1228 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1229 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1230 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1231 if (LHSSigned == RHSSigned) {
1232 // Same signedness; use the higher-ranked type
1234 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1236 } else if (!IsCompAssign)
1237 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1239 } else if (order != (LHSSigned ? 1 : -1)) {
1240 // The unsigned type has greater than or equal rank to the
1241 // signed type, so use the unsigned type
1243 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1245 } else if (!IsCompAssign)
1246 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1248 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1249 // The two types are different widths; if we are here, that
1250 // means the signed type is larger than the unsigned type, so
1251 // use the signed type.
1253 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1255 } else if (!IsCompAssign)
1256 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1259 // The signed type is higher-ranked than the unsigned type,
1260 // but isn't actually any bigger (like unsigned int and long
1261 // on most 32-bit systems). Use the unsigned type corresponding
1262 // to the signed type.
1264 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1265 RHS = (*doRHSCast)(S, RHS.get(), result);
1267 LHS = (*doLHSCast)(S, LHS.get(), result);
1272 /// \brief Handle conversions with GCC complex int extension. Helper function
1273 /// of UsualArithmeticConversions()
1274 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1275 ExprResult &RHS, QualType LHSType,
1277 bool IsCompAssign) {
1278 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1279 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1281 if (LHSComplexInt && RHSComplexInt) {
1282 QualType LHSEltType = LHSComplexInt->getElementType();
1283 QualType RHSEltType = RHSComplexInt->getElementType();
1284 QualType ScalarType =
1285 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1286 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1288 return S.Context.getComplexType(ScalarType);
1291 if (LHSComplexInt) {
1292 QualType LHSEltType = LHSComplexInt->getElementType();
1293 QualType ScalarType =
1294 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1295 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1296 QualType ComplexType = S.Context.getComplexType(ScalarType);
1297 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1298 CK_IntegralRealToComplex);
1303 assert(RHSComplexInt);
1305 QualType RHSEltType = RHSComplexInt->getElementType();
1306 QualType ScalarType =
1307 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1308 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1309 QualType ComplexType = S.Context.getComplexType(ScalarType);
1312 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1313 CK_IntegralRealToComplex);
1317 /// UsualArithmeticConversions - Performs various conversions that are common to
1318 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1319 /// routine returns the first non-arithmetic type found. The client is
1320 /// responsible for emitting appropriate error diagnostics.
1321 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1322 bool IsCompAssign) {
1323 if (!IsCompAssign) {
1324 LHS = UsualUnaryConversions(LHS.get());
1325 if (LHS.isInvalid())
1329 RHS = UsualUnaryConversions(RHS.get());
1330 if (RHS.isInvalid())
1333 // For conversion purposes, we ignore any qualifiers.
1334 // For example, "const float" and "float" are equivalent.
1336 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1338 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1340 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1341 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1342 LHSType = AtomicLHS->getValueType();
1344 // If both types are identical, no conversion is needed.
1345 if (LHSType == RHSType)
1348 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1349 // The caller can deal with this (e.g. pointer + int).
1350 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1353 // Apply unary and bitfield promotions to the LHS's type.
1354 QualType LHSUnpromotedType = LHSType;
1355 if (LHSType->isPromotableIntegerType())
1356 LHSType = Context.getPromotedIntegerType(LHSType);
1357 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1358 if (!LHSBitfieldPromoteTy.isNull())
1359 LHSType = LHSBitfieldPromoteTy;
1360 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1361 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1363 // If both types are identical, no conversion is needed.
1364 if (LHSType == RHSType)
1367 // At this point, we have two different arithmetic types.
1369 // Diagnose attempts to convert between __float128 and long double where
1370 // such conversions currently can't be handled.
1371 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1374 // Handle complex types first (C99 6.3.1.8p1).
1375 if (LHSType->isComplexType() || RHSType->isComplexType())
1376 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1379 // Now handle "real" floating types (i.e. float, double, long double).
1380 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1381 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1384 // Handle GCC complex int extension.
1385 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1386 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1389 // Finally, we have two differing integer types.
1390 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1391 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1395 //===----------------------------------------------------------------------===//
1396 // Semantic Analysis for various Expression Types
1397 //===----------------------------------------------------------------------===//
1401 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1402 SourceLocation DefaultLoc,
1403 SourceLocation RParenLoc,
1404 Expr *ControllingExpr,
1405 ArrayRef<ParsedType> ArgTypes,
1406 ArrayRef<Expr *> ArgExprs) {
1407 unsigned NumAssocs = ArgTypes.size();
1408 assert(NumAssocs == ArgExprs.size());
1410 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1411 for (unsigned i = 0; i < NumAssocs; ++i) {
1413 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1418 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1420 llvm::makeArrayRef(Types, NumAssocs),
1427 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1428 SourceLocation DefaultLoc,
1429 SourceLocation RParenLoc,
1430 Expr *ControllingExpr,
1431 ArrayRef<TypeSourceInfo *> Types,
1432 ArrayRef<Expr *> Exprs) {
1433 unsigned NumAssocs = Types.size();
1434 assert(NumAssocs == Exprs.size());
1436 // Decay and strip qualifiers for the controlling expression type, and handle
1437 // placeholder type replacement. See committee discussion from WG14 DR423.
1439 EnterExpressionEvaluationContext Unevaluated(
1440 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1441 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1444 ControllingExpr = R.get();
1447 // The controlling expression is an unevaluated operand, so side effects are
1448 // likely unintended.
1449 if (!inTemplateInstantiation() &&
1450 ControllingExpr->HasSideEffects(Context, false))
1451 Diag(ControllingExpr->getExprLoc(),
1452 diag::warn_side_effects_unevaluated_context);
1454 bool TypeErrorFound = false,
1455 IsResultDependent = ControllingExpr->isTypeDependent(),
1456 ContainsUnexpandedParameterPack
1457 = ControllingExpr->containsUnexpandedParameterPack();
1459 for (unsigned i = 0; i < NumAssocs; ++i) {
1460 if (Exprs[i]->containsUnexpandedParameterPack())
1461 ContainsUnexpandedParameterPack = true;
1464 if (Types[i]->getType()->containsUnexpandedParameterPack())
1465 ContainsUnexpandedParameterPack = true;
1467 if (Types[i]->getType()->isDependentType()) {
1468 IsResultDependent = true;
1470 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1471 // complete object type other than a variably modified type."
1473 if (Types[i]->getType()->isIncompleteType())
1474 D = diag::err_assoc_type_incomplete;
1475 else if (!Types[i]->getType()->isObjectType())
1476 D = diag::err_assoc_type_nonobject;
1477 else if (Types[i]->getType()->isVariablyModifiedType())
1478 D = diag::err_assoc_type_variably_modified;
1481 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1482 << Types[i]->getTypeLoc().getSourceRange()
1483 << Types[i]->getType();
1484 TypeErrorFound = true;
1487 // C11 6.5.1.1p2 "No two generic associations in the same generic
1488 // selection shall specify compatible types."
1489 for (unsigned j = i+1; j < NumAssocs; ++j)
1490 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1491 Context.typesAreCompatible(Types[i]->getType(),
1492 Types[j]->getType())) {
1493 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1494 diag::err_assoc_compatible_types)
1495 << Types[j]->getTypeLoc().getSourceRange()
1496 << Types[j]->getType()
1497 << Types[i]->getType();
1498 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1499 diag::note_compat_assoc)
1500 << Types[i]->getTypeLoc().getSourceRange()
1501 << Types[i]->getType();
1502 TypeErrorFound = true;
1510 // If we determined that the generic selection is result-dependent, don't
1511 // try to compute the result expression.
1512 if (IsResultDependent)
1513 return new (Context) GenericSelectionExpr(
1514 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1515 ContainsUnexpandedParameterPack);
1517 SmallVector<unsigned, 1> CompatIndices;
1518 unsigned DefaultIndex = -1U;
1519 for (unsigned i = 0; i < NumAssocs; ++i) {
1522 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1523 Types[i]->getType()))
1524 CompatIndices.push_back(i);
1527 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1528 // type compatible with at most one of the types named in its generic
1529 // association list."
1530 if (CompatIndices.size() > 1) {
1531 // We strip parens here because the controlling expression is typically
1532 // parenthesized in macro definitions.
1533 ControllingExpr = ControllingExpr->IgnoreParens();
1534 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1535 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1536 << (unsigned) CompatIndices.size();
1537 for (unsigned I : CompatIndices) {
1538 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1539 diag::note_compat_assoc)
1540 << Types[I]->getTypeLoc().getSourceRange()
1541 << Types[I]->getType();
1546 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1547 // its controlling expression shall have type compatible with exactly one of
1548 // the types named in its generic association list."
1549 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1550 // We strip parens here because the controlling expression is typically
1551 // parenthesized in macro definitions.
1552 ControllingExpr = ControllingExpr->IgnoreParens();
1553 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1554 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1558 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1559 // type name that is compatible with the type of the controlling expression,
1560 // then the result expression of the generic selection is the expression
1561 // in that generic association. Otherwise, the result expression of the
1562 // generic selection is the expression in the default generic association."
1563 unsigned ResultIndex =
1564 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1566 return new (Context) GenericSelectionExpr(
1567 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1568 ContainsUnexpandedParameterPack, ResultIndex);
1571 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1572 /// location of the token and the offset of the ud-suffix within it.
1573 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1575 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1579 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1580 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1581 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1582 IdentifierInfo *UDSuffix,
1583 SourceLocation UDSuffixLoc,
1584 ArrayRef<Expr*> Args,
1585 SourceLocation LitEndLoc) {
1586 assert(Args.size() <= 2 && "too many arguments for literal operator");
1589 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1590 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1591 if (ArgTy[ArgIdx]->isArrayType())
1592 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1595 DeclarationName OpName =
1596 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1597 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1598 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1600 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1601 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1602 /*AllowRaw*/false, /*AllowTemplate*/false,
1603 /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1606 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1609 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1610 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1611 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1612 /// multiple tokens. However, the common case is that StringToks points to one
1616 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1617 assert(!StringToks.empty() && "Must have at least one string!");
1619 StringLiteralParser Literal(StringToks, PP);
1620 if (Literal.hadError)
1623 SmallVector<SourceLocation, 4> StringTokLocs;
1624 for (const Token &Tok : StringToks)
1625 StringTokLocs.push_back(Tok.getLocation());
1627 QualType CharTy = Context.CharTy;
1628 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1629 if (Literal.isWide()) {
1630 CharTy = Context.getWideCharType();
1631 Kind = StringLiteral::Wide;
1632 } else if (Literal.isUTF8()) {
1633 Kind = StringLiteral::UTF8;
1634 } else if (Literal.isUTF16()) {
1635 CharTy = Context.Char16Ty;
1636 Kind = StringLiteral::UTF16;
1637 } else if (Literal.isUTF32()) {
1638 CharTy = Context.Char32Ty;
1639 Kind = StringLiteral::UTF32;
1640 } else if (Literal.isPascal()) {
1641 CharTy = Context.UnsignedCharTy;
1644 QualType CharTyConst = CharTy;
1645 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1646 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1647 CharTyConst.addConst();
1649 // Get an array type for the string, according to C99 6.4.5. This includes
1650 // the nul terminator character as well as the string length for pascal
1652 QualType StrTy = Context.getConstantArrayType(CharTyConst,
1653 llvm::APInt(32, Literal.GetNumStringChars()+1),
1654 ArrayType::Normal, 0);
1656 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1657 if (getLangOpts().OpenCL) {
1658 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1661 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1662 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1663 Kind, Literal.Pascal, StrTy,
1665 StringTokLocs.size());
1666 if (Literal.getUDSuffix().empty())
1669 // We're building a user-defined literal.
1670 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1671 SourceLocation UDSuffixLoc =
1672 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1673 Literal.getUDSuffixOffset());
1675 // Make sure we're allowed user-defined literals here.
1677 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1679 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1680 // operator "" X (str, len)
1681 QualType SizeType = Context.getSizeType();
1683 DeclarationName OpName =
1684 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1685 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1686 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1688 QualType ArgTy[] = {
1689 Context.getArrayDecayedType(StrTy), SizeType
1692 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1693 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1694 /*AllowRaw*/false, /*AllowTemplate*/false,
1695 /*AllowStringTemplate*/true)) {
1698 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1699 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1701 Expr *Args[] = { Lit, LenArg };
1703 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1706 case LOLR_StringTemplate: {
1707 TemplateArgumentListInfo ExplicitArgs;
1709 unsigned CharBits = Context.getIntWidth(CharTy);
1710 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1711 llvm::APSInt Value(CharBits, CharIsUnsigned);
1713 TemplateArgument TypeArg(CharTy);
1714 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1715 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1717 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1718 Value = Lit->getCodeUnit(I);
1719 TemplateArgument Arg(Context, Value, CharTy);
1720 TemplateArgumentLocInfo ArgInfo;
1721 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1723 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1728 llvm_unreachable("unexpected literal operator lookup result");
1732 llvm_unreachable("unexpected literal operator lookup result");
1736 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1738 const CXXScopeSpec *SS) {
1739 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1740 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1743 /// BuildDeclRefExpr - Build an expression that references a
1744 /// declaration that does not require a closure capture.
1746 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1747 const DeclarationNameInfo &NameInfo,
1748 const CXXScopeSpec *SS, NamedDecl *FoundD,
1749 const TemplateArgumentListInfo *TemplateArgs) {
1750 bool RefersToCapturedVariable =
1752 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1755 if (isa<VarTemplateSpecializationDecl>(D)) {
1756 VarTemplateSpecializationDecl *VarSpec =
1757 cast<VarTemplateSpecializationDecl>(D);
1759 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1760 : NestedNameSpecifierLoc(),
1761 VarSpec->getTemplateKeywordLoc(), D,
1762 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1763 FoundD, TemplateArgs);
1765 assert(!TemplateArgs && "No template arguments for non-variable"
1766 " template specialization references");
1767 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1768 : NestedNameSpecifierLoc(),
1769 SourceLocation(), D, RefersToCapturedVariable,
1770 NameInfo, Ty, VK, FoundD);
1773 MarkDeclRefReferenced(E);
1775 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1776 Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1777 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1778 recordUseOfEvaluatedWeak(E);
1780 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1781 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1782 FD = IFD->getAnonField();
1784 UnusedPrivateFields.remove(FD);
1785 // Just in case we're building an illegal pointer-to-member.
1786 if (FD->isBitField())
1787 E->setObjectKind(OK_BitField);
1790 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1791 // designates a bit-field.
1792 if (auto *BD = dyn_cast<BindingDecl>(D))
1793 if (auto *BE = BD->getBinding())
1794 E->setObjectKind(BE->getObjectKind());
1799 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1800 /// possibly a list of template arguments.
1802 /// If this produces template arguments, it is permitted to call
1803 /// DecomposeTemplateName.
1805 /// This actually loses a lot of source location information for
1806 /// non-standard name kinds; we should consider preserving that in
1809 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1810 TemplateArgumentListInfo &Buffer,
1811 DeclarationNameInfo &NameInfo,
1812 const TemplateArgumentListInfo *&TemplateArgs) {
1813 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1814 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1815 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1817 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1818 Id.TemplateId->NumArgs);
1819 translateTemplateArguments(TemplateArgsPtr, Buffer);
1821 TemplateName TName = Id.TemplateId->Template.get();
1822 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1823 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1824 TemplateArgs = &Buffer;
1826 NameInfo = GetNameFromUnqualifiedId(Id);
1827 TemplateArgs = nullptr;
1831 static void emitEmptyLookupTypoDiagnostic(
1832 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1833 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1834 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1836 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1838 // Emit a special diagnostic for failed member lookups.
1839 // FIXME: computing the declaration context might fail here (?)
1841 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1844 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1848 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1849 bool DroppedSpecifier =
1850 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1851 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1852 ? diag::note_implicit_param_decl
1853 : diag::note_previous_decl;
1855 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1856 SemaRef.PDiag(NoteID));
1858 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1859 << Typo << Ctx << DroppedSpecifier
1861 SemaRef.PDiag(NoteID));
1864 /// Diagnose an empty lookup.
1866 /// \return false if new lookup candidates were found
1868 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1869 std::unique_ptr<CorrectionCandidateCallback> CCC,
1870 TemplateArgumentListInfo *ExplicitTemplateArgs,
1871 ArrayRef<Expr *> Args, TypoExpr **Out) {
1872 DeclarationName Name = R.getLookupName();
1874 unsigned diagnostic = diag::err_undeclared_var_use;
1875 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1876 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1877 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1878 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1879 diagnostic = diag::err_undeclared_use;
1880 diagnostic_suggest = diag::err_undeclared_use_suggest;
1883 // If the original lookup was an unqualified lookup, fake an
1884 // unqualified lookup. This is useful when (for example) the
1885 // original lookup would not have found something because it was a
1887 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1889 if (isa<CXXRecordDecl>(DC)) {
1890 LookupQualifiedName(R, DC);
1893 // Don't give errors about ambiguities in this lookup.
1894 R.suppressDiagnostics();
1896 // During a default argument instantiation the CurContext points
1897 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1898 // function parameter list, hence add an explicit check.
1899 bool isDefaultArgument =
1900 !CodeSynthesisContexts.empty() &&
1901 CodeSynthesisContexts.back().Kind ==
1902 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1903 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1904 bool isInstance = CurMethod &&
1905 CurMethod->isInstance() &&
1906 DC == CurMethod->getParent() && !isDefaultArgument;
1908 // Give a code modification hint to insert 'this->'.
1909 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1910 // Actually quite difficult!
1911 if (getLangOpts().MSVCCompat)
1912 diagnostic = diag::ext_found_via_dependent_bases_lookup;
1914 Diag(R.getNameLoc(), diagnostic) << Name
1915 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1916 CheckCXXThisCapture(R.getNameLoc());
1918 Diag(R.getNameLoc(), diagnostic) << Name;
1921 // Do we really want to note all of these?
1922 for (NamedDecl *D : R)
1923 Diag(D->getLocation(), diag::note_dependent_var_use);
1925 // Return true if we are inside a default argument instantiation
1926 // and the found name refers to an instance member function, otherwise
1927 // the function calling DiagnoseEmptyLookup will try to create an
1928 // implicit member call and this is wrong for default argument.
1929 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1930 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1934 // Tell the callee to try to recover.
1941 // In Microsoft mode, if we are performing lookup from within a friend
1942 // function definition declared at class scope then we must set
1943 // DC to the lexical parent to be able to search into the parent
1945 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1946 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1947 DC->getLexicalParent()->isRecord())
1948 DC = DC->getLexicalParent();
1950 DC = DC->getParent();
1953 // We didn't find anything, so try to correct for a typo.
1954 TypoCorrection Corrected;
1956 SourceLocation TypoLoc = R.getNameLoc();
1957 assert(!ExplicitTemplateArgs &&
1958 "Diagnosing an empty lookup with explicit template args!");
1959 *Out = CorrectTypoDelayed(
1960 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1961 [=](const TypoCorrection &TC) {
1962 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1963 diagnostic, diagnostic_suggest);
1965 nullptr, CTK_ErrorRecovery);
1968 } else if (S && (Corrected =
1969 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1970 &SS, std::move(CCC), CTK_ErrorRecovery))) {
1971 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1972 bool DroppedSpecifier =
1973 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1974 R.setLookupName(Corrected.getCorrection());
1976 bool AcceptableWithRecovery = false;
1977 bool AcceptableWithoutRecovery = false;
1978 NamedDecl *ND = Corrected.getFoundDecl();
1980 if (Corrected.isOverloaded()) {
1981 OverloadCandidateSet OCS(R.getNameLoc(),
1982 OverloadCandidateSet::CSK_Normal);
1983 OverloadCandidateSet::iterator Best;
1984 for (NamedDecl *CD : Corrected) {
1985 if (FunctionTemplateDecl *FTD =
1986 dyn_cast<FunctionTemplateDecl>(CD))
1987 AddTemplateOverloadCandidate(
1988 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1990 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1991 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1992 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1995 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1997 ND = Best->FoundDecl;
1998 Corrected.setCorrectionDecl(ND);
2001 // FIXME: Arbitrarily pick the first declaration for the note.
2002 Corrected.setCorrectionDecl(ND);
2007 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2008 CXXRecordDecl *Record = nullptr;
2009 if (Corrected.getCorrectionSpecifier()) {
2010 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2011 Record = Ty->getAsCXXRecordDecl();
2014 Record = cast<CXXRecordDecl>(
2015 ND->getDeclContext()->getRedeclContext());
2016 R.setNamingClass(Record);
2019 auto *UnderlyingND = ND->getUnderlyingDecl();
2020 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2021 isa<FunctionTemplateDecl>(UnderlyingND);
2022 // FIXME: If we ended up with a typo for a type name or
2023 // Objective-C class name, we're in trouble because the parser
2024 // is in the wrong place to recover. Suggest the typo
2025 // correction, but don't make it a fix-it since we're not going
2026 // to recover well anyway.
2027 AcceptableWithoutRecovery =
2028 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2030 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2031 // because we aren't able to recover.
2032 AcceptableWithoutRecovery = true;
2035 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2036 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2037 ? diag::note_implicit_param_decl
2038 : diag::note_previous_decl;
2040 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2041 PDiag(NoteID), AcceptableWithRecovery);
2043 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2044 << Name << computeDeclContext(SS, false)
2045 << DroppedSpecifier << SS.getRange(),
2046 PDiag(NoteID), AcceptableWithRecovery);
2048 // Tell the callee whether to try to recover.
2049 return !AcceptableWithRecovery;
2054 // Emit a special diagnostic for failed member lookups.
2055 // FIXME: computing the declaration context might fail here (?)
2056 if (!SS.isEmpty()) {
2057 Diag(R.getNameLoc(), diag::err_no_member)
2058 << Name << computeDeclContext(SS, false)
2063 // Give up, we can't recover.
2064 Diag(R.getNameLoc(), diagnostic) << Name;
2068 /// In Microsoft mode, if we are inside a template class whose parent class has
2069 /// dependent base classes, and we can't resolve an unqualified identifier, then
2070 /// assume the identifier is a member of a dependent base class. We can only
2071 /// recover successfully in static methods, instance methods, and other contexts
2072 /// where 'this' is available. This doesn't precisely match MSVC's
2073 /// instantiation model, but it's close enough.
2075 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2076 DeclarationNameInfo &NameInfo,
2077 SourceLocation TemplateKWLoc,
2078 const TemplateArgumentListInfo *TemplateArgs) {
2079 // Only try to recover from lookup into dependent bases in static methods or
2080 // contexts where 'this' is available.
2081 QualType ThisType = S.getCurrentThisType();
2082 const CXXRecordDecl *RD = nullptr;
2083 if (!ThisType.isNull())
2084 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2085 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2086 RD = MD->getParent();
2087 if (!RD || !RD->hasAnyDependentBases())
2090 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2091 // is available, suggest inserting 'this->' as a fixit.
2092 SourceLocation Loc = NameInfo.getLoc();
2093 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2094 DB << NameInfo.getName() << RD;
2096 if (!ThisType.isNull()) {
2097 DB << FixItHint::CreateInsertion(Loc, "this->");
2098 return CXXDependentScopeMemberExpr::Create(
2099 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2100 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2101 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2104 // Synthesize a fake NNS that points to the derived class. This will
2105 // perform name lookup during template instantiation.
2108 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2109 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2110 return DependentScopeDeclRefExpr::Create(
2111 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2116 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2117 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2118 bool HasTrailingLParen, bool IsAddressOfOperand,
2119 std::unique_ptr<CorrectionCandidateCallback> CCC,
2120 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2121 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2122 "cannot be direct & operand and have a trailing lparen");
2126 TemplateArgumentListInfo TemplateArgsBuffer;
2128 // Decompose the UnqualifiedId into the following data.
2129 DeclarationNameInfo NameInfo;
2130 const TemplateArgumentListInfo *TemplateArgs;
2131 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2133 DeclarationName Name = NameInfo.getName();
2134 IdentifierInfo *II = Name.getAsIdentifierInfo();
2135 SourceLocation NameLoc = NameInfo.getLoc();
2137 if (II && II->isEditorPlaceholder()) {
2138 // FIXME: When typed placeholders are supported we can create a typed
2139 // placeholder expression node.
2143 // C++ [temp.dep.expr]p3:
2144 // An id-expression is type-dependent if it contains:
2145 // -- an identifier that was declared with a dependent type,
2146 // (note: handled after lookup)
2147 // -- a template-id that is dependent,
2148 // (note: handled in BuildTemplateIdExpr)
2149 // -- a conversion-function-id that specifies a dependent type,
2150 // -- a nested-name-specifier that contains a class-name that
2151 // names a dependent type.
2152 // Determine whether this is a member of an unknown specialization;
2153 // we need to handle these differently.
2154 bool DependentID = false;
2155 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2156 Name.getCXXNameType()->isDependentType()) {
2158 } else if (SS.isSet()) {
2159 if (DeclContext *DC = computeDeclContext(SS, false)) {
2160 if (RequireCompleteDeclContext(SS, DC))
2168 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2169 IsAddressOfOperand, TemplateArgs);
2171 // Perform the required lookup.
2172 LookupResult R(*this, NameInfo,
2173 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2174 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2176 // Lookup the template name again to correctly establish the context in
2177 // which it was found. This is really unfortunate as we already did the
2178 // lookup to determine that it was a template name in the first place. If
2179 // this becomes a performance hit, we can work harder to preserve those
2180 // results until we get here but it's likely not worth it.
2181 bool MemberOfUnknownSpecialization;
2182 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2183 MemberOfUnknownSpecialization);
2185 if (MemberOfUnknownSpecialization ||
2186 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2187 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2188 IsAddressOfOperand, TemplateArgs);
2190 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2191 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2193 // If the result might be in a dependent base class, this is a dependent
2195 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2196 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2197 IsAddressOfOperand, TemplateArgs);
2199 // If this reference is in an Objective-C method, then we need to do
2200 // some special Objective-C lookup, too.
2201 if (IvarLookupFollowUp) {
2202 ExprResult E(LookupInObjCMethod(R, S, II, true));
2206 if (Expr *Ex = E.getAs<Expr>())
2211 if (R.isAmbiguous())
2214 // This could be an implicitly declared function reference (legal in C90,
2215 // extension in C99, forbidden in C++).
2216 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2217 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2218 if (D) R.addDecl(D);
2221 // Determine whether this name might be a candidate for
2222 // argument-dependent lookup.
2223 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2225 if (R.empty() && !ADL) {
2226 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2227 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2228 TemplateKWLoc, TemplateArgs))
2232 // Don't diagnose an empty lookup for inline assembly.
2233 if (IsInlineAsmIdentifier)
2236 // If this name wasn't predeclared and if this is not a function
2237 // call, diagnose the problem.
2238 TypoExpr *TE = nullptr;
2239 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2240 II, SS.isValid() ? SS.getScopeRep() : nullptr);
2241 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2242 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2243 "Typo correction callback misconfigured");
2245 // Make sure the callback knows what the typo being diagnosed is.
2246 CCC->setTypoName(II);
2248 CCC->setTypoNNS(SS.getScopeRep());
2250 if (DiagnoseEmptyLookup(S, SS, R,
2251 CCC ? std::move(CCC) : std::move(DefaultValidator),
2252 nullptr, None, &TE)) {
2253 if (TE && KeywordReplacement) {
2254 auto &State = getTypoExprState(TE);
2255 auto BestTC = State.Consumer->getNextCorrection();
2256 if (BestTC.isKeyword()) {
2257 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2258 if (State.DiagHandler)
2259 State.DiagHandler(BestTC);
2260 KeywordReplacement->startToken();
2261 KeywordReplacement->setKind(II->getTokenID());
2262 KeywordReplacement->setIdentifierInfo(II);
2263 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2264 // Clean up the state associated with the TypoExpr, since it has
2265 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2266 clearDelayedTypo(TE);
2267 // Signal that a correction to a keyword was performed by returning a
2268 // valid-but-null ExprResult.
2269 return (Expr*)nullptr;
2271 State.Consumer->resetCorrectionStream();
2273 return TE ? TE : ExprError();
2276 assert(!R.empty() &&
2277 "DiagnoseEmptyLookup returned false but added no results");
2279 // If we found an Objective-C instance variable, let
2280 // LookupInObjCMethod build the appropriate expression to
2281 // reference the ivar.
2282 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2284 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2285 // In a hopelessly buggy code, Objective-C instance variable
2286 // lookup fails and no expression will be built to reference it.
2287 if (!E.isInvalid() && !E.get())
2293 // This is guaranteed from this point on.
2294 assert(!R.empty() || ADL);
2296 // Check whether this might be a C++ implicit instance member access.
2297 // C++ [class.mfct.non-static]p3:
2298 // When an id-expression that is not part of a class member access
2299 // syntax and not used to form a pointer to member is used in the
2300 // body of a non-static member function of class X, if name lookup
2301 // resolves the name in the id-expression to a non-static non-type
2302 // member of some class C, the id-expression is transformed into a
2303 // class member access expression using (*this) as the
2304 // postfix-expression to the left of the . operator.
2306 // But we don't actually need to do this for '&' operands if R
2307 // resolved to a function or overloaded function set, because the
2308 // expression is ill-formed if it actually works out to be a
2309 // non-static member function:
2311 // C++ [expr.ref]p4:
2312 // Otherwise, if E1.E2 refers to a non-static member function. . .
2313 // [t]he expression can be used only as the left-hand operand of a
2314 // member function call.
2316 // There are other safeguards against such uses, but it's important
2317 // to get this right here so that we don't end up making a
2318 // spuriously dependent expression if we're inside a dependent
2320 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2321 bool MightBeImplicitMember;
2322 if (!IsAddressOfOperand)
2323 MightBeImplicitMember = true;
2324 else if (!SS.isEmpty())
2325 MightBeImplicitMember = false;
2326 else if (R.isOverloadedResult())
2327 MightBeImplicitMember = false;
2328 else if (R.isUnresolvableResult())
2329 MightBeImplicitMember = true;
2331 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2332 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2333 isa<MSPropertyDecl>(R.getFoundDecl());
2335 if (MightBeImplicitMember)
2336 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2337 R, TemplateArgs, S);
2340 if (TemplateArgs || TemplateKWLoc.isValid()) {
2342 // In C++1y, if this is a variable template id, then check it
2343 // in BuildTemplateIdExpr().
2344 // The single lookup result must be a variable template declaration.
2345 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2346 Id.TemplateId->Kind == TNK_Var_template) {
2347 assert(R.getAsSingle<VarTemplateDecl>() &&
2348 "There should only be one declaration found.");
2351 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2354 return BuildDeclarationNameExpr(SS, R, ADL);
2357 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2358 /// declaration name, generally during template instantiation.
2359 /// There's a large number of things which don't need to be done along
2361 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2362 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2363 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2364 DeclContext *DC = computeDeclContext(SS, false);
2366 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2367 NameInfo, /*TemplateArgs=*/nullptr);
2369 if (RequireCompleteDeclContext(SS, DC))
2372 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2373 LookupQualifiedName(R, DC);
2375 if (R.isAmbiguous())
2378 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2379 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2380 NameInfo, /*TemplateArgs=*/nullptr);
2383 Diag(NameInfo.getLoc(), diag::err_no_member)
2384 << NameInfo.getName() << DC << SS.getRange();
2388 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2389 // Diagnose a missing typename if this resolved unambiguously to a type in
2390 // a dependent context. If we can recover with a type, downgrade this to
2391 // a warning in Microsoft compatibility mode.
2392 unsigned DiagID = diag::err_typename_missing;
2393 if (RecoveryTSI && getLangOpts().MSVCCompat)
2394 DiagID = diag::ext_typename_missing;
2395 SourceLocation Loc = SS.getBeginLoc();
2396 auto D = Diag(Loc, DiagID);
2397 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2398 << SourceRange(Loc, NameInfo.getEndLoc());
2400 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2405 // Only issue the fixit if we're prepared to recover.
2406 D << FixItHint::CreateInsertion(Loc, "typename ");
2408 // Recover by pretending this was an elaborated type.
2409 QualType Ty = Context.getTypeDeclType(TD);
2411 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2413 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2414 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2415 QTL.setElaboratedKeywordLoc(SourceLocation());
2416 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2418 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2423 // Defend against this resolving to an implicit member access. We usually
2424 // won't get here if this might be a legitimate a class member (we end up in
2425 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2426 // a pointer-to-member or in an unevaluated context in C++11.
2427 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2428 return BuildPossibleImplicitMemberExpr(SS,
2429 /*TemplateKWLoc=*/SourceLocation(),
2430 R, /*TemplateArgs=*/nullptr, S);
2432 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2435 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2436 /// detected that we're currently inside an ObjC method. Perform some
2437 /// additional lookup.
2439 /// Ideally, most of this would be done by lookup, but there's
2440 /// actually quite a lot of extra work involved.
2442 /// Returns a null sentinel to indicate trivial success.
2444 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2445 IdentifierInfo *II, bool AllowBuiltinCreation) {
2446 SourceLocation Loc = Lookup.getNameLoc();
2447 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2449 // Check for error condition which is already reported.
2453 // There are two cases to handle here. 1) scoped lookup could have failed,
2454 // in which case we should look for an ivar. 2) scoped lookup could have
2455 // found a decl, but that decl is outside the current instance method (i.e.
2456 // a global variable). In these two cases, we do a lookup for an ivar with
2457 // this name, if the lookup sucedes, we replace it our current decl.
2459 // If we're in a class method, we don't normally want to look for
2460 // ivars. But if we don't find anything else, and there's an
2461 // ivar, that's an error.
2462 bool IsClassMethod = CurMethod->isClassMethod();
2466 LookForIvars = true;
2467 else if (IsClassMethod)
2468 LookForIvars = false;
2470 LookForIvars = (Lookup.isSingleResult() &&
2471 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2472 ObjCInterfaceDecl *IFace = nullptr;
2474 IFace = CurMethod->getClassInterface();
2475 ObjCInterfaceDecl *ClassDeclared;
2476 ObjCIvarDecl *IV = nullptr;
2477 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2478 // Diagnose using an ivar in a class method.
2480 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2481 << IV->getDeclName());
2483 // If we're referencing an invalid decl, just return this as a silent
2484 // error node. The error diagnostic was already emitted on the decl.
2485 if (IV->isInvalidDecl())
2488 // Check if referencing a field with __attribute__((deprecated)).
2489 if (DiagnoseUseOfDecl(IV, Loc))
2492 // Diagnose the use of an ivar outside of the declaring class.
2493 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2494 !declaresSameEntity(ClassDeclared, IFace) &&
2495 !getLangOpts().DebuggerSupport)
2496 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2498 // FIXME: This should use a new expr for a direct reference, don't
2499 // turn this into Self->ivar, just return a BareIVarExpr or something.
2500 IdentifierInfo &II = Context.Idents.get("self");
2501 UnqualifiedId SelfName;
2502 SelfName.setIdentifier(&II, SourceLocation());
2503 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2504 CXXScopeSpec SelfScopeSpec;
2505 SourceLocation TemplateKWLoc;
2506 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2507 SelfName, false, false);
2508 if (SelfExpr.isInvalid())
2511 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2512 if (SelfExpr.isInvalid())
2515 MarkAnyDeclReferenced(Loc, IV, true);
2517 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2518 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2519 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2520 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2522 ObjCIvarRefExpr *Result = new (Context)
2523 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2524 IV->getLocation(), SelfExpr.get(), true, true);
2526 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2527 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2528 recordUseOfEvaluatedWeak(Result);
2530 if (getLangOpts().ObjCAutoRefCount) {
2531 if (CurContext->isClosure())
2532 Diag(Loc, diag::warn_implicitly_retains_self)
2533 << FixItHint::CreateInsertion(Loc, "self->");
2538 } else if (CurMethod->isInstanceMethod()) {
2539 // We should warn if a local variable hides an ivar.
2540 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2541 ObjCInterfaceDecl *ClassDeclared;
2542 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2543 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2544 declaresSameEntity(IFace, ClassDeclared))
2545 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2548 } else if (Lookup.isSingleResult() &&
2549 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2550 // If accessing a stand-alone ivar in a class method, this is an error.
2551 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2552 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2553 << IV->getDeclName());
2556 if (Lookup.empty() && II && AllowBuiltinCreation) {
2557 // FIXME. Consolidate this with similar code in LookupName.
2558 if (unsigned BuiltinID = II->getBuiltinID()) {
2559 if (!(getLangOpts().CPlusPlus &&
2560 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2561 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2562 S, Lookup.isForRedeclaration(),
2563 Lookup.getNameLoc());
2564 if (D) Lookup.addDecl(D);
2568 // Sentinel value saying that we didn't do anything special.
2569 return ExprResult((Expr *)nullptr);
2572 /// \brief Cast a base object to a member's actual type.
2574 /// Logically this happens in three phases:
2576 /// * First we cast from the base type to the naming class.
2577 /// The naming class is the class into which we were looking
2578 /// when we found the member; it's the qualifier type if a
2579 /// qualifier was provided, and otherwise it's the base type.
2581 /// * Next we cast from the naming class to the declaring class.
2582 /// If the member we found was brought into a class's scope by
2583 /// a using declaration, this is that class; otherwise it's
2584 /// the class declaring the member.
2586 /// * Finally we cast from the declaring class to the "true"
2587 /// declaring class of the member. This conversion does not
2588 /// obey access control.
2590 Sema::PerformObjectMemberConversion(Expr *From,
2591 NestedNameSpecifier *Qualifier,
2592 NamedDecl *FoundDecl,
2593 NamedDecl *Member) {
2594 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2598 QualType DestRecordType;
2600 QualType FromRecordType;
2601 QualType FromType = From->getType();
2602 bool PointerConversions = false;
2603 if (isa<FieldDecl>(Member)) {
2604 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2606 if (FromType->getAs<PointerType>()) {
2607 DestType = Context.getPointerType(DestRecordType);
2608 FromRecordType = FromType->getPointeeType();
2609 PointerConversions = true;
2611 DestType = DestRecordType;
2612 FromRecordType = FromType;
2614 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2615 if (Method->isStatic())
2618 DestType = Method->getThisType(Context);
2619 DestRecordType = DestType->getPointeeType();
2621 if (FromType->getAs<PointerType>()) {
2622 FromRecordType = FromType->getPointeeType();
2623 PointerConversions = true;
2625 FromRecordType = FromType;
2626 DestType = DestRecordType;
2629 // No conversion necessary.
2633 if (DestType->isDependentType() || FromType->isDependentType())
2636 // If the unqualified types are the same, no conversion is necessary.
2637 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2640 SourceRange FromRange = From->getSourceRange();
2641 SourceLocation FromLoc = FromRange.getBegin();
2643 ExprValueKind VK = From->getValueKind();
2645 // C++ [class.member.lookup]p8:
2646 // [...] Ambiguities can often be resolved by qualifying a name with its
2649 // If the member was a qualified name and the qualified referred to a
2650 // specific base subobject type, we'll cast to that intermediate type
2651 // first and then to the object in which the member is declared. That allows
2652 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2654 // class Base { public: int x; };
2655 // class Derived1 : public Base { };
2656 // class Derived2 : public Base { };
2657 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2659 // void VeryDerived::f() {
2660 // x = 17; // error: ambiguous base subobjects
2661 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2663 if (Qualifier && Qualifier->getAsType()) {
2664 QualType QType = QualType(Qualifier->getAsType(), 0);
2665 assert(QType->isRecordType() && "lookup done with non-record type");
2667 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2669 // In C++98, the qualifier type doesn't actually have to be a base
2670 // type of the object type, in which case we just ignore it.
2671 // Otherwise build the appropriate casts.
2672 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2673 CXXCastPath BasePath;
2674 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2675 FromLoc, FromRange, &BasePath))
2678 if (PointerConversions)
2679 QType = Context.getPointerType(QType);
2680 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2681 VK, &BasePath).get();
2684 FromRecordType = QRecordType;
2686 // If the qualifier type was the same as the destination type,
2688 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2693 bool IgnoreAccess = false;
2695 // If we actually found the member through a using declaration, cast
2696 // down to the using declaration's type.
2698 // Pointer equality is fine here because only one declaration of a
2699 // class ever has member declarations.
2700 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2701 assert(isa<UsingShadowDecl>(FoundDecl));
2702 QualType URecordType = Context.getTypeDeclType(
2703 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2705 // We only need to do this if the naming-class to declaring-class
2706 // conversion is non-trivial.
2707 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2708 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2709 CXXCastPath BasePath;
2710 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2711 FromLoc, FromRange, &BasePath))
2714 QualType UType = URecordType;
2715 if (PointerConversions)
2716 UType = Context.getPointerType(UType);
2717 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2718 VK, &BasePath).get();
2720 FromRecordType = URecordType;
2723 // We don't do access control for the conversion from the
2724 // declaring class to the true declaring class.
2725 IgnoreAccess = true;
2728 CXXCastPath BasePath;
2729 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2730 FromLoc, FromRange, &BasePath,
2734 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2738 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2739 const LookupResult &R,
2740 bool HasTrailingLParen) {
2741 // Only when used directly as the postfix-expression of a call.
2742 if (!HasTrailingLParen)
2745 // Never if a scope specifier was provided.
2749 // Only in C++ or ObjC++.
2750 if (!getLangOpts().CPlusPlus)
2753 // Turn off ADL when we find certain kinds of declarations during
2755 for (NamedDecl *D : R) {
2756 // C++0x [basic.lookup.argdep]p3:
2757 // -- a declaration of a class member
2758 // Since using decls preserve this property, we check this on the
2760 if (D->isCXXClassMember())
2763 // C++0x [basic.lookup.argdep]p3:
2764 // -- a block-scope function declaration that is not a
2765 // using-declaration
2766 // NOTE: we also trigger this for function templates (in fact, we
2767 // don't check the decl type at all, since all other decl types
2768 // turn off ADL anyway).
2769 if (isa<UsingShadowDecl>(D))
2770 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2771 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2774 // C++0x [basic.lookup.argdep]p3:
2775 // -- a declaration that is neither a function or a function
2777 // And also for builtin functions.
2778 if (isa<FunctionDecl>(D)) {
2779 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2781 // But also builtin functions.
2782 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2784 } else if (!isa<FunctionTemplateDecl>(D))
2792 /// Diagnoses obvious problems with the use of the given declaration
2793 /// as an expression. This is only actually called for lookups that
2794 /// were not overloaded, and it doesn't promise that the declaration
2795 /// will in fact be used.
2796 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2797 if (D->isInvalidDecl())
2800 if (isa<TypedefNameDecl>(D)) {
2801 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2805 if (isa<ObjCInterfaceDecl>(D)) {
2806 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2810 if (isa<NamespaceDecl>(D)) {
2811 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2818 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2819 LookupResult &R, bool NeedsADL,
2820 bool AcceptInvalidDecl) {
2821 // If this is a single, fully-resolved result and we don't need ADL,
2822 // just build an ordinary singleton decl ref.
2823 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2824 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2825 R.getRepresentativeDecl(), nullptr,
2828 // We only need to check the declaration if there's exactly one
2829 // result, because in the overloaded case the results can only be
2830 // functions and function templates.
2831 if (R.isSingleResult() &&
2832 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2835 // Otherwise, just build an unresolved lookup expression. Suppress
2836 // any lookup-related diagnostics; we'll hash these out later, when
2837 // we've picked a target.
2838 R.suppressDiagnostics();
2840 UnresolvedLookupExpr *ULE
2841 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2842 SS.getWithLocInContext(Context),
2843 R.getLookupNameInfo(),
2844 NeedsADL, R.isOverloadedResult(),
2845 R.begin(), R.end());
2851 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2852 ValueDecl *var, DeclContext *DC);
2854 /// \brief Complete semantic analysis for a reference to the given declaration.
2855 ExprResult Sema::BuildDeclarationNameExpr(
2856 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2857 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2858 bool AcceptInvalidDecl) {
2859 assert(D && "Cannot refer to a NULL declaration");
2860 assert(!isa<FunctionTemplateDecl>(D) &&
2861 "Cannot refer unambiguously to a function template");
2863 SourceLocation Loc = NameInfo.getLoc();
2864 if (CheckDeclInExpr(*this, Loc, D))
2867 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2868 // Specifically diagnose references to class templates that are missing
2869 // a template argument list.
2870 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2871 << Template << SS.getRange();
2872 Diag(Template->getLocation(), diag::note_template_decl_here);
2876 // Make sure that we're referring to a value.
2877 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2879 Diag(Loc, diag::err_ref_non_value)
2880 << D << SS.getRange();
2881 Diag(D->getLocation(), diag::note_declared_at);
2885 // Check whether this declaration can be used. Note that we suppress
2886 // this check when we're going to perform argument-dependent lookup
2887 // on this function name, because this might not be the function
2888 // that overload resolution actually selects.
2889 if (DiagnoseUseOfDecl(VD, Loc))
2892 // Only create DeclRefExpr's for valid Decl's.
2893 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2896 // Handle members of anonymous structs and unions. If we got here,
2897 // and the reference is to a class member indirect field, then this
2898 // must be the subject of a pointer-to-member expression.
2899 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2900 if (!indirectField->isCXXClassMember())
2901 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2905 QualType type = VD->getType();
2906 if (auto *FPT = type->getAs<FunctionProtoType>()) {
2907 // C++ [except.spec]p17:
2908 // An exception-specification is considered to be needed when:
2909 // - in an expression, the function is the unique lookup result or
2910 // the selected member of a set of overloaded functions.
2911 ResolveExceptionSpec(Loc, FPT);
2912 type = VD->getType();
2914 ExprValueKind valueKind = VK_RValue;
2916 switch (D->getKind()) {
2917 // Ignore all the non-ValueDecl kinds.
2918 #define ABSTRACT_DECL(kind)
2919 #define VALUE(type, base)
2920 #define DECL(type, base) \
2922 #include "clang/AST/DeclNodes.inc"
2923 llvm_unreachable("invalid value decl kind");
2925 // These shouldn't make it here.
2926 case Decl::ObjCAtDefsField:
2927 case Decl::ObjCIvar:
2928 llvm_unreachable("forming non-member reference to ivar?");
2930 // Enum constants are always r-values and never references.
2931 // Unresolved using declarations are dependent.
2932 case Decl::EnumConstant:
2933 case Decl::UnresolvedUsingValue:
2934 case Decl::OMPDeclareReduction:
2935 valueKind = VK_RValue;
2938 // Fields and indirect fields that got here must be for
2939 // pointer-to-member expressions; we just call them l-values for
2940 // internal consistency, because this subexpression doesn't really
2941 // exist in the high-level semantics.
2943 case Decl::IndirectField:
2944 assert(getLangOpts().CPlusPlus &&
2945 "building reference to field in C?");
2947 // These can't have reference type in well-formed programs, but
2948 // for internal consistency we do this anyway.
2949 type = type.getNonReferenceType();
2950 valueKind = VK_LValue;
2953 // Non-type template parameters are either l-values or r-values
2954 // depending on the type.
2955 case Decl::NonTypeTemplateParm: {
2956 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2957 type = reftype->getPointeeType();
2958 valueKind = VK_LValue; // even if the parameter is an r-value reference
2962 // For non-references, we need to strip qualifiers just in case
2963 // the template parameter was declared as 'const int' or whatever.
2964 valueKind = VK_RValue;
2965 type = type.getUnqualifiedType();
2970 case Decl::VarTemplateSpecialization:
2971 case Decl::VarTemplatePartialSpecialization:
2972 case Decl::Decomposition:
2973 case Decl::OMPCapturedExpr:
2974 // In C, "extern void blah;" is valid and is an r-value.
2975 if (!getLangOpts().CPlusPlus &&
2976 !type.hasQualifiers() &&
2977 type->isVoidType()) {
2978 valueKind = VK_RValue;
2983 case Decl::ImplicitParam:
2984 case Decl::ParmVar: {
2985 // These are always l-values.
2986 valueKind = VK_LValue;
2987 type = type.getNonReferenceType();
2989 // FIXME: Does the addition of const really only apply in
2990 // potentially-evaluated contexts? Since the variable isn't actually
2991 // captured in an unevaluated context, it seems that the answer is no.
2992 if (!isUnevaluatedContext()) {
2993 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2994 if (!CapturedType.isNull())
2995 type = CapturedType;
3001 case Decl::Binding: {
3002 // These are always lvalues.
3003 valueKind = VK_LValue;
3004 type = type.getNonReferenceType();
3005 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3006 // decides how that's supposed to work.
3007 auto *BD = cast<BindingDecl>(VD);
3008 if (BD->getDeclContext()->isFunctionOrMethod() &&
3009 BD->getDeclContext() != CurContext)
3010 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3014 case Decl::Function: {
3015 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3016 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3017 type = Context.BuiltinFnTy;
3018 valueKind = VK_RValue;
3023 const FunctionType *fty = type->castAs<FunctionType>();
3025 // If we're referring to a function with an __unknown_anytype
3026 // result type, make the entire expression __unknown_anytype.
3027 if (fty->getReturnType() == Context.UnknownAnyTy) {
3028 type = Context.UnknownAnyTy;
3029 valueKind = VK_RValue;
3033 // Functions are l-values in C++.
3034 if (getLangOpts().CPlusPlus) {
3035 valueKind = VK_LValue;
3039 // C99 DR 316 says that, if a function type comes from a
3040 // function definition (without a prototype), that type is only
3041 // used for checking compatibility. Therefore, when referencing
3042 // the function, we pretend that we don't have the full function
3044 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3045 isa<FunctionProtoType>(fty))
3046 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3049 // Functions are r-values in C.
3050 valueKind = VK_RValue;
3054 case Decl::CXXDeductionGuide:
3055 llvm_unreachable("building reference to deduction guide");
3057 case Decl::MSProperty:
3058 valueKind = VK_LValue;
3061 case Decl::CXXMethod:
3062 // If we're referring to a method with an __unknown_anytype
3063 // result type, make the entire expression __unknown_anytype.
3064 // This should only be possible with a type written directly.
3065 if (const FunctionProtoType *proto
3066 = dyn_cast<FunctionProtoType>(VD->getType()))
3067 if (proto->getReturnType() == Context.UnknownAnyTy) {
3068 type = Context.UnknownAnyTy;
3069 valueKind = VK_RValue;
3073 // C++ methods are l-values if static, r-values if non-static.
3074 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3075 valueKind = VK_LValue;
3080 case Decl::CXXConversion:
3081 case Decl::CXXDestructor:
3082 case Decl::CXXConstructor:
3083 valueKind = VK_RValue;
3087 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3092 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3093 SmallString<32> &Target) {
3094 Target.resize(CharByteWidth * (Source.size() + 1));
3095 char *ResultPtr = &Target[0];
3096 const llvm::UTF8 *ErrorPtr;
3098 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3101 Target.resize(ResultPtr - &Target[0]);
3104 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3105 PredefinedExpr::IdentType IT) {
3106 // Pick the current block, lambda, captured statement or function.
3107 Decl *currentDecl = nullptr;
3108 if (const BlockScopeInfo *BSI = getCurBlock())
3109 currentDecl = BSI->TheDecl;
3110 else if (const LambdaScopeInfo *LSI = getCurLambda())
3111 currentDecl = LSI->CallOperator;
3112 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3113 currentDecl = CSI->TheCapturedDecl;
3115 currentDecl = getCurFunctionOrMethodDecl();
3118 Diag(Loc, diag::ext_predef_outside_function);
3119 currentDecl = Context.getTranslationUnitDecl();
3123 StringLiteral *SL = nullptr;
3124 if (cast<DeclContext>(currentDecl)->isDependentContext())
3125 ResTy = Context.DependentTy;
3127 // Pre-defined identifiers are of type char[x], where x is the length of
3129 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3130 unsigned Length = Str.length();
3132 llvm::APInt LengthI(32, Length + 1);
3133 if (IT == PredefinedExpr::LFunction) {
3134 ResTy = Context.WideCharTy.withConst();
3135 SmallString<32> RawChars;
3136 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3138 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3139 /*IndexTypeQuals*/ 0);
3140 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3141 /*Pascal*/ false, ResTy, Loc);
3143 ResTy = Context.CharTy.withConst();
3144 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3145 /*IndexTypeQuals*/ 0);
3146 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3147 /*Pascal*/ false, ResTy, Loc);
3151 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3154 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3155 PredefinedExpr::IdentType IT;
3158 default: llvm_unreachable("Unknown simple primary expr!");
3159 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3160 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3161 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3162 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3163 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3164 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3167 return BuildPredefinedExpr(Loc, IT);
3170 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3171 SmallString<16> CharBuffer;
3172 bool Invalid = false;
3173 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3177 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3179 if (Literal.hadError())
3183 if (Literal.isWide())
3184 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3185 else if (Literal.isUTF16())
3186 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3187 else if (Literal.isUTF32())
3188 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3189 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3190 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3192 Ty = Context.CharTy; // 'x' -> char in C++
3194 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3195 if (Literal.isWide())
3196 Kind = CharacterLiteral::Wide;
3197 else if (Literal.isUTF16())
3198 Kind = CharacterLiteral::UTF16;
3199 else if (Literal.isUTF32())
3200 Kind = CharacterLiteral::UTF32;
3201 else if (Literal.isUTF8())
3202 Kind = CharacterLiteral::UTF8;
3204 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3207 if (Literal.getUDSuffix().empty())
3210 // We're building a user-defined literal.
3211 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3212 SourceLocation UDSuffixLoc =
3213 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3215 // Make sure we're allowed user-defined literals here.
3217 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3219 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3220 // operator "" X (ch)
3221 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3222 Lit, Tok.getLocation());
3225 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3226 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3227 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3228 Context.IntTy, Loc);
3231 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3232 QualType Ty, SourceLocation Loc) {
3233 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3235 using llvm::APFloat;
3236 APFloat Val(Format);
3238 APFloat::opStatus result = Literal.GetFloatValue(Val);
3240 // Overflow is always an error, but underflow is only an error if
3241 // we underflowed to zero (APFloat reports denormals as underflow).
3242 if ((result & APFloat::opOverflow) ||
3243 ((result & APFloat::opUnderflow) && Val.isZero())) {
3244 unsigned diagnostic;
3245 SmallString<20> buffer;
3246 if (result & APFloat::opOverflow) {
3247 diagnostic = diag::warn_float_overflow;
3248 APFloat::getLargest(Format).toString(buffer);
3250 diagnostic = diag::warn_float_underflow;
3251 APFloat::getSmallest(Format).toString(buffer);
3254 S.Diag(Loc, diagnostic)
3256 << StringRef(buffer.data(), buffer.size());
3259 bool isExact = (result == APFloat::opOK);
3260 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3263 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3264 assert(E && "Invalid expression");
3266 if (E->isValueDependent())
3269 QualType QT = E->getType();
3270 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3271 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3275 llvm::APSInt ValueAPS;
3276 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3281 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3282 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3283 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3284 << ValueAPS.toString(10) << ValueIsPositive;
3291 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3292 // Fast path for a single digit (which is quite common). A single digit
3293 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3294 if (Tok.getLength() == 1) {
3295 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3296 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3299 SmallString<128> SpellingBuffer;
3300 // NumericLiteralParser wants to overread by one character. Add padding to
3301 // the buffer in case the token is copied to the buffer. If getSpelling()
3302 // returns a StringRef to the memory buffer, it should have a null char at
3303 // the EOF, so it is also safe.
3304 SpellingBuffer.resize(Tok.getLength() + 1);
3306 // Get the spelling of the token, which eliminates trigraphs, etc.
3307 bool Invalid = false;
3308 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3312 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3313 if (Literal.hadError)
3316 if (Literal.hasUDSuffix()) {
3317 // We're building a user-defined literal.
3318 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3319 SourceLocation UDSuffixLoc =
3320 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3322 // Make sure we're allowed user-defined literals here.
3324 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3327 if (Literal.isFloatingLiteral()) {
3328 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3329 // long double, the literal is treated as a call of the form
3330 // operator "" X (f L)
3331 CookedTy = Context.LongDoubleTy;
3333 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3334 // unsigned long long, the literal is treated as a call of the form
3335 // operator "" X (n ULL)
3336 CookedTy = Context.UnsignedLongLongTy;
3339 DeclarationName OpName =
3340 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3341 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3342 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3344 SourceLocation TokLoc = Tok.getLocation();
3346 // Perform literal operator lookup to determine if we're building a raw
3347 // literal or a cooked one.
3348 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3349 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3350 /*AllowRaw*/true, /*AllowTemplate*/true,
3351 /*AllowStringTemplate*/false)) {
3357 if (Literal.isFloatingLiteral()) {
3358 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3360 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3361 if (Literal.GetIntegerValue(ResultVal))
3362 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3363 << /* Unsigned */ 1;
3364 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3367 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3371 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3372 // literal is treated as a call of the form
3373 // operator "" X ("n")
3374 unsigned Length = Literal.getUDSuffixOffset();
3375 QualType StrTy = Context.getConstantArrayType(
3376 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3377 ArrayType::Normal, 0);
3378 Expr *Lit = StringLiteral::Create(
3379 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3380 /*Pascal*/false, StrTy, &TokLoc, 1);
3381 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3384 case LOLR_Template: {
3385 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3386 // template), L is treated as a call fo the form
3387 // operator "" X <'c1', 'c2', ... 'ck'>()
3388 // where n is the source character sequence c1 c2 ... ck.
3389 TemplateArgumentListInfo ExplicitArgs;
3390 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3391 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3392 llvm::APSInt Value(CharBits, CharIsUnsigned);
3393 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3394 Value = TokSpelling[I];
3395 TemplateArgument Arg(Context, Value, Context.CharTy);
3396 TemplateArgumentLocInfo ArgInfo;
3397 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3399 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3402 case LOLR_StringTemplate:
3403 llvm_unreachable("unexpected literal operator lookup result");
3409 if (Literal.isFloatingLiteral()) {
3411 if (Literal.isHalf){
3412 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3413 Ty = Context.HalfTy;
3415 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3418 } else if (Literal.isFloat)
3419 Ty = Context.FloatTy;
3420 else if (Literal.isLong)
3421 Ty = Context.LongDoubleTy;
3422 else if (Literal.isFloat128)
3423 Ty = Context.Float128Ty;
3425 Ty = Context.DoubleTy;
3427 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3429 if (Ty == Context.DoubleTy) {
3430 if (getLangOpts().SinglePrecisionConstants) {
3431 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3432 if (BTy->getKind() != BuiltinType::Float) {
3433 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3435 } else if (getLangOpts().OpenCL &&
3436 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3437 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3438 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3439 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3442 } else if (!Literal.isIntegerLiteral()) {
3447 // 'long long' is a C99 or C++11 feature.
3448 if (!getLangOpts().C99 && Literal.isLongLong) {
3449 if (getLangOpts().CPlusPlus)
3450 Diag(Tok.getLocation(),
3451 getLangOpts().CPlusPlus11 ?
3452 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3454 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3457 // Get the value in the widest-possible width.
3458 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3459 llvm::APInt ResultVal(MaxWidth, 0);
3461 if (Literal.GetIntegerValue(ResultVal)) {
3462 // If this value didn't fit into uintmax_t, error and force to ull.
3463 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3464 << /* Unsigned */ 1;
3465 Ty = Context.UnsignedLongLongTy;
3466 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3467 "long long is not intmax_t?");
3469 // If this value fits into a ULL, try to figure out what else it fits into
3470 // according to the rules of C99 6.4.4.1p5.
3472 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3473 // be an unsigned int.
3474 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3476 // Check from smallest to largest, picking the smallest type we can.
3479 // Microsoft specific integer suffixes are explicitly sized.
3480 if (Literal.MicrosoftInteger) {
3481 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3483 Ty = Context.CharTy;
3485 Width = Literal.MicrosoftInteger;
3486 Ty = Context.getIntTypeForBitwidth(Width,
3487 /*Signed=*/!Literal.isUnsigned);
3491 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3492 // Are int/unsigned possibilities?
3493 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3495 // Does it fit in a unsigned int?
3496 if (ResultVal.isIntN(IntSize)) {
3497 // Does it fit in a signed int?
3498 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3500 else if (AllowUnsigned)
3501 Ty = Context.UnsignedIntTy;
3506 // Are long/unsigned long possibilities?
3507 if (Ty.isNull() && !Literal.isLongLong) {
3508 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3510 // Does it fit in a unsigned long?
3511 if (ResultVal.isIntN(LongSize)) {
3512 // Does it fit in a signed long?
3513 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3514 Ty = Context.LongTy;
3515 else if (AllowUnsigned)
3516 Ty = Context.UnsignedLongTy;
3517 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3519 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3520 const unsigned LongLongSize =
3521 Context.getTargetInfo().getLongLongWidth();
3522 Diag(Tok.getLocation(),
3523 getLangOpts().CPlusPlus
3525 ? diag::warn_old_implicitly_unsigned_long_cxx
3526 : /*C++98 UB*/ diag::
3527 ext_old_implicitly_unsigned_long_cxx
3528 : diag::warn_old_implicitly_unsigned_long)
3529 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3530 : /*will be ill-formed*/ 1);
3531 Ty = Context.UnsignedLongTy;
3537 // Check long long if needed.
3539 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3541 // Does it fit in a unsigned long long?
3542 if (ResultVal.isIntN(LongLongSize)) {
3543 // Does it fit in a signed long long?
3544 // To be compatible with MSVC, hex integer literals ending with the
3545 // LL or i64 suffix are always signed in Microsoft mode.
3546 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3547 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3548 Ty = Context.LongLongTy;
3549 else if (AllowUnsigned)
3550 Ty = Context.UnsignedLongLongTy;
3551 Width = LongLongSize;
3555 // If we still couldn't decide a type, we probably have something that
3556 // does not fit in a signed long long, but has no U suffix.
3558 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3559 Ty = Context.UnsignedLongLongTy;
3560 Width = Context.getTargetInfo().getLongLongWidth();
3563 if (ResultVal.getBitWidth() != Width)
3564 ResultVal = ResultVal.trunc(Width);
3566 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3569 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3570 if (Literal.isImaginary)
3571 Res = new (Context) ImaginaryLiteral(Res,
3572 Context.getComplexType(Res->getType()));
3577 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3578 assert(E && "ActOnParenExpr() missing expr");
3579 return new (Context) ParenExpr(L, R, E);
3582 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3584 SourceRange ArgRange) {
3585 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3586 // scalar or vector data type argument..."
3587 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3588 // type (C99 6.2.5p18) or void.
3589 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3590 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3595 assert((T->isVoidType() || !T->isIncompleteType()) &&
3596 "Scalar types should always be complete");
3600 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3602 SourceRange ArgRange,
3603 UnaryExprOrTypeTrait TraitKind) {
3604 // Invalid types must be hard errors for SFINAE in C++.
3605 if (S.LangOpts.CPlusPlus)
3609 if (T->isFunctionType() &&
3610 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3611 // sizeof(function)/alignof(function) is allowed as an extension.
3612 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3613 << TraitKind << ArgRange;
3617 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3618 // this is an error (OpenCL v1.1 s6.3.k)
3619 if (T->isVoidType()) {
3620 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3621 : diag::ext_sizeof_alignof_void_type;
3622 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3629 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3631 SourceRange ArgRange,
3632 UnaryExprOrTypeTrait TraitKind) {
3633 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3634 // runtime doesn't allow it.
3635 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3636 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3637 << T << (TraitKind == UETT_SizeOf)
3645 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3646 /// pointer type is equal to T) and emit a warning if it is.
3647 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3649 // Don't warn if the operation changed the type.
3650 if (T != E->getType())
3653 // Now look for array decays.
3654 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3655 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3658 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3660 << ICE->getSubExpr()->getType();
3663 /// \brief Check the constraints on expression operands to unary type expression
3664 /// and type traits.
3666 /// Completes any types necessary and validates the constraints on the operand
3667 /// expression. The logic mostly mirrors the type-based overload, but may modify
3668 /// the expression as it completes the type for that expression through template
3669 /// instantiation, etc.
3670 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3671 UnaryExprOrTypeTrait ExprKind) {
3672 QualType ExprTy = E->getType();
3673 assert(!ExprTy->isReferenceType());
3675 if (ExprKind == UETT_VecStep)
3676 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3677 E->getSourceRange());
3679 // Whitelist some types as extensions
3680 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3681 E->getSourceRange(), ExprKind))
3684 // 'alignof' applied to an expression only requires the base element type of
3685 // the expression to be complete. 'sizeof' requires the expression's type to
3686 // be complete (and will attempt to complete it if it's an array of unknown
3688 if (ExprKind == UETT_AlignOf) {
3689 if (RequireCompleteType(E->getExprLoc(),
3690 Context.getBaseElementType(E->getType()),
3691 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3692 E->getSourceRange()))
3695 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3696 ExprKind, E->getSourceRange()))
3700 // Completing the expression's type may have changed it.
3701 ExprTy = E->getType();
3702 assert(!ExprTy->isReferenceType());
3704 if (ExprTy->isFunctionType()) {
3705 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3706 << ExprKind << E->getSourceRange();
3710 // The operand for sizeof and alignof is in an unevaluated expression context,
3711 // so side effects could result in unintended consequences.
3712 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3713 !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3714 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3716 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3717 E->getSourceRange(), ExprKind))
3720 if (ExprKind == UETT_SizeOf) {
3721 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3722 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3723 QualType OType = PVD->getOriginalType();
3724 QualType Type = PVD->getType();
3725 if (Type->isPointerType() && OType->isArrayType()) {
3726 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3728 Diag(PVD->getLocation(), diag::note_declared_at);
3733 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3734 // decays into a pointer and returns an unintended result. This is most
3735 // likely a typo for "sizeof(array) op x".
3736 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3737 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3739 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3747 /// \brief Check the constraints on operands to unary expression and type
3750 /// This will complete any types necessary, and validate the various constraints
3751 /// on those operands.
3753 /// The UsualUnaryConversions() function is *not* called by this routine.
3754 /// C99 6.3.2.1p[2-4] all state:
3755 /// Except when it is the operand of the sizeof operator ...
3757 /// C++ [expr.sizeof]p4
3758 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3759 /// standard conversions are not applied to the operand of sizeof.
3761 /// This policy is followed for all of the unary trait expressions.
3762 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3763 SourceLocation OpLoc,
3764 SourceRange ExprRange,
3765 UnaryExprOrTypeTrait ExprKind) {
3766 if (ExprType->isDependentType())
3769 // C++ [expr.sizeof]p2:
3770 // When applied to a reference or a reference type, the result
3771 // is the size of the referenced type.
3772 // C++11 [expr.alignof]p3:
3773 // When alignof is applied to a reference type, the result
3774 // shall be the alignment of the referenced type.
3775 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3776 ExprType = Ref->getPointeeType();
3778 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3779 // When alignof or _Alignof is applied to an array type, the result
3780 // is the alignment of the element type.
3781 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3782 ExprType = Context.getBaseElementType(ExprType);
3784 if (ExprKind == UETT_VecStep)
3785 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3787 // Whitelist some types as extensions
3788 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3792 if (RequireCompleteType(OpLoc, ExprType,
3793 diag::err_sizeof_alignof_incomplete_type,
3794 ExprKind, ExprRange))
3797 if (ExprType->isFunctionType()) {
3798 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3799 << ExprKind << ExprRange;
3803 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3810 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3811 E = E->IgnoreParens();
3813 // Cannot know anything else if the expression is dependent.
3814 if (E->isTypeDependent())
3817 if (E->getObjectKind() == OK_BitField) {
3818 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3819 << 1 << E->getSourceRange();
3823 ValueDecl *D = nullptr;
3824 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3826 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3827 D = ME->getMemberDecl();
3830 // If it's a field, require the containing struct to have a
3831 // complete definition so that we can compute the layout.
3833 // This can happen in C++11 onwards, either by naming the member
3834 // in a way that is not transformed into a member access expression
3835 // (in an unevaluated operand, for instance), or by naming the member
3836 // in a trailing-return-type.
3838 // For the record, since __alignof__ on expressions is a GCC
3839 // extension, GCC seems to permit this but always gives the
3840 // nonsensical answer 0.
3842 // We don't really need the layout here --- we could instead just
3843 // directly check for all the appropriate alignment-lowing
3844 // attributes --- but that would require duplicating a lot of
3845 // logic that just isn't worth duplicating for such a marginal
3847 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3848 // Fast path this check, since we at least know the record has a
3849 // definition if we can find a member of it.
3850 if (!FD->getParent()->isCompleteDefinition()) {
3851 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3852 << E->getSourceRange();
3856 // Otherwise, if it's a field, and the field doesn't have
3857 // reference type, then it must have a complete type (or be a
3858 // flexible array member, which we explicitly want to
3859 // white-list anyway), which makes the following checks trivial.
3860 if (!FD->getType()->isReferenceType())
3864 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3867 bool Sema::CheckVecStepExpr(Expr *E) {
3868 E = E->IgnoreParens();
3870 // Cannot know anything else if the expression is dependent.
3871 if (E->isTypeDependent())
3874 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3877 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3878 CapturingScopeInfo *CSI) {
3879 assert(T->isVariablyModifiedType());
3880 assert(CSI != nullptr);
3882 // We're going to walk down into the type and look for VLA expressions.
3884 const Type *Ty = T.getTypePtr();
3885 switch (Ty->getTypeClass()) {
3886 #define TYPE(Class, Base)
3887 #define ABSTRACT_TYPE(Class, Base)
3888 #define NON_CANONICAL_TYPE(Class, Base)
3889 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3890 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3891 #include "clang/AST/TypeNodes.def"
3894 // These types are never variably-modified.
3898 case Type::ExtVector:
3901 case Type::Elaborated:
3902 case Type::TemplateSpecialization:
3903 case Type::ObjCObject:
3904 case Type::ObjCInterface:
3905 case Type::ObjCObjectPointer:
3906 case Type::ObjCTypeParam:
3908 llvm_unreachable("type class is never variably-modified!");
3909 case Type::Adjusted:
3910 T = cast<AdjustedType>(Ty)->getOriginalType();
3913 T = cast<DecayedType>(Ty)->getPointeeType();
3916 T = cast<PointerType>(Ty)->getPointeeType();
3918 case Type::BlockPointer:
3919 T = cast<BlockPointerType>(Ty)->getPointeeType();
3921 case Type::LValueReference:
3922 case Type::RValueReference:
3923 T = cast<ReferenceType>(Ty)->getPointeeType();
3925 case Type::MemberPointer:
3926 T = cast<MemberPointerType>(Ty)->getPointeeType();
3928 case Type::ConstantArray:
3929 case Type::IncompleteArray:
3930 // Losing element qualification here is fine.
3931 T = cast<ArrayType>(Ty)->getElementType();
3933 case Type::VariableArray: {
3934 // Losing element qualification here is fine.
3935 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3937 // Unknown size indication requires no size computation.
3938 // Otherwise, evaluate and record it.
3939 if (auto Size = VAT->getSizeExpr()) {
3940 if (!CSI->isVLATypeCaptured(VAT)) {
3941 RecordDecl *CapRecord = nullptr;
3942 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3943 CapRecord = LSI->Lambda;
3944 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3945 CapRecord = CRSI->TheRecordDecl;
3948 auto ExprLoc = Size->getExprLoc();
3949 auto SizeType = Context.getSizeType();
3950 // Build the non-static data member.
3952 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3953 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3954 /*BW*/ nullptr, /*Mutable*/ false,
3955 /*InitStyle*/ ICIS_NoInit);
3956 Field->setImplicit(true);
3957 Field->setAccess(AS_private);
3958 Field->setCapturedVLAType(VAT);
3959 CapRecord->addDecl(Field);
3961 CSI->addVLATypeCapture(ExprLoc, SizeType);
3965 T = VAT->getElementType();
3968 case Type::FunctionProto:
3969 case Type::FunctionNoProto:
3970 T = cast<FunctionType>(Ty)->getReturnType();
3974 case Type::UnaryTransform:
3975 case Type::Attributed:
3976 case Type::SubstTemplateTypeParm:
3977 case Type::PackExpansion:
3978 // Keep walking after single level desugaring.
3979 T = T.getSingleStepDesugaredType(Context);
3982 T = cast<TypedefType>(Ty)->desugar();
3984 case Type::Decltype:
3985 T = cast<DecltypeType>(Ty)->desugar();
3988 case Type::DeducedTemplateSpecialization:
3989 T = cast<DeducedType>(Ty)->getDeducedType();
3991 case Type::TypeOfExpr:
3992 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3995 T = cast<AtomicType>(Ty)->getValueType();
3998 } while (!T.isNull() && T->isVariablyModifiedType());
4001 /// \brief Build a sizeof or alignof expression given a type operand.
4003 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4004 SourceLocation OpLoc,
4005 UnaryExprOrTypeTrait ExprKind,
4010 QualType T = TInfo->getType();
4012 if (!T->isDependentType() &&
4013 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4016 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4017 if (auto *TT = T->getAs<TypedefType>()) {
4018 for (auto I = FunctionScopes.rbegin(),
4019 E = std::prev(FunctionScopes.rend());
4021 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4024 DeclContext *DC = nullptr;
4025 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4026 DC = LSI->CallOperator;
4027 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4028 DC = CRSI->TheCapturedDecl;
4029 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4032 if (DC->containsDecl(TT->getDecl()))
4034 captureVariablyModifiedType(Context, T, CSI);
4040 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4041 return new (Context) UnaryExprOrTypeTraitExpr(
4042 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4045 /// \brief Build a sizeof or alignof expression given an expression
4048 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4049 UnaryExprOrTypeTrait ExprKind) {
4050 ExprResult PE = CheckPlaceholderExpr(E);
4056 // Verify that the operand is valid.
4057 bool isInvalid = false;
4058 if (E->isTypeDependent()) {
4059 // Delay type-checking for type-dependent expressions.
4060 } else if (ExprKind == UETT_AlignOf) {
4061 isInvalid = CheckAlignOfExpr(*this, E);
4062 } else if (ExprKind == UETT_VecStep) {
4063 isInvalid = CheckVecStepExpr(E);
4064 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4065 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4067 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4068 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4071 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4077 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4078 PE = TransformToPotentiallyEvaluated(E);
4079 if (PE.isInvalid()) return ExprError();
4083 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4084 return new (Context) UnaryExprOrTypeTraitExpr(
4085 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4088 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4089 /// expr and the same for @c alignof and @c __alignof
4090 /// Note that the ArgRange is invalid if isType is false.
4092 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4093 UnaryExprOrTypeTrait ExprKind, bool IsType,
4094 void *TyOrEx, SourceRange ArgRange) {
4095 // If error parsing type, ignore.
4096 if (!TyOrEx) return ExprError();
4099 TypeSourceInfo *TInfo;
4100 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4101 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4104 Expr *ArgEx = (Expr *)TyOrEx;
4105 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4109 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4111 if (V.get()->isTypeDependent())
4112 return S.Context.DependentTy;
4114 // _Real and _Imag are only l-values for normal l-values.
4115 if (V.get()->getObjectKind() != OK_Ordinary) {
4116 V = S.DefaultLvalueConversion(V.get());
4121 // These operators return the element type of a complex type.
4122 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4123 return CT->getElementType();
4125 // Otherwise they pass through real integer and floating point types here.
4126 if (V.get()->getType()->isArithmeticType())
4127 return V.get()->getType();
4129 // Test for placeholders.
4130 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4131 if (PR.isInvalid()) return QualType();
4132 if (PR.get() != V.get()) {
4134 return CheckRealImagOperand(S, V, Loc, IsReal);
4137 // Reject anything else.
4138 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4139 << (IsReal ? "__real" : "__imag");
4146 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4147 tok::TokenKind Kind, Expr *Input) {
4148 UnaryOperatorKind Opc;
4150 default: llvm_unreachable("Unknown unary op!");
4151 case tok::plusplus: Opc = UO_PostInc; break;
4152 case tok::minusminus: Opc = UO_PostDec; break;
4155 // Since this might is a postfix expression, get rid of ParenListExprs.
4156 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4157 if (Result.isInvalid()) return ExprError();
4158 Input = Result.get();
4160 return BuildUnaryOp(S, OpLoc, Opc, Input);
4163 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4165 /// \return true on error
4166 static bool checkArithmeticOnObjCPointer(Sema &S,
4167 SourceLocation opLoc,
4169 assert(op->getType()->isObjCObjectPointerType());
4170 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4171 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4174 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4175 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4176 << op->getSourceRange();
4180 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4181 auto *BaseNoParens = Base->IgnoreParens();
4182 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4183 return MSProp->getPropertyDecl()->getType()->isArrayType();
4184 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4188 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4189 Expr *idx, SourceLocation rbLoc) {
4190 if (base && !base->getType().isNull() &&
4191 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4192 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4193 /*Length=*/nullptr, rbLoc);
4195 // Since this might be a postfix expression, get rid of ParenListExprs.
4196 if (isa<ParenListExpr>(base)) {
4197 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4198 if (result.isInvalid()) return ExprError();
4199 base = result.get();
4202 // Handle any non-overload placeholder types in the base and index
4203 // expressions. We can't handle overloads here because the other
4204 // operand might be an overloadable type, in which case the overload
4205 // resolution for the operator overload should get the first crack
4207 bool IsMSPropertySubscript = false;
4208 if (base->getType()->isNonOverloadPlaceholderType()) {
4209 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4210 if (!IsMSPropertySubscript) {
4211 ExprResult result = CheckPlaceholderExpr(base);
4212 if (result.isInvalid())
4214 base = result.get();
4217 if (idx->getType()->isNonOverloadPlaceholderType()) {
4218 ExprResult result = CheckPlaceholderExpr(idx);
4219 if (result.isInvalid()) return ExprError();
4223 // Build an unanalyzed expression if either operand is type-dependent.
4224 if (getLangOpts().CPlusPlus &&
4225 (base->isTypeDependent() || idx->isTypeDependent())) {
4226 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4227 VK_LValue, OK_Ordinary, rbLoc);
4230 // MSDN, property (C++)
4231 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4232 // This attribute can also be used in the declaration of an empty array in a
4233 // class or structure definition. For example:
4234 // __declspec(property(get=GetX, put=PutX)) int x[];
4235 // The above statement indicates that x[] can be used with one or more array
4236 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4237 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4238 if (IsMSPropertySubscript) {
4239 // Build MS property subscript expression if base is MS property reference
4240 // or MS property subscript.
4241 return new (Context) MSPropertySubscriptExpr(
4242 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4245 // Use C++ overloaded-operator rules if either operand has record
4246 // type. The spec says to do this if either type is *overloadable*,
4247 // but enum types can't declare subscript operators or conversion
4248 // operators, so there's nothing interesting for overload resolution
4249 // to do if there aren't any record types involved.
4251 // ObjC pointers have their own subscripting logic that is not tied
4252 // to overload resolution and so should not take this path.
4253 if (getLangOpts().CPlusPlus &&
4254 (base->getType()->isRecordType() ||
4255 (!base->getType()->isObjCObjectPointerType() &&
4256 idx->getType()->isRecordType()))) {
4257 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4260 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4263 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4265 SourceLocation ColonLoc, Expr *Length,
4266 SourceLocation RBLoc) {
4267 if (Base->getType()->isPlaceholderType() &&
4268 !Base->getType()->isSpecificPlaceholderType(
4269 BuiltinType::OMPArraySection)) {
4270 ExprResult Result = CheckPlaceholderExpr(Base);
4271 if (Result.isInvalid())
4273 Base = Result.get();
4275 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4276 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4277 if (Result.isInvalid())
4279 Result = DefaultLvalueConversion(Result.get());
4280 if (Result.isInvalid())
4282 LowerBound = Result.get();
4284 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4285 ExprResult Result = CheckPlaceholderExpr(Length);
4286 if (Result.isInvalid())
4288 Result = DefaultLvalueConversion(Result.get());
4289 if (Result.isInvalid())
4291 Length = Result.get();
4294 // Build an unanalyzed expression if either operand is type-dependent.
4295 if (Base->isTypeDependent() ||
4297 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4298 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4299 return new (Context)
4300 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4301 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4304 // Perform default conversions.
4305 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4307 if (OriginalTy->isAnyPointerType()) {
4308 ResultTy = OriginalTy->getPointeeType();
4309 } else if (OriginalTy->isArrayType()) {
4310 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4313 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4314 << Base->getSourceRange());
4318 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4320 if (Res.isInvalid())
4321 return ExprError(Diag(LowerBound->getExprLoc(),
4322 diag::err_omp_typecheck_section_not_integer)
4323 << 0 << LowerBound->getSourceRange());
4324 LowerBound = Res.get();
4326 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4327 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4328 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4329 << 0 << LowerBound->getSourceRange();
4333 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4334 if (Res.isInvalid())
4335 return ExprError(Diag(Length->getExprLoc(),
4336 diag::err_omp_typecheck_section_not_integer)
4337 << 1 << Length->getSourceRange());
4340 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4341 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4342 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4343 << 1 << Length->getSourceRange();
4346 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4347 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4348 // type. Note that functions are not objects, and that (in C99 parlance)
4349 // incomplete types are not object types.
4350 if (ResultTy->isFunctionType()) {
4351 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4352 << ResultTy << Base->getSourceRange();
4356 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4357 diag::err_omp_section_incomplete_type, Base))
4360 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4361 llvm::APSInt LowerBoundValue;
4362 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4363 // OpenMP 4.5, [2.4 Array Sections]
4364 // The array section must be a subset of the original array.
4365 if (LowerBoundValue.isNegative()) {
4366 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4367 << LowerBound->getSourceRange();
4374 llvm::APSInt LengthValue;
4375 if (Length->EvaluateAsInt(LengthValue, Context)) {
4376 // OpenMP 4.5, [2.4 Array Sections]
4377 // The length must evaluate to non-negative integers.
4378 if (LengthValue.isNegative()) {
4379 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4380 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4381 << Length->getSourceRange();
4385 } else if (ColonLoc.isValid() &&
4386 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4387 !OriginalTy->isVariableArrayType()))) {
4388 // OpenMP 4.5, [2.4 Array Sections]
4389 // When the size of the array dimension is not known, the length must be
4390 // specified explicitly.
4391 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4392 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4396 if (!Base->getType()->isSpecificPlaceholderType(
4397 BuiltinType::OMPArraySection)) {
4398 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4399 if (Result.isInvalid())
4401 Base = Result.get();
4403 return new (Context)
4404 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4405 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4409 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4410 Expr *Idx, SourceLocation RLoc) {
4411 Expr *LHSExp = Base;
4414 ExprValueKind VK = VK_LValue;
4415 ExprObjectKind OK = OK_Ordinary;
4417 // Per C++ core issue 1213, the result is an xvalue if either operand is
4418 // a non-lvalue array, and an lvalue otherwise.
4419 if (getLangOpts().CPlusPlus11 &&
4420 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4421 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4424 // Perform default conversions.
4425 if (!LHSExp->getType()->getAs<VectorType>()) {
4426 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4427 if (Result.isInvalid())
4429 LHSExp = Result.get();
4431 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4432 if (Result.isInvalid())
4434 RHSExp = Result.get();
4436 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4438 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4439 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4440 // in the subscript position. As a result, we need to derive the array base
4441 // and index from the expression types.
4442 Expr *BaseExpr, *IndexExpr;
4443 QualType ResultType;
4444 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4447 ResultType = Context.DependentTy;
4448 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4451 ResultType = PTy->getPointeeType();
4452 } else if (const ObjCObjectPointerType *PTy =
4453 LHSTy->getAs<ObjCObjectPointerType>()) {
4457 // Use custom logic if this should be the pseudo-object subscript
4459 if (!LangOpts.isSubscriptPointerArithmetic())
4460 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4463 ResultType = PTy->getPointeeType();
4464 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4465 // Handle the uncommon case of "123[Ptr]".
4468 ResultType = PTy->getPointeeType();
4469 } else if (const ObjCObjectPointerType *PTy =
4470 RHSTy->getAs<ObjCObjectPointerType>()) {
4471 // Handle the uncommon case of "123[Ptr]".
4474 ResultType = PTy->getPointeeType();
4475 if (!LangOpts.isSubscriptPointerArithmetic()) {
4476 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4477 << ResultType << BaseExpr->getSourceRange();
4480 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4481 BaseExpr = LHSExp; // vectors: V[123]
4483 VK = LHSExp->getValueKind();
4484 if (VK != VK_RValue)
4485 OK = OK_VectorComponent;
4487 // FIXME: need to deal with const...
4488 ResultType = VTy->getElementType();
4489 } else if (LHSTy->isArrayType()) {
4490 // If we see an array that wasn't promoted by
4491 // DefaultFunctionArrayLvalueConversion, it must be an array that
4492 // wasn't promoted because of the C90 rule that doesn't
4493 // allow promoting non-lvalue arrays. Warn, then
4494 // force the promotion here.
4495 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4496 LHSExp->getSourceRange();
4497 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4498 CK_ArrayToPointerDecay).get();
4499 LHSTy = LHSExp->getType();
4503 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4504 } else if (RHSTy->isArrayType()) {
4505 // Same as previous, except for 123[f().a] case
4506 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4507 RHSExp->getSourceRange();
4508 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4509 CK_ArrayToPointerDecay).get();
4510 RHSTy = RHSExp->getType();
4514 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4516 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4517 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4520 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4521 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4522 << IndexExpr->getSourceRange());
4524 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4525 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4526 && !IndexExpr->isTypeDependent())
4527 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4529 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4530 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4531 // type. Note that Functions are not objects, and that (in C99 parlance)
4532 // incomplete types are not object types.
4533 if (ResultType->isFunctionType()) {
4534 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4535 << ResultType << BaseExpr->getSourceRange();
4539 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4540 // GNU extension: subscripting on pointer to void
4541 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4542 << BaseExpr->getSourceRange();
4544 // C forbids expressions of unqualified void type from being l-values.
4545 // See IsCForbiddenLValueType.
4546 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4547 } else if (!ResultType->isDependentType() &&
4548 RequireCompleteType(LLoc, ResultType,
4549 diag::err_subscript_incomplete_type, BaseExpr))
4552 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4553 !ResultType.isCForbiddenLValueType());
4555 return new (Context)
4556 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4559 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4560 ParmVarDecl *Param) {
4561 if (Param->hasUnparsedDefaultArg()) {
4563 diag::err_use_of_default_argument_to_function_declared_later) <<
4564 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4565 Diag(UnparsedDefaultArgLocs[Param],
4566 diag::note_default_argument_declared_here);
4570 if (Param->hasUninstantiatedDefaultArg()) {
4571 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4573 EnterExpressionEvaluationContext EvalContext(
4574 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4576 // Instantiate the expression.
4577 MultiLevelTemplateArgumentList MutiLevelArgList
4578 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4580 InstantiatingTemplate Inst(*this, CallLoc, Param,
4581 MutiLevelArgList.getInnermost());
4582 if (Inst.isInvalid())
4584 if (Inst.isAlreadyInstantiating()) {
4585 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4586 Param->setInvalidDecl();
4592 // C++ [dcl.fct.default]p5:
4593 // The names in the [default argument] expression are bound, and
4594 // the semantic constraints are checked, at the point where the
4595 // default argument expression appears.
4596 ContextRAII SavedContext(*this, FD);
4597 LocalInstantiationScope Local(*this);
4598 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4599 /*DirectInit*/false);
4601 if (Result.isInvalid())
4604 // Check the expression as an initializer for the parameter.
4605 InitializedEntity Entity
4606 = InitializedEntity::InitializeParameter(Context, Param);
4607 InitializationKind Kind
4608 = InitializationKind::CreateCopy(Param->getLocation(),
4609 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4610 Expr *ResultE = Result.getAs<Expr>();
4612 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4613 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4614 if (Result.isInvalid())
4617 Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4618 Param->getOuterLocStart());
4619 if (Result.isInvalid())
4622 // Remember the instantiated default argument.
4623 Param->setDefaultArg(Result.getAs<Expr>());
4624 if (ASTMutationListener *L = getASTMutationListener()) {
4625 L->DefaultArgumentInstantiated(Param);
4629 // If the default argument expression is not set yet, we are building it now.
4630 if (!Param->hasInit()) {
4631 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4632 Param->setInvalidDecl();
4636 // If the default expression creates temporaries, we need to
4637 // push them to the current stack of expression temporaries so they'll
4638 // be properly destroyed.
4639 // FIXME: We should really be rebuilding the default argument with new
4640 // bound temporaries; see the comment in PR5810.
4641 // We don't need to do that with block decls, though, because
4642 // blocks in default argument expression can never capture anything.
4643 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4644 // Set the "needs cleanups" bit regardless of whether there are
4645 // any explicit objects.
4646 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4648 // Append all the objects to the cleanup list. Right now, this
4649 // should always be a no-op, because blocks in default argument
4650 // expressions should never be able to capture anything.
4651 assert(!Init->getNumObjects() &&
4652 "default argument expression has capturing blocks?");
4655 // We already type-checked the argument, so we know it works.
4656 // Just mark all of the declarations in this potentially-evaluated expression
4657 // as being "referenced".
4658 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4659 /*SkipLocalVariables=*/true);
4663 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4664 FunctionDecl *FD, ParmVarDecl *Param) {
4665 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4667 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4670 Sema::VariadicCallType
4671 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4673 if (Proto && Proto->isVariadic()) {
4674 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4675 return VariadicConstructor;
4676 else if (Fn && Fn->getType()->isBlockPointerType())
4677 return VariadicBlock;
4679 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4680 if (Method->isInstance())
4681 return VariadicMethod;
4682 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4683 return VariadicMethod;
4684 return VariadicFunction;
4686 return VariadicDoesNotApply;
4690 class FunctionCallCCC : public FunctionCallFilterCCC {
4692 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4693 unsigned NumArgs, MemberExpr *ME)
4694 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4695 FunctionName(FuncName) {}
4697 bool ValidateCandidate(const TypoCorrection &candidate) override {
4698 if (!candidate.getCorrectionSpecifier() ||
4699 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4703 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4707 const IdentifierInfo *const FunctionName;
4711 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4712 FunctionDecl *FDecl,
4713 ArrayRef<Expr *> Args) {
4714 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4715 DeclarationName FuncName = FDecl->getDeclName();
4716 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4718 if (TypoCorrection Corrected = S.CorrectTypo(
4719 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4720 S.getScopeForContext(S.CurContext), nullptr,
4721 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4723 Sema::CTK_ErrorRecovery)) {
4724 if (NamedDecl *ND = Corrected.getFoundDecl()) {
4725 if (Corrected.isOverloaded()) {
4726 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4727 OverloadCandidateSet::iterator Best;
4728 for (NamedDecl *CD : Corrected) {
4729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4730 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4733 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4735 ND = Best->FoundDecl;
4736 Corrected.setCorrectionDecl(ND);
4742 ND = ND->getUnderlyingDecl();
4743 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4747 return TypoCorrection();
4750 /// ConvertArgumentsForCall - Converts the arguments specified in
4751 /// Args/NumArgs to the parameter types of the function FDecl with
4752 /// function prototype Proto. Call is the call expression itself, and
4753 /// Fn is the function expression. For a C++ member function, this
4754 /// routine does not attempt to convert the object argument. Returns
4755 /// true if the call is ill-formed.
4757 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4758 FunctionDecl *FDecl,
4759 const FunctionProtoType *Proto,
4760 ArrayRef<Expr *> Args,
4761 SourceLocation RParenLoc,
4762 bool IsExecConfig) {
4763 // Bail out early if calling a builtin with custom typechecking.
4765 if (unsigned ID = FDecl->getBuiltinID())
4766 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4769 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4770 // assignment, to the types of the corresponding parameter, ...
4771 unsigned NumParams = Proto->getNumParams();
4772 bool Invalid = false;
4773 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4774 unsigned FnKind = Fn->getType()->isBlockPointerType()
4776 : (IsExecConfig ? 3 /* kernel function (exec config) */
4777 : 0 /* function */);
4779 // If too few arguments are available (and we don't have default
4780 // arguments for the remaining parameters), don't make the call.
4781 if (Args.size() < NumParams) {
4782 if (Args.size() < MinArgs) {
4784 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4786 MinArgs == NumParams && !Proto->isVariadic()
4787 ? diag::err_typecheck_call_too_few_args_suggest
4788 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4789 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4790 << static_cast<unsigned>(Args.size())
4791 << TC.getCorrectionRange());
4792 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4794 MinArgs == NumParams && !Proto->isVariadic()
4795 ? diag::err_typecheck_call_too_few_args_one
4796 : diag::err_typecheck_call_too_few_args_at_least_one)
4797 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4799 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4800 ? diag::err_typecheck_call_too_few_args
4801 : diag::err_typecheck_call_too_few_args_at_least)
4802 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4803 << Fn->getSourceRange();
4805 // Emit the location of the prototype.
4806 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4807 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4812 Call->setNumArgs(Context, NumParams);
4815 // If too many are passed and not variadic, error on the extras and drop
4817 if (Args.size() > NumParams) {
4818 if (!Proto->isVariadic()) {
4820 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4822 MinArgs == NumParams && !Proto->isVariadic()
4823 ? diag::err_typecheck_call_too_many_args_suggest
4824 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4825 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4826 << static_cast<unsigned>(Args.size())
4827 << TC.getCorrectionRange());
4828 } else if (NumParams == 1 && FDecl &&
4829 FDecl->getParamDecl(0)->getDeclName())
4830 Diag(Args[NumParams]->getLocStart(),
4831 MinArgs == NumParams
4832 ? diag::err_typecheck_call_too_many_args_one
4833 : diag::err_typecheck_call_too_many_args_at_most_one)
4834 << FnKind << FDecl->getParamDecl(0)
4835 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4836 << SourceRange(Args[NumParams]->getLocStart(),
4837 Args.back()->getLocEnd());
4839 Diag(Args[NumParams]->getLocStart(),
4840 MinArgs == NumParams
4841 ? diag::err_typecheck_call_too_many_args
4842 : diag::err_typecheck_call_too_many_args_at_most)
4843 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4844 << Fn->getSourceRange()
4845 << SourceRange(Args[NumParams]->getLocStart(),
4846 Args.back()->getLocEnd());
4848 // Emit the location of the prototype.
4849 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4850 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4853 // This deletes the extra arguments.
4854 Call->setNumArgs(Context, NumParams);
4858 SmallVector<Expr *, 8> AllArgs;
4859 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4861 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4862 Proto, 0, Args, AllArgs, CallType);
4865 unsigned TotalNumArgs = AllArgs.size();
4866 for (unsigned i = 0; i < TotalNumArgs; ++i)
4867 Call->setArg(i, AllArgs[i]);
4872 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4873 const FunctionProtoType *Proto,
4874 unsigned FirstParam, ArrayRef<Expr *> Args,
4875 SmallVectorImpl<Expr *> &AllArgs,
4876 VariadicCallType CallType, bool AllowExplicit,
4877 bool IsListInitialization) {
4878 unsigned NumParams = Proto->getNumParams();
4879 bool Invalid = false;
4881 // Continue to check argument types (even if we have too few/many args).
4882 for (unsigned i = FirstParam; i < NumParams; i++) {
4883 QualType ProtoArgType = Proto->getParamType(i);
4886 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4887 if (ArgIx < Args.size()) {
4888 Arg = Args[ArgIx++];
4890 if (RequireCompleteType(Arg->getLocStart(),
4892 diag::err_call_incomplete_argument, Arg))
4895 // Strip the unbridged-cast placeholder expression off, if applicable.
4896 bool CFAudited = false;
4897 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4898 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4899 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4900 Arg = stripARCUnbridgedCast(Arg);
4901 else if (getLangOpts().ObjCAutoRefCount &&
4902 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4903 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4906 InitializedEntity Entity =
4907 Param ? InitializedEntity::InitializeParameter(Context, Param,
4909 : InitializedEntity::InitializeParameter(
4910 Context, ProtoArgType, Proto->isParamConsumed(i));
4912 // Remember that parameter belongs to a CF audited API.
4914 Entity.setParameterCFAudited();
4916 ExprResult ArgE = PerformCopyInitialization(
4917 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4918 if (ArgE.isInvalid())
4921 Arg = ArgE.getAs<Expr>();
4923 assert(Param && "can't use default arguments without a known callee");
4925 ExprResult ArgExpr =
4926 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4927 if (ArgExpr.isInvalid())
4930 Arg = ArgExpr.getAs<Expr>();
4933 // Check for array bounds violations for each argument to the call. This
4934 // check only triggers warnings when the argument isn't a more complex Expr
4935 // with its own checking, such as a BinaryOperator.
4936 CheckArrayAccess(Arg);
4938 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4939 CheckStaticArrayArgument(CallLoc, Param, Arg);
4941 AllArgs.push_back(Arg);
4944 // If this is a variadic call, handle args passed through "...".
4945 if (CallType != VariadicDoesNotApply) {
4946 // Assume that extern "C" functions with variadic arguments that
4947 // return __unknown_anytype aren't *really* variadic.
4948 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4949 FDecl->isExternC()) {
4950 for (Expr *A : Args.slice(ArgIx)) {
4951 QualType paramType; // ignored
4952 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4953 Invalid |= arg.isInvalid();
4954 AllArgs.push_back(arg.get());
4957 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4959 for (Expr *A : Args.slice(ArgIx)) {
4960 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4961 Invalid |= Arg.isInvalid();
4962 AllArgs.push_back(Arg.get());
4966 // Check for array bounds violations.
4967 for (Expr *A : Args.slice(ArgIx))
4968 CheckArrayAccess(A);
4973 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4974 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4975 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4976 TL = DTL.getOriginalLoc();
4977 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4978 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4979 << ATL.getLocalSourceRange();
4982 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4983 /// array parameter, check that it is non-null, and that if it is formed by
4984 /// array-to-pointer decay, the underlying array is sufficiently large.
4986 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4987 /// array type derivation, then for each call to the function, the value of the
4988 /// corresponding actual argument shall provide access to the first element of
4989 /// an array with at least as many elements as specified by the size expression.
4991 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4993 const Expr *ArgExpr) {
4994 // Static array parameters are not supported in C++.
4995 if (!Param || getLangOpts().CPlusPlus)
4998 QualType OrigTy = Param->getOriginalType();
5000 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5001 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5004 if (ArgExpr->isNullPointerConstant(Context,
5005 Expr::NPC_NeverValueDependent)) {
5006 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5007 DiagnoseCalleeStaticArrayParam(*this, Param);
5011 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5015 const ConstantArrayType *ArgCAT =
5016 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5020 if (ArgCAT->getSize().ult(CAT->getSize())) {
5021 Diag(CallLoc, diag::warn_static_array_too_small)
5022 << ArgExpr->getSourceRange()
5023 << (unsigned) ArgCAT->getSize().getZExtValue()
5024 << (unsigned) CAT->getSize().getZExtValue();
5025 DiagnoseCalleeStaticArrayParam(*this, Param);
5029 /// Given a function expression of unknown-any type, try to rebuild it
5030 /// to have a function type.
5031 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5033 /// Is the given type a placeholder that we need to lower out
5034 /// immediately during argument processing?
5035 static bool isPlaceholderToRemoveAsArg(QualType type) {
5036 // Placeholders are never sugared.
5037 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5038 if (!placeholder) return false;
5040 switch (placeholder->getKind()) {
5041 // Ignore all the non-placeholder types.
5042 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5043 case BuiltinType::Id:
5044 #include "clang/Basic/OpenCLImageTypes.def"
5045 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5046 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5047 #include "clang/AST/BuiltinTypes.def"
5050 // We cannot lower out overload sets; they might validly be resolved
5051 // by the call machinery.
5052 case BuiltinType::Overload:
5055 // Unbridged casts in ARC can be handled in some call positions and
5056 // should be left in place.
5057 case BuiltinType::ARCUnbridgedCast:
5060 // Pseudo-objects should be converted as soon as possible.
5061 case BuiltinType::PseudoObject:
5064 // The debugger mode could theoretically but currently does not try
5065 // to resolve unknown-typed arguments based on known parameter types.
5066 case BuiltinType::UnknownAny:
5069 // These are always invalid as call arguments and should be reported.
5070 case BuiltinType::BoundMember:
5071 case BuiltinType::BuiltinFn:
5072 case BuiltinType::OMPArraySection:
5076 llvm_unreachable("bad builtin type kind");
5079 /// Check an argument list for placeholders that we won't try to
5081 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5082 // Apply this processing to all the arguments at once instead of
5083 // dying at the first failure.
5084 bool hasInvalid = false;
5085 for (size_t i = 0, e = args.size(); i != e; i++) {
5086 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5087 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5088 if (result.isInvalid()) hasInvalid = true;
5089 else args[i] = result.get();
5090 } else if (hasInvalid) {
5091 (void)S.CorrectDelayedTyposInExpr(args[i]);
5097 /// If a builtin function has a pointer argument with no explicit address
5098 /// space, then it should be able to accept a pointer to any address
5099 /// space as input. In order to do this, we need to replace the
5100 /// standard builtin declaration with one that uses the same address space
5103 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5104 /// it does not contain any pointer arguments without
5105 /// an address space qualifer. Otherwise the rewritten
5106 /// FunctionDecl is returned.
5107 /// TODO: Handle pointer return types.
5108 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5109 const FunctionDecl *FDecl,
5110 MultiExprArg ArgExprs) {
5112 QualType DeclType = FDecl->getType();
5113 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5115 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5116 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5119 bool NeedsNewDecl = false;
5121 SmallVector<QualType, 8> OverloadParams;
5123 for (QualType ParamType : FT->param_types()) {
5125 // Convert array arguments to pointer to simplify type lookup.
5127 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5128 if (ArgRes.isInvalid())
5130 Expr *Arg = ArgRes.get();
5131 QualType ArgType = Arg->getType();
5132 if (!ParamType->isPointerType() ||
5133 ParamType.getQualifiers().hasAddressSpace() ||
5134 !ArgType->isPointerType() ||
5135 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5136 OverloadParams.push_back(ParamType);
5140 NeedsNewDecl = true;
5141 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5143 QualType PointeeType = ParamType->getPointeeType();
5144 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5145 OverloadParams.push_back(Context.getPointerType(PointeeType));
5151 FunctionProtoType::ExtProtoInfo EPI;
5152 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5153 OverloadParams, EPI);
5154 DeclContext *Parent = Context.getTranslationUnitDecl();
5155 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5156 FDecl->getLocation(),
5157 FDecl->getLocation(),
5158 FDecl->getIdentifier(),
5162 /*hasPrototype=*/true);
5163 SmallVector<ParmVarDecl*, 16> Params;
5164 FT = cast<FunctionProtoType>(OverloadTy);
5165 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5166 QualType ParamType = FT->getParamType(i);
5168 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5169 SourceLocation(), nullptr, ParamType,
5170 /*TInfo=*/nullptr, SC_None, nullptr);
5171 Parm->setScopeInfo(0, i);
5172 Params.push_back(Parm);
5174 OverloadDecl->setParams(Params);
5175 return OverloadDecl;
5178 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5179 FunctionDecl *Callee,
5180 MultiExprArg ArgExprs) {
5181 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5182 // similar attributes) really don't like it when functions are called with an
5183 // invalid number of args.
5184 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5185 /*PartialOverloading=*/false) &&
5186 !Callee->isVariadic())
5188 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5191 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5192 S.Diag(Fn->getLocStart(),
5193 isa<CXXMethodDecl>(Callee)
5194 ? diag::err_ovl_no_viable_member_function_in_call
5195 : diag::err_ovl_no_viable_function_in_call)
5196 << Callee << Callee->getSourceRange();
5197 S.Diag(Callee->getLocation(),
5198 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5199 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5204 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5205 /// This provides the location of the left/right parens and a list of comma
5207 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5208 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5209 Expr *ExecConfig, bool IsExecConfig) {
5210 // Since this might be a postfix expression, get rid of ParenListExprs.
5211 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5212 if (Result.isInvalid()) return ExprError();
5215 if (checkArgsForPlaceholders(*this, ArgExprs))
5218 if (getLangOpts().CPlusPlus) {
5219 // If this is a pseudo-destructor expression, build the call immediately.
5220 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5221 if (!ArgExprs.empty()) {
5222 // Pseudo-destructor calls should not have any arguments.
5223 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5224 << FixItHint::CreateRemoval(
5225 SourceRange(ArgExprs.front()->getLocStart(),
5226 ArgExprs.back()->getLocEnd()));
5229 return new (Context)
5230 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5232 if (Fn->getType() == Context.PseudoObjectTy) {
5233 ExprResult result = CheckPlaceholderExpr(Fn);
5234 if (result.isInvalid()) return ExprError();
5238 // Determine whether this is a dependent call inside a C++ template,
5239 // in which case we won't do any semantic analysis now.
5240 bool Dependent = false;
5241 if (Fn->isTypeDependent())
5243 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5248 return new (Context) CUDAKernelCallExpr(
5249 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5250 Context.DependentTy, VK_RValue, RParenLoc);
5252 return new (Context) CallExpr(
5253 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5257 // Determine whether this is a call to an object (C++ [over.call.object]).
5258 if (Fn->getType()->isRecordType())
5259 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5262 if (Fn->getType() == Context.UnknownAnyTy) {
5263 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5264 if (result.isInvalid()) return ExprError();
5268 if (Fn->getType() == Context.BoundMemberTy) {
5269 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5274 // Check for overloaded calls. This can happen even in C due to extensions.
5275 if (Fn->getType() == Context.OverloadTy) {
5276 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5278 // We aren't supposed to apply this logic for if there'Scope an '&'
5280 if (!find.HasFormOfMemberPointer) {
5281 OverloadExpr *ovl = find.Expression;
5282 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5283 return BuildOverloadedCallExpr(
5284 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5285 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5286 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5291 // If we're directly calling a function, get the appropriate declaration.
5292 if (Fn->getType() == Context.UnknownAnyTy) {
5293 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5294 if (result.isInvalid()) return ExprError();
5298 Expr *NakedFn = Fn->IgnoreParens();
5300 bool CallingNDeclIndirectly = false;
5301 NamedDecl *NDecl = nullptr;
5302 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5303 if (UnOp->getOpcode() == UO_AddrOf) {
5304 CallingNDeclIndirectly = true;
5305 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5309 if (isa<DeclRefExpr>(NakedFn)) {
5310 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5312 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5313 if (FDecl && FDecl->getBuiltinID()) {
5314 // Rewrite the function decl for this builtin by replacing parameters
5315 // with no explicit address space with the address space of the arguments
5318 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5320 Fn = DeclRefExpr::Create(
5321 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5322 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5325 } else if (isa<MemberExpr>(NakedFn))
5326 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5328 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5329 if (CallingNDeclIndirectly &&
5330 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5334 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5337 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5340 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5341 ExecConfig, IsExecConfig);
5344 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5346 /// __builtin_astype( value, dst type )
5348 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5349 SourceLocation BuiltinLoc,
5350 SourceLocation RParenLoc) {
5351 ExprValueKind VK = VK_RValue;
5352 ExprObjectKind OK = OK_Ordinary;
5353 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5354 QualType SrcTy = E->getType();
5355 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5356 return ExprError(Diag(BuiltinLoc,
5357 diag::err_invalid_astype_of_different_size)
5360 << E->getSourceRange());
5361 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5364 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5365 /// provided arguments.
5367 /// __builtin_convertvector( value, dst type )
5369 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5370 SourceLocation BuiltinLoc,
5371 SourceLocation RParenLoc) {
5372 TypeSourceInfo *TInfo;
5373 GetTypeFromParser(ParsedDestTy, &TInfo);
5374 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5377 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5378 /// i.e. an expression not of \p OverloadTy. The expression should
5379 /// unary-convert to an expression of function-pointer or
5380 /// block-pointer type.
5382 /// \param NDecl the declaration being called, if available
5384 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5385 SourceLocation LParenLoc,
5386 ArrayRef<Expr *> Args,
5387 SourceLocation RParenLoc,
5388 Expr *Config, bool IsExecConfig) {
5389 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5390 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5392 // Functions with 'interrupt' attribute cannot be called directly.
5393 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5394 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5398 // Interrupt handlers don't save off the VFP regs automatically on ARM,
5399 // so there's some risk when calling out to non-interrupt handler functions
5400 // that the callee might not preserve them. This is easy to diagnose here,
5401 // but can be very challenging to debug.
5402 if (auto *Caller = getCurFunctionDecl())
5403 if (Caller->hasAttr<ARMInterruptAttr>())
5404 if (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())
5405 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5407 // Promote the function operand.
5408 // We special-case function promotion here because we only allow promoting
5409 // builtin functions to function pointers in the callee of a call.
5412 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5413 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5414 CK_BuiltinFnToFnPtr).get();
5416 Result = CallExprUnaryConversions(Fn);
5418 if (Result.isInvalid())
5422 // Make the call expr early, before semantic checks. This guarantees cleanup
5423 // of arguments and function on error.
5426 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5427 cast<CallExpr>(Config), Args,
5428 Context.BoolTy, VK_RValue,
5431 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5432 VK_RValue, RParenLoc);
5434 if (!getLangOpts().CPlusPlus) {
5435 // C cannot always handle TypoExpr nodes in builtin calls and direct
5436 // function calls as their argument checking don't necessarily handle
5437 // dependent types properly, so make sure any TypoExprs have been
5439 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5440 if (!Result.isUsable()) return ExprError();
5441 TheCall = dyn_cast<CallExpr>(Result.get());
5442 if (!TheCall) return Result;
5443 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5446 // Bail out early if calling a builtin with custom typechecking.
5447 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5448 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5451 const FunctionType *FuncT;
5452 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5453 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5454 // have type pointer to function".
5455 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5457 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5458 << Fn->getType() << Fn->getSourceRange());
5459 } else if (const BlockPointerType *BPT =
5460 Fn->getType()->getAs<BlockPointerType>()) {
5461 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5463 // Handle calls to expressions of unknown-any type.
5464 if (Fn->getType() == Context.UnknownAnyTy) {
5465 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5466 if (rewrite.isInvalid()) return ExprError();
5468 TheCall->setCallee(Fn);
5472 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5473 << Fn->getType() << Fn->getSourceRange());
5476 if (getLangOpts().CUDA) {
5478 // CUDA: Kernel calls must be to global functions
5479 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5480 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5481 << FDecl->getName() << Fn->getSourceRange());
5483 // CUDA: Kernel function must have 'void' return type
5484 if (!FuncT->getReturnType()->isVoidType())
5485 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5486 << Fn->getType() << Fn->getSourceRange());
5488 // CUDA: Calls to global functions must be configured
5489 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5490 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5491 << FDecl->getName() << Fn->getSourceRange());
5495 // Check for a valid return type
5496 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5500 // We know the result type of the call, set it.
5501 TheCall->setType(FuncT->getCallResultType(Context));
5502 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5504 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5506 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5510 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5513 // Check if we have too few/too many template arguments, based
5514 // on our knowledge of the function definition.
5515 const FunctionDecl *Def = nullptr;
5516 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5517 Proto = Def->getType()->getAs<FunctionProtoType>();
5518 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5519 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5520 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5523 // If the function we're calling isn't a function prototype, but we have
5524 // a function prototype from a prior declaratiom, use that prototype.
5525 if (!FDecl->hasPrototype())
5526 Proto = FDecl->getType()->getAs<FunctionProtoType>();
5529 // Promote the arguments (C99 6.5.2.2p6).
5530 for (unsigned i = 0, e = Args.size(); i != e; i++) {
5531 Expr *Arg = Args[i];
5533 if (Proto && i < Proto->getNumParams()) {
5534 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5535 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5537 PerformCopyInitialization(Entity, SourceLocation(), Arg);
5538 if (ArgE.isInvalid())
5541 Arg = ArgE.getAs<Expr>();
5544 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5546 if (ArgE.isInvalid())
5549 Arg = ArgE.getAs<Expr>();
5552 if (RequireCompleteType(Arg->getLocStart(),
5554 diag::err_call_incomplete_argument, Arg))
5557 TheCall->setArg(i, Arg);
5561 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5562 if (!Method->isStatic())
5563 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5564 << Fn->getSourceRange());
5566 // Check for sentinels
5568 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5570 // Do special checking on direct calls to functions.
5572 if (CheckFunctionCall(FDecl, TheCall, Proto))
5576 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5578 if (CheckPointerCall(NDecl, TheCall, Proto))
5581 if (CheckOtherCall(TheCall, Proto))
5585 return MaybeBindToTemporary(TheCall);
5589 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5590 SourceLocation RParenLoc, Expr *InitExpr) {
5591 assert(Ty && "ActOnCompoundLiteral(): missing type");
5592 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5594 TypeSourceInfo *TInfo;
5595 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5597 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5599 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5603 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5604 SourceLocation RParenLoc, Expr *LiteralExpr) {
5605 QualType literalType = TInfo->getType();
5607 if (literalType->isArrayType()) {
5608 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5609 diag::err_illegal_decl_array_incomplete_type,
5610 SourceRange(LParenLoc,
5611 LiteralExpr->getSourceRange().getEnd())))
5613 if (literalType->isVariableArrayType())
5614 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5615 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5616 } else if (!literalType->isDependentType() &&
5617 RequireCompleteType(LParenLoc, literalType,
5618 diag::err_typecheck_decl_incomplete_type,
5619 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5622 InitializedEntity Entity
5623 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5624 InitializationKind Kind
5625 = InitializationKind::CreateCStyleCast(LParenLoc,
5626 SourceRange(LParenLoc, RParenLoc),
5628 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5629 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5631 if (Result.isInvalid())
5633 LiteralExpr = Result.get();
5635 bool isFileScope = !CurContext->isFunctionOrMethod();
5637 !LiteralExpr->isTypeDependent() &&
5638 !LiteralExpr->isValueDependent() &&
5639 !literalType->isDependentType()) { // 6.5.2.5p3
5640 if (CheckForConstantInitializer(LiteralExpr, literalType))
5644 // In C, compound literals are l-values for some reason.
5645 // For GCC compatibility, in C++, file-scope array compound literals with
5646 // constant initializers are also l-values, and compound literals are
5647 // otherwise prvalues.
5649 // (GCC also treats C++ list-initialized file-scope array prvalues with
5650 // constant initializers as l-values, but that's non-conforming, so we don't
5651 // follow it there.)
5653 // FIXME: It would be better to handle the lvalue cases as materializing and
5654 // lifetime-extending a temporary object, but our materialized temporaries
5655 // representation only supports lifetime extension from a variable, not "out
5657 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5658 // is bound to the result of applying array-to-pointer decay to the compound
5660 // FIXME: GCC supports compound literals of reference type, which should
5661 // obviously have a value kind derived from the kind of reference involved.
5663 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5667 return MaybeBindToTemporary(
5668 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5669 VK, LiteralExpr, isFileScope));
5673 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5674 SourceLocation RBraceLoc) {
5675 // Immediately handle non-overload placeholders. Overloads can be
5676 // resolved contextually, but everything else here can't.
5677 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5678 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5679 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5681 // Ignore failures; dropping the entire initializer list because
5682 // of one failure would be terrible for indexing/etc.
5683 if (result.isInvalid()) continue;
5685 InitArgList[I] = result.get();
5689 // Semantic analysis for initializers is done by ActOnDeclarator() and
5690 // CheckInitializer() - it requires knowledge of the object being intialized.
5692 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5694 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5698 /// Do an explicit extend of the given block pointer if we're in ARC.
5699 void Sema::maybeExtendBlockObject(ExprResult &E) {
5700 assert(E.get()->getType()->isBlockPointerType());
5701 assert(E.get()->isRValue());
5703 // Only do this in an r-value context.
5704 if (!getLangOpts().ObjCAutoRefCount) return;
5706 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5707 CK_ARCExtendBlockObject, E.get(),
5708 /*base path*/ nullptr, VK_RValue);
5709 Cleanup.setExprNeedsCleanups(true);
5712 /// Prepare a conversion of the given expression to an ObjC object
5714 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5715 QualType type = E.get()->getType();
5716 if (type->isObjCObjectPointerType()) {
5718 } else if (type->isBlockPointerType()) {
5719 maybeExtendBlockObject(E);
5720 return CK_BlockPointerToObjCPointerCast;
5722 assert(type->isPointerType());
5723 return CK_CPointerToObjCPointerCast;
5727 /// Prepares for a scalar cast, performing all the necessary stages
5728 /// except the final cast and returning the kind required.
5729 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5730 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5731 // Also, callers should have filtered out the invalid cases with
5732 // pointers. Everything else should be possible.
5734 QualType SrcTy = Src.get()->getType();
5735 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5738 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5739 case Type::STK_MemberPointer:
5740 llvm_unreachable("member pointer type in C");
5742 case Type::STK_CPointer:
5743 case Type::STK_BlockPointer:
5744 case Type::STK_ObjCObjectPointer:
5745 switch (DestTy->getScalarTypeKind()) {
5746 case Type::STK_CPointer: {
5747 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5748 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5749 if (SrcAS != DestAS)
5750 return CK_AddressSpaceConversion;
5753 case Type::STK_BlockPointer:
5754 return (SrcKind == Type::STK_BlockPointer
5755 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5756 case Type::STK_ObjCObjectPointer:
5757 if (SrcKind == Type::STK_ObjCObjectPointer)
5759 if (SrcKind == Type::STK_CPointer)
5760 return CK_CPointerToObjCPointerCast;
5761 maybeExtendBlockObject(Src);
5762 return CK_BlockPointerToObjCPointerCast;
5763 case Type::STK_Bool:
5764 return CK_PointerToBoolean;
5765 case Type::STK_Integral:
5766 return CK_PointerToIntegral;
5767 case Type::STK_Floating:
5768 case Type::STK_FloatingComplex:
5769 case Type::STK_IntegralComplex:
5770 case Type::STK_MemberPointer:
5771 llvm_unreachable("illegal cast from pointer");
5773 llvm_unreachable("Should have returned before this");
5775 case Type::STK_Bool: // casting from bool is like casting from an integer
5776 case Type::STK_Integral:
5777 switch (DestTy->getScalarTypeKind()) {
5778 case Type::STK_CPointer:
5779 case Type::STK_ObjCObjectPointer:
5780 case Type::STK_BlockPointer:
5781 if (Src.get()->isNullPointerConstant(Context,
5782 Expr::NPC_ValueDependentIsNull))
5783 return CK_NullToPointer;
5784 return CK_IntegralToPointer;
5785 case Type::STK_Bool:
5786 return CK_IntegralToBoolean;
5787 case Type::STK_Integral:
5788 return CK_IntegralCast;
5789 case Type::STK_Floating:
5790 return CK_IntegralToFloating;
5791 case Type::STK_IntegralComplex:
5792 Src = ImpCastExprToType(Src.get(),
5793 DestTy->castAs<ComplexType>()->getElementType(),
5795 return CK_IntegralRealToComplex;
5796 case Type::STK_FloatingComplex:
5797 Src = ImpCastExprToType(Src.get(),
5798 DestTy->castAs<ComplexType>()->getElementType(),
5799 CK_IntegralToFloating);
5800 return CK_FloatingRealToComplex;
5801 case Type::STK_MemberPointer:
5802 llvm_unreachable("member pointer type in C");
5804 llvm_unreachable("Should have returned before this");
5806 case Type::STK_Floating:
5807 switch (DestTy->getScalarTypeKind()) {
5808 case Type::STK_Floating:
5809 return CK_FloatingCast;
5810 case Type::STK_Bool:
5811 return CK_FloatingToBoolean;
5812 case Type::STK_Integral:
5813 return CK_FloatingToIntegral;
5814 case Type::STK_FloatingComplex:
5815 Src = ImpCastExprToType(Src.get(),
5816 DestTy->castAs<ComplexType>()->getElementType(),
5818 return CK_FloatingRealToComplex;
5819 case Type::STK_IntegralComplex:
5820 Src = ImpCastExprToType(Src.get(),
5821 DestTy->castAs<ComplexType>()->getElementType(),
5822 CK_FloatingToIntegral);
5823 return CK_IntegralRealToComplex;
5824 case Type::STK_CPointer:
5825 case Type::STK_ObjCObjectPointer:
5826 case Type::STK_BlockPointer:
5827 llvm_unreachable("valid float->pointer cast?");
5828 case Type::STK_MemberPointer:
5829 llvm_unreachable("member pointer type in C");
5831 llvm_unreachable("Should have returned before this");
5833 case Type::STK_FloatingComplex:
5834 switch (DestTy->getScalarTypeKind()) {
5835 case Type::STK_FloatingComplex:
5836 return CK_FloatingComplexCast;
5837 case Type::STK_IntegralComplex:
5838 return CK_FloatingComplexToIntegralComplex;
5839 case Type::STK_Floating: {
5840 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5841 if (Context.hasSameType(ET, DestTy))
5842 return CK_FloatingComplexToReal;
5843 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5844 return CK_FloatingCast;
5846 case Type::STK_Bool:
5847 return CK_FloatingComplexToBoolean;
5848 case Type::STK_Integral:
5849 Src = ImpCastExprToType(Src.get(),
5850 SrcTy->castAs<ComplexType>()->getElementType(),
5851 CK_FloatingComplexToReal);
5852 return CK_FloatingToIntegral;
5853 case Type::STK_CPointer:
5854 case Type::STK_ObjCObjectPointer:
5855 case Type::STK_BlockPointer:
5856 llvm_unreachable("valid complex float->pointer cast?");
5857 case Type::STK_MemberPointer:
5858 llvm_unreachable("member pointer type in C");
5860 llvm_unreachable("Should have returned before this");
5862 case Type::STK_IntegralComplex:
5863 switch (DestTy->getScalarTypeKind()) {
5864 case Type::STK_FloatingComplex:
5865 return CK_IntegralComplexToFloatingComplex;
5866 case Type::STK_IntegralComplex:
5867 return CK_IntegralComplexCast;
5868 case Type::STK_Integral: {
5869 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5870 if (Context.hasSameType(ET, DestTy))
5871 return CK_IntegralComplexToReal;
5872 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5873 return CK_IntegralCast;
5875 case Type::STK_Bool:
5876 return CK_IntegralComplexToBoolean;
5877 case Type::STK_Floating:
5878 Src = ImpCastExprToType(Src.get(),
5879 SrcTy->castAs<ComplexType>()->getElementType(),
5880 CK_IntegralComplexToReal);
5881 return CK_IntegralToFloating;
5882 case Type::STK_CPointer:
5883 case Type::STK_ObjCObjectPointer:
5884 case Type::STK_BlockPointer:
5885 llvm_unreachable("valid complex int->pointer cast?");
5886 case Type::STK_MemberPointer:
5887 llvm_unreachable("member pointer type in C");
5889 llvm_unreachable("Should have returned before this");
5892 llvm_unreachable("Unhandled scalar cast");
5895 static bool breakDownVectorType(QualType type, uint64_t &len,
5896 QualType &eltType) {
5897 // Vectors are simple.
5898 if (const VectorType *vecType = type->getAs<VectorType>()) {
5899 len = vecType->getNumElements();
5900 eltType = vecType->getElementType();
5901 assert(eltType->isScalarType());
5905 // We allow lax conversion to and from non-vector types, but only if
5906 // they're real types (i.e. non-complex, non-pointer scalar types).
5907 if (!type->isRealType()) return false;
5914 /// Are the two types lax-compatible vector types? That is, given
5915 /// that one of them is a vector, do they have equal storage sizes,
5916 /// where the storage size is the number of elements times the element
5919 /// This will also return false if either of the types is neither a
5920 /// vector nor a real type.
5921 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5922 assert(destTy->isVectorType() || srcTy->isVectorType());
5924 // Disallow lax conversions between scalars and ExtVectors (these
5925 // conversions are allowed for other vector types because common headers
5926 // depend on them). Most scalar OP ExtVector cases are handled by the
5927 // splat path anyway, which does what we want (convert, not bitcast).
5928 // What this rules out for ExtVectors is crazy things like char4*float.
5929 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5930 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5932 uint64_t srcLen, destLen;
5933 QualType srcEltTy, destEltTy;
5934 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5935 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5937 // ASTContext::getTypeSize will return the size rounded up to a
5938 // power of 2, so instead of using that, we need to use the raw
5939 // element size multiplied by the element count.
5940 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5941 uint64_t destEltSize = Context.getTypeSize(destEltTy);
5943 return (srcLen * srcEltSize == destLen * destEltSize);
5946 /// Is this a legal conversion between two types, one of which is
5947 /// known to be a vector type?
5948 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5949 assert(destTy->isVectorType() || srcTy->isVectorType());
5951 if (!Context.getLangOpts().LaxVectorConversions)
5953 return areLaxCompatibleVectorTypes(srcTy, destTy);
5956 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5958 assert(VectorTy->isVectorType() && "Not a vector type!");
5960 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5961 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5962 return Diag(R.getBegin(),
5963 Ty->isVectorType() ?
5964 diag::err_invalid_conversion_between_vectors :
5965 diag::err_invalid_conversion_between_vector_and_integer)
5966 << VectorTy << Ty << R;
5968 return Diag(R.getBegin(),
5969 diag::err_invalid_conversion_between_vector_and_scalar)
5970 << VectorTy << Ty << R;
5976 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5977 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5979 if (DestElemTy == SplattedExpr->getType())
5980 return SplattedExpr;
5982 assert(DestElemTy->isFloatingType() ||
5983 DestElemTy->isIntegralOrEnumerationType());
5986 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5987 // OpenCL requires that we convert `true` boolean expressions to -1, but
5988 // only when splatting vectors.
5989 if (DestElemTy->isFloatingType()) {
5990 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5991 // in two steps: boolean to signed integral, then to floating.
5992 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5993 CK_BooleanToSignedIntegral);
5994 SplattedExpr = CastExprRes.get();
5995 CK = CK_IntegralToFloating;
5997 CK = CK_BooleanToSignedIntegral;
6000 ExprResult CastExprRes = SplattedExpr;
6001 CK = PrepareScalarCast(CastExprRes, DestElemTy);
6002 if (CastExprRes.isInvalid())
6004 SplattedExpr = CastExprRes.get();
6006 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6009 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6010 Expr *CastExpr, CastKind &Kind) {
6011 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6013 QualType SrcTy = CastExpr->getType();
6015 // If SrcTy is a VectorType, the total size must match to explicitly cast to
6016 // an ExtVectorType.
6017 // In OpenCL, casts between vectors of different types are not allowed.
6018 // (See OpenCL 6.2).
6019 if (SrcTy->isVectorType()) {
6020 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6021 || (getLangOpts().OpenCL &&
6022 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6023 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6024 << DestTy << SrcTy << R;
6031 // All non-pointer scalars can be cast to ExtVector type. The appropriate
6032 // conversion will take place first from scalar to elt type, and then
6033 // splat from elt type to vector.
6034 if (SrcTy->isPointerType())
6035 return Diag(R.getBegin(),
6036 diag::err_invalid_conversion_between_vector_and_scalar)
6037 << DestTy << SrcTy << R;
6039 Kind = CK_VectorSplat;
6040 return prepareVectorSplat(DestTy, CastExpr);
6044 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6045 Declarator &D, ParsedType &Ty,
6046 SourceLocation RParenLoc, Expr *CastExpr) {
6047 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6048 "ActOnCastExpr(): missing type or expr");
6050 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6051 if (D.isInvalidType())
6054 if (getLangOpts().CPlusPlus) {
6055 // Check that there are no default arguments (C++ only).
6056 CheckExtraCXXDefaultArguments(D);
6058 // Make sure any TypoExprs have been dealt with.
6059 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6060 if (!Res.isUsable())
6062 CastExpr = Res.get();
6065 checkUnusedDeclAttributes(D);
6067 QualType castType = castTInfo->getType();
6068 Ty = CreateParsedType(castType, castTInfo);
6070 bool isVectorLiteral = false;
6072 // Check for an altivec or OpenCL literal,
6073 // i.e. all the elements are integer constants.
6074 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6075 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6076 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6077 && castType->isVectorType() && (PE || PLE)) {
6078 if (PLE && PLE->getNumExprs() == 0) {
6079 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6082 if (PE || PLE->getNumExprs() == 1) {
6083 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6084 if (!E->getType()->isVectorType())
6085 isVectorLiteral = true;
6088 isVectorLiteral = true;
6091 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6092 // then handle it as such.
6093 if (isVectorLiteral)
6094 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6096 // If the Expr being casted is a ParenListExpr, handle it specially.
6097 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6098 // sequence of BinOp comma operators.
6099 if (isa<ParenListExpr>(CastExpr)) {
6100 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6101 if (Result.isInvalid()) return ExprError();
6102 CastExpr = Result.get();
6105 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6106 !getSourceManager().isInSystemMacro(LParenLoc))
6107 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6109 CheckTollFreeBridgeCast(castType, CastExpr);
6111 CheckObjCBridgeRelatedCast(castType, CastExpr);
6113 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6115 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6118 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6119 SourceLocation RParenLoc, Expr *E,
6120 TypeSourceInfo *TInfo) {
6121 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6122 "Expected paren or paren list expression");
6127 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6128 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6129 LiteralLParenLoc = PE->getLParenLoc();
6130 LiteralRParenLoc = PE->getRParenLoc();
6131 exprs = PE->getExprs();
6132 numExprs = PE->getNumExprs();
6133 } else { // isa<ParenExpr> by assertion at function entrance
6134 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6135 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6136 subExpr = cast<ParenExpr>(E)->getSubExpr();
6141 QualType Ty = TInfo->getType();
6142 assert(Ty->isVectorType() && "Expected vector type");
6144 SmallVector<Expr *, 8> initExprs;
6145 const VectorType *VTy = Ty->getAs<VectorType>();
6146 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6148 // '(...)' form of vector initialization in AltiVec: the number of
6149 // initializers must be one or must match the size of the vector.
6150 // If a single value is specified in the initializer then it will be
6151 // replicated to all the components of the vector
6152 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6153 // The number of initializers must be one or must match the size of the
6154 // vector. If a single value is specified in the initializer then it will
6155 // be replicated to all the components of the vector
6156 if (numExprs == 1) {
6157 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6158 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6159 if (Literal.isInvalid())
6161 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6162 PrepareScalarCast(Literal, ElemTy));
6163 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6165 else if (numExprs < numElems) {
6166 Diag(E->getExprLoc(),
6167 diag::err_incorrect_number_of_vector_initializers);
6171 initExprs.append(exprs, exprs + numExprs);
6174 // For OpenCL, when the number of initializers is a single value,
6175 // it will be replicated to all components of the vector.
6176 if (getLangOpts().OpenCL &&
6177 VTy->getVectorKind() == VectorType::GenericVector &&
6179 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6180 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6181 if (Literal.isInvalid())
6183 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6184 PrepareScalarCast(Literal, ElemTy));
6185 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6188 initExprs.append(exprs, exprs + numExprs);
6190 // FIXME: This means that pretty-printing the final AST will produce curly
6191 // braces instead of the original commas.
6192 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6193 initExprs, LiteralRParenLoc);
6195 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6198 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6199 /// the ParenListExpr into a sequence of comma binary operators.
6201 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6202 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6206 ExprResult Result(E->getExpr(0));
6208 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6209 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6212 if (Result.isInvalid()) return ExprError();
6214 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6217 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6220 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6224 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6225 /// constant and the other is not a pointer. Returns true if a diagnostic is
6227 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6228 SourceLocation QuestionLoc) {
6229 Expr *NullExpr = LHSExpr;
6230 Expr *NonPointerExpr = RHSExpr;
6231 Expr::NullPointerConstantKind NullKind =
6232 NullExpr->isNullPointerConstant(Context,
6233 Expr::NPC_ValueDependentIsNotNull);
6235 if (NullKind == Expr::NPCK_NotNull) {
6237 NonPointerExpr = LHSExpr;
6239 NullExpr->isNullPointerConstant(Context,
6240 Expr::NPC_ValueDependentIsNotNull);
6243 if (NullKind == Expr::NPCK_NotNull)
6246 if (NullKind == Expr::NPCK_ZeroExpression)
6249 if (NullKind == Expr::NPCK_ZeroLiteral) {
6250 // In this case, check to make sure that we got here from a "NULL"
6251 // string in the source code.
6252 NullExpr = NullExpr->IgnoreParenImpCasts();
6253 SourceLocation loc = NullExpr->getExprLoc();
6254 if (!findMacroSpelling(loc, "NULL"))
6258 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6259 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6260 << NonPointerExpr->getType() << DiagType
6261 << NonPointerExpr->getSourceRange();
6265 /// \brief Return false if the condition expression is valid, true otherwise.
6266 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6267 QualType CondTy = Cond->getType();
6269 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6270 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6271 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6272 << CondTy << Cond->getSourceRange();
6277 if (CondTy->isScalarType()) return false;
6279 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6280 << CondTy << Cond->getSourceRange();
6284 /// \brief Handle when one or both operands are void type.
6285 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6287 Expr *LHSExpr = LHS.get();
6288 Expr *RHSExpr = RHS.get();
6290 if (!LHSExpr->getType()->isVoidType())
6291 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6292 << RHSExpr->getSourceRange();
6293 if (!RHSExpr->getType()->isVoidType())
6294 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6295 << LHSExpr->getSourceRange();
6296 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6297 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6298 return S.Context.VoidTy;
6301 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6303 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6304 QualType PointerTy) {
6305 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6306 !NullExpr.get()->isNullPointerConstant(S.Context,
6307 Expr::NPC_ValueDependentIsNull))
6310 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6314 /// \brief Checks compatibility between two pointers and return the resulting
6316 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6318 SourceLocation Loc) {
6319 QualType LHSTy = LHS.get()->getType();
6320 QualType RHSTy = RHS.get()->getType();
6322 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6323 // Two identical pointers types are always compatible.
6327 QualType lhptee, rhptee;
6329 // Get the pointee types.
6330 bool IsBlockPointer = false;
6331 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6332 lhptee = LHSBTy->getPointeeType();
6333 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6334 IsBlockPointer = true;
6336 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6337 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6340 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6341 // differently qualified versions of compatible types, the result type is
6342 // a pointer to an appropriately qualified version of the composite
6345 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6346 // clause doesn't make sense for our extensions. E.g. address space 2 should
6347 // be incompatible with address space 3: they may live on different devices or
6349 Qualifiers lhQual = lhptee.getQualifiers();
6350 Qualifiers rhQual = rhptee.getQualifiers();
6352 unsigned ResultAddrSpace = 0;
6353 unsigned LAddrSpace = lhQual.getAddressSpace();
6354 unsigned RAddrSpace = rhQual.getAddressSpace();
6355 if (S.getLangOpts().OpenCL) {
6356 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6357 // spaces is disallowed.
6358 if (lhQual.isAddressSpaceSupersetOf(rhQual))
6359 ResultAddrSpace = LAddrSpace;
6360 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6361 ResultAddrSpace = RAddrSpace;
6364 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6365 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6366 << RHS.get()->getSourceRange();
6371 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6372 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6373 lhQual.removeCVRQualifiers();
6374 rhQual.removeCVRQualifiers();
6376 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6377 // (C99 6.7.3) for address spaces. We assume that the check should behave in
6378 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6379 // qual types are compatible iff
6380 // * corresponded types are compatible
6381 // * CVR qualifiers are equal
6382 // * address spaces are equal
6383 // Thus for conditional operator we merge CVR and address space unqualified
6384 // pointees and if there is a composite type we return a pointer to it with
6385 // merged qualifiers.
6386 if (S.getLangOpts().OpenCL) {
6387 LHSCastKind = LAddrSpace == ResultAddrSpace
6389 : CK_AddressSpaceConversion;
6390 RHSCastKind = RAddrSpace == ResultAddrSpace
6392 : CK_AddressSpaceConversion;
6393 lhQual.removeAddressSpace();
6394 rhQual.removeAddressSpace();
6397 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6398 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6400 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6402 if (CompositeTy.isNull()) {
6403 // In this situation, we assume void* type. No especially good
6404 // reason, but this is what gcc does, and we do have to pick
6405 // to get a consistent AST.
6406 QualType incompatTy;
6407 incompatTy = S.Context.getPointerType(
6408 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6409 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6410 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6411 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6412 // for casts between types with incompatible address space qualifiers.
6413 // For the following code the compiler produces casts between global and
6414 // local address spaces of the corresponded innermost pointees:
6415 // local int *global *a;
6416 // global int *global *b;
6417 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6418 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6419 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6420 << RHS.get()->getSourceRange();
6424 // The pointer types are compatible.
6425 // In case of OpenCL ResultTy should have the address space qualifier
6426 // which is a superset of address spaces of both the 2nd and the 3rd
6427 // operands of the conditional operator.
6428 QualType ResultTy = [&, ResultAddrSpace]() {
6429 if (S.getLangOpts().OpenCL) {
6430 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6431 CompositeQuals.setAddressSpace(ResultAddrSpace);
6433 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6434 .withCVRQualifiers(MergedCVRQual);
6436 return CompositeTy.withCVRQualifiers(MergedCVRQual);
6439 ResultTy = S.Context.getBlockPointerType(ResultTy);
6441 ResultTy = S.Context.getPointerType(ResultTy);
6444 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6445 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6449 /// \brief Return the resulting type when the operands are both block pointers.
6450 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6453 SourceLocation Loc) {
6454 QualType LHSTy = LHS.get()->getType();
6455 QualType RHSTy = RHS.get()->getType();
6457 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6458 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6459 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6460 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6461 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6464 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6465 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6466 << RHS.get()->getSourceRange();
6470 // We have 2 block pointer types.
6471 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6474 /// \brief Return the resulting type when the operands are both pointers.
6476 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6478 SourceLocation Loc) {
6479 // get the pointer types
6480 QualType LHSTy = LHS.get()->getType();
6481 QualType RHSTy = RHS.get()->getType();
6483 // get the "pointed to" types
6484 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6485 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6487 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6488 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6489 // Figure out necessary qualifiers (C99 6.5.15p6)
6490 QualType destPointee
6491 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6492 QualType destType = S.Context.getPointerType(destPointee);
6493 // Add qualifiers if necessary.
6494 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6495 // Promote to void*.
6496 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6499 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6500 QualType destPointee
6501 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6502 QualType destType = S.Context.getPointerType(destPointee);
6503 // Add qualifiers if necessary.
6504 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6505 // Promote to void*.
6506 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6510 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6513 /// \brief Return false if the first expression is not an integer and the second
6514 /// expression is not a pointer, true otherwise.
6515 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6516 Expr* PointerExpr, SourceLocation Loc,
6517 bool IsIntFirstExpr) {
6518 if (!PointerExpr->getType()->isPointerType() ||
6519 !Int.get()->getType()->isIntegerType())
6522 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6523 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6525 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6526 << Expr1->getType() << Expr2->getType()
6527 << Expr1->getSourceRange() << Expr2->getSourceRange();
6528 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6529 CK_IntegralToPointer);
6533 /// \brief Simple conversion between integer and floating point types.
6535 /// Used when handling the OpenCL conditional operator where the
6536 /// condition is a vector while the other operands are scalar.
6538 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6539 /// types are either integer or floating type. Between the two
6540 /// operands, the type with the higher rank is defined as the "result
6541 /// type". The other operand needs to be promoted to the same type. No
6542 /// other type promotion is allowed. We cannot use
6543 /// UsualArithmeticConversions() for this purpose, since it always
6544 /// promotes promotable types.
6545 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6547 SourceLocation QuestionLoc) {
6548 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6549 if (LHS.isInvalid())
6551 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6552 if (RHS.isInvalid())
6555 // For conversion purposes, we ignore any qualifiers.
6556 // For example, "const float" and "float" are equivalent.
6558 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6560 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6562 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6563 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6564 << LHSType << LHS.get()->getSourceRange();
6568 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6569 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6570 << RHSType << RHS.get()->getSourceRange();
6574 // If both types are identical, no conversion is needed.
6575 if (LHSType == RHSType)
6578 // Now handle "real" floating types (i.e. float, double, long double).
6579 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6580 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6581 /*IsCompAssign = */ false);
6583 // Finally, we have two differing integer types.
6584 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6585 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6588 /// \brief Convert scalar operands to a vector that matches the
6589 /// condition in length.
6591 /// Used when handling the OpenCL conditional operator where the
6592 /// condition is a vector while the other operands are scalar.
6594 /// We first compute the "result type" for the scalar operands
6595 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6596 /// into a vector of that type where the length matches the condition
6597 /// vector type. s6.11.6 requires that the element types of the result
6598 /// and the condition must have the same number of bits.
6600 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6601 QualType CondTy, SourceLocation QuestionLoc) {
6602 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6603 if (ResTy.isNull()) return QualType();
6605 const VectorType *CV = CondTy->getAs<VectorType>();
6608 // Determine the vector result type
6609 unsigned NumElements = CV->getNumElements();
6610 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6612 // Ensure that all types have the same number of bits
6613 if (S.Context.getTypeSize(CV->getElementType())
6614 != S.Context.getTypeSize(ResTy)) {
6615 // Since VectorTy is created internally, it does not pretty print
6616 // with an OpenCL name. Instead, we just print a description.
6617 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6618 SmallString<64> Str;
6619 llvm::raw_svector_ostream OS(Str);
6620 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6621 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6622 << CondTy << OS.str();
6626 // Convert operands to the vector result type
6627 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6628 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6633 /// \brief Return false if this is a valid OpenCL condition vector
6634 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6635 SourceLocation QuestionLoc) {
6636 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6638 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6640 QualType EleTy = CondTy->getElementType();
6641 if (EleTy->isIntegerType()) return false;
6643 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6644 << Cond->getType() << Cond->getSourceRange();
6648 /// \brief Return false if the vector condition type and the vector
6649 /// result type are compatible.
6651 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6652 /// number of elements, and their element types have the same number
6654 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6655 SourceLocation QuestionLoc) {
6656 const VectorType *CV = CondTy->getAs<VectorType>();
6657 const VectorType *RV = VecResTy->getAs<VectorType>();
6660 if (CV->getNumElements() != RV->getNumElements()) {
6661 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6662 << CondTy << VecResTy;
6666 QualType CVE = CV->getElementType();
6667 QualType RVE = RV->getElementType();
6669 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6670 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6671 << CondTy << VecResTy;
6678 /// \brief Return the resulting type for the conditional operator in
6679 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6680 /// s6.3.i) when the condition is a vector type.
6682 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6683 ExprResult &LHS, ExprResult &RHS,
6684 SourceLocation QuestionLoc) {
6685 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6686 if (Cond.isInvalid())
6688 QualType CondTy = Cond.get()->getType();
6690 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6693 // If either operand is a vector then find the vector type of the
6694 // result as specified in OpenCL v1.1 s6.3.i.
6695 if (LHS.get()->getType()->isVectorType() ||
6696 RHS.get()->getType()->isVectorType()) {
6697 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6698 /*isCompAssign*/false,
6699 /*AllowBothBool*/true,
6700 /*AllowBoolConversions*/false);
6701 if (VecResTy.isNull()) return QualType();
6702 // The result type must match the condition type as specified in
6703 // OpenCL v1.1 s6.11.6.
6704 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6709 // Both operands are scalar.
6710 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6713 /// \brief Return true if the Expr is block type
6714 static bool checkBlockType(Sema &S, const Expr *E) {
6715 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6716 QualType Ty = CE->getCallee()->getType();
6717 if (Ty->isBlockPointerType()) {
6718 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6725 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6726 /// In that case, LHS = cond.
6728 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6729 ExprResult &RHS, ExprValueKind &VK,
6731 SourceLocation QuestionLoc) {
6733 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6734 if (!LHSResult.isUsable()) return QualType();
6737 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6738 if (!RHSResult.isUsable()) return QualType();
6741 // C++ is sufficiently different to merit its own checker.
6742 if (getLangOpts().CPlusPlus)
6743 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6748 // The OpenCL operator with a vector condition is sufficiently
6749 // different to merit its own checker.
6750 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6751 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6753 // First, check the condition.
6754 Cond = UsualUnaryConversions(Cond.get());
6755 if (Cond.isInvalid())
6757 if (checkCondition(*this, Cond.get(), QuestionLoc))
6760 // Now check the two expressions.
6761 if (LHS.get()->getType()->isVectorType() ||
6762 RHS.get()->getType()->isVectorType())
6763 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6764 /*AllowBothBool*/true,
6765 /*AllowBoolConversions*/false);
6767 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6768 if (LHS.isInvalid() || RHS.isInvalid())
6771 QualType LHSTy = LHS.get()->getType();
6772 QualType RHSTy = RHS.get()->getType();
6774 // Diagnose attempts to convert between __float128 and long double where
6775 // such conversions currently can't be handled.
6776 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6778 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6779 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6783 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6784 // selection operator (?:).
6785 if (getLangOpts().OpenCL &&
6786 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6790 // If both operands have arithmetic type, do the usual arithmetic conversions
6791 // to find a common type: C99 6.5.15p3,5.
6792 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6793 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6794 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6799 // If both operands are the same structure or union type, the result is that
6801 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6802 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6803 if (LHSRT->getDecl() == RHSRT->getDecl())
6804 // "If both the operands have structure or union type, the result has
6805 // that type." This implies that CV qualifiers are dropped.
6806 return LHSTy.getUnqualifiedType();
6807 // FIXME: Type of conditional expression must be complete in C mode.
6810 // C99 6.5.15p5: "If both operands have void type, the result has void type."
6811 // The following || allows only one side to be void (a GCC-ism).
6812 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6813 return checkConditionalVoidType(*this, LHS, RHS);
6816 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6817 // the type of the other operand."
6818 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6819 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6821 // All objective-c pointer type analysis is done here.
6822 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6824 if (LHS.isInvalid() || RHS.isInvalid())
6826 if (!compositeType.isNull())
6827 return compositeType;
6830 // Handle block pointer types.
6831 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6832 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6835 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6836 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6837 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6840 // GCC compatibility: soften pointer/integer mismatch. Note that
6841 // null pointers have been filtered out by this point.
6842 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6843 /*isIntFirstExpr=*/true))
6845 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6846 /*isIntFirstExpr=*/false))
6849 // Emit a better diagnostic if one of the expressions is a null pointer
6850 // constant and the other is not a pointer type. In this case, the user most
6851 // likely forgot to take the address of the other expression.
6852 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6855 // Otherwise, the operands are not compatible.
6856 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6857 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6858 << RHS.get()->getSourceRange();
6862 /// FindCompositeObjCPointerType - Helper method to find composite type of
6863 /// two objective-c pointer types of the two input expressions.
6864 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6865 SourceLocation QuestionLoc) {
6866 QualType LHSTy = LHS.get()->getType();
6867 QualType RHSTy = RHS.get()->getType();
6869 // Handle things like Class and struct objc_class*. Here we case the result
6870 // to the pseudo-builtin, because that will be implicitly cast back to the
6871 // redefinition type if an attempt is made to access its fields.
6872 if (LHSTy->isObjCClassType() &&
6873 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6874 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6877 if (RHSTy->isObjCClassType() &&
6878 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6879 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6882 // And the same for struct objc_object* / id
6883 if (LHSTy->isObjCIdType() &&
6884 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6885 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6888 if (RHSTy->isObjCIdType() &&
6889 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6890 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6893 // And the same for struct objc_selector* / SEL
6894 if (Context.isObjCSelType(LHSTy) &&
6895 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6896 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6899 if (Context.isObjCSelType(RHSTy) &&
6900 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6901 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6904 // Check constraints for Objective-C object pointers types.
6905 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6907 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6908 // Two identical object pointer types are always compatible.
6911 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6912 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6913 QualType compositeType = LHSTy;
6915 // If both operands are interfaces and either operand can be
6916 // assigned to the other, use that type as the composite
6917 // type. This allows
6918 // xxx ? (A*) a : (B*) b
6919 // where B is a subclass of A.
6921 // Additionally, as for assignment, if either type is 'id'
6922 // allow silent coercion. Finally, if the types are
6923 // incompatible then make sure to use 'id' as the composite
6924 // type so the result is acceptable for sending messages to.
6926 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6927 // It could return the composite type.
6928 if (!(compositeType =
6929 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6930 // Nothing more to do.
6931 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6932 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6933 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6934 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6935 } else if ((LHSTy->isObjCQualifiedIdType() ||
6936 RHSTy->isObjCQualifiedIdType()) &&
6937 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6938 // Need to handle "id<xx>" explicitly.
6939 // GCC allows qualified id and any Objective-C type to devolve to
6940 // id. Currently localizing to here until clear this should be
6941 // part of ObjCQualifiedIdTypesAreCompatible.
6942 compositeType = Context.getObjCIdType();
6943 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6944 compositeType = Context.getObjCIdType();
6946 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6948 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6949 QualType incompatTy = Context.getObjCIdType();
6950 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6951 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6954 // The object pointer types are compatible.
6955 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6956 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6957 return compositeType;
6959 // Check Objective-C object pointer types and 'void *'
6960 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6961 if (getLangOpts().ObjCAutoRefCount) {
6962 // ARC forbids the implicit conversion of object pointers to 'void *',
6963 // so these types are not compatible.
6964 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6969 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6970 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6971 QualType destPointee
6972 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6973 QualType destType = Context.getPointerType(destPointee);
6974 // Add qualifiers if necessary.
6975 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6976 // Promote to void*.
6977 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6980 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6981 if (getLangOpts().ObjCAutoRefCount) {
6982 // ARC forbids the implicit conversion of object pointers to 'void *',
6983 // so these types are not compatible.
6984 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6985 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6989 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6990 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6991 QualType destPointee
6992 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6993 QualType destType = Context.getPointerType(destPointee);
6994 // Add qualifiers if necessary.
6995 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6996 // Promote to void*.
6997 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7003 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7004 /// ParenRange in parentheses.
7005 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7006 const PartialDiagnostic &Note,
7007 SourceRange ParenRange) {
7008 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7009 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7011 Self.Diag(Loc, Note)
7012 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7013 << FixItHint::CreateInsertion(EndLoc, ")");
7015 // We can't display the parentheses, so just show the bare note.
7016 Self.Diag(Loc, Note) << ParenRange;
7020 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7021 return BinaryOperator::isAdditiveOp(Opc) ||
7022 BinaryOperator::isMultiplicativeOp(Opc) ||
7023 BinaryOperator::isShiftOp(Opc);
7026 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7027 /// expression, either using a built-in or overloaded operator,
7028 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7030 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7032 // Don't strip parenthesis: we should not warn if E is in parenthesis.
7033 E = E->IgnoreImpCasts();
7034 E = E->IgnoreConversionOperator();
7035 E = E->IgnoreImpCasts();
7037 // Built-in binary operator.
7038 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7039 if (IsArithmeticOp(OP->getOpcode())) {
7040 *Opcode = OP->getOpcode();
7041 *RHSExprs = OP->getRHS();
7046 // Overloaded operator.
7047 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7048 if (Call->getNumArgs() != 2)
7051 // Make sure this is really a binary operator that is safe to pass into
7052 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7053 OverloadedOperatorKind OO = Call->getOperator();
7054 if (OO < OO_Plus || OO > OO_Arrow ||
7055 OO == OO_PlusPlus || OO == OO_MinusMinus)
7058 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7059 if (IsArithmeticOp(OpKind)) {
7061 *RHSExprs = Call->getArg(1);
7069 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7070 /// or is a logical expression such as (x==y) which has int type, but is
7071 /// commonly interpreted as boolean.
7072 static bool ExprLooksBoolean(Expr *E) {
7073 E = E->IgnoreParenImpCasts();
7075 if (E->getType()->isBooleanType())
7077 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7078 return OP->isComparisonOp() || OP->isLogicalOp();
7079 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7080 return OP->getOpcode() == UO_LNot;
7081 if (E->getType()->isPointerType())
7087 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7088 /// and binary operator are mixed in a way that suggests the programmer assumed
7089 /// the conditional operator has higher precedence, for example:
7090 /// "int x = a + someBinaryCondition ? 1 : 2".
7091 static void DiagnoseConditionalPrecedence(Sema &Self,
7092 SourceLocation OpLoc,
7096 BinaryOperatorKind CondOpcode;
7099 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7101 if (!ExprLooksBoolean(CondRHS))
7104 // The condition is an arithmetic binary expression, with a right-
7105 // hand side that looks boolean, so warn.
7107 Self.Diag(OpLoc, diag::warn_precedence_conditional)
7108 << Condition->getSourceRange()
7109 << BinaryOperator::getOpcodeStr(CondOpcode);
7111 SuggestParentheses(Self, OpLoc,
7112 Self.PDiag(diag::note_precedence_silence)
7113 << BinaryOperator::getOpcodeStr(CondOpcode),
7114 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7116 SuggestParentheses(Self, OpLoc,
7117 Self.PDiag(diag::note_precedence_conditional_first),
7118 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7121 /// Compute the nullability of a conditional expression.
7122 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7123 QualType LHSTy, QualType RHSTy,
7125 if (!ResTy->isAnyPointerType())
7128 auto GetNullability = [&Ctx](QualType Ty) {
7129 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7132 return NullabilityKind::Unspecified;
7135 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7136 NullabilityKind MergedKind;
7138 // Compute nullability of a binary conditional expression.
7140 if (LHSKind == NullabilityKind::NonNull)
7141 MergedKind = NullabilityKind::NonNull;
7143 MergedKind = RHSKind;
7144 // Compute nullability of a normal conditional expression.
7146 if (LHSKind == NullabilityKind::Nullable ||
7147 RHSKind == NullabilityKind::Nullable)
7148 MergedKind = NullabilityKind::Nullable;
7149 else if (LHSKind == NullabilityKind::NonNull)
7150 MergedKind = RHSKind;
7151 else if (RHSKind == NullabilityKind::NonNull)
7152 MergedKind = LHSKind;
7154 MergedKind = NullabilityKind::Unspecified;
7157 // Return if ResTy already has the correct nullability.
7158 if (GetNullability(ResTy) == MergedKind)
7161 // Strip all nullability from ResTy.
7162 while (ResTy->getNullability(Ctx))
7163 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7165 // Create a new AttributedType with the new nullability kind.
7166 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7167 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7170 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7171 /// in the case of a the GNU conditional expr extension.
7172 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7173 SourceLocation ColonLoc,
7174 Expr *CondExpr, Expr *LHSExpr,
7176 if (!getLangOpts().CPlusPlus) {
7177 // C cannot handle TypoExpr nodes in the condition because it
7178 // doesn't handle dependent types properly, so make sure any TypoExprs have
7179 // been dealt with before checking the operands.
7180 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7181 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7182 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7184 if (!CondResult.isUsable())
7188 if (!LHSResult.isUsable())
7192 if (!RHSResult.isUsable())
7195 CondExpr = CondResult.get();
7196 LHSExpr = LHSResult.get();
7197 RHSExpr = RHSResult.get();
7200 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7201 // was the condition.
7202 OpaqueValueExpr *opaqueValue = nullptr;
7203 Expr *commonExpr = nullptr;
7205 commonExpr = CondExpr;
7206 // Lower out placeholder types first. This is important so that we don't
7207 // try to capture a placeholder. This happens in few cases in C++; such
7208 // as Objective-C++'s dictionary subscripting syntax.
7209 if (commonExpr->hasPlaceholderType()) {
7210 ExprResult result = CheckPlaceholderExpr(commonExpr);
7211 if (!result.isUsable()) return ExprError();
7212 commonExpr = result.get();
7214 // We usually want to apply unary conversions *before* saving, except
7215 // in the special case of a C++ l-value conditional.
7216 if (!(getLangOpts().CPlusPlus
7217 && !commonExpr->isTypeDependent()
7218 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7219 && commonExpr->isGLValue()
7220 && commonExpr->isOrdinaryOrBitFieldObject()
7221 && RHSExpr->isOrdinaryOrBitFieldObject()
7222 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7223 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7224 if (commonRes.isInvalid())
7226 commonExpr = commonRes.get();
7229 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7230 commonExpr->getType(),
7231 commonExpr->getValueKind(),
7232 commonExpr->getObjectKind(),
7234 LHSExpr = CondExpr = opaqueValue;
7237 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7238 ExprValueKind VK = VK_RValue;
7239 ExprObjectKind OK = OK_Ordinary;
7240 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7241 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7242 VK, OK, QuestionLoc);
7243 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7247 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7250 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7252 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7256 return new (Context)
7257 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7258 RHS.get(), result, VK, OK);
7260 return new (Context) BinaryConditionalOperator(
7261 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7262 ColonLoc, result, VK, OK);
7265 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7266 // being closely modeled after the C99 spec:-). The odd characteristic of this
7267 // routine is it effectively iqnores the qualifiers on the top level pointee.
7268 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7269 // FIXME: add a couple examples in this comment.
7270 static Sema::AssignConvertType
7271 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7272 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7273 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7275 // get the "pointed to" type (ignoring qualifiers at the top level)
7276 const Type *lhptee, *rhptee;
7277 Qualifiers lhq, rhq;
7278 std::tie(lhptee, lhq) =
7279 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7280 std::tie(rhptee, rhq) =
7281 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7283 Sema::AssignConvertType ConvTy = Sema::Compatible;
7285 // C99 6.5.16.1p1: This following citation is common to constraints
7286 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7287 // qualifiers of the type *pointed to* by the right;
7289 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7290 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7291 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7292 // Ignore lifetime for further calculation.
7293 lhq.removeObjCLifetime();
7294 rhq.removeObjCLifetime();
7297 if (!lhq.compatiblyIncludes(rhq)) {
7298 // Treat address-space mismatches as fatal. TODO: address subspaces
7299 if (!lhq.isAddressSpaceSupersetOf(rhq))
7300 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7302 // It's okay to add or remove GC or lifetime qualifiers when converting to
7304 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7305 .compatiblyIncludes(
7306 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7307 && (lhptee->isVoidType() || rhptee->isVoidType()))
7310 // Treat lifetime mismatches as fatal.
7311 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7312 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7314 // For GCC/MS compatibility, other qualifier mismatches are treated
7315 // as still compatible in C.
7316 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7319 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7320 // incomplete type and the other is a pointer to a qualified or unqualified
7321 // version of void...
7322 if (lhptee->isVoidType()) {
7323 if (rhptee->isIncompleteOrObjectType())
7326 // As an extension, we allow cast to/from void* to function pointer.
7327 assert(rhptee->isFunctionType());
7328 return Sema::FunctionVoidPointer;
7331 if (rhptee->isVoidType()) {
7332 if (lhptee->isIncompleteOrObjectType())
7335 // As an extension, we allow cast to/from void* to function pointer.
7336 assert(lhptee->isFunctionType());
7337 return Sema::FunctionVoidPointer;
7340 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7341 // unqualified versions of compatible types, ...
7342 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7343 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7344 // Check if the pointee types are compatible ignoring the sign.
7345 // We explicitly check for char so that we catch "char" vs
7346 // "unsigned char" on systems where "char" is unsigned.
7347 if (lhptee->isCharType())
7348 ltrans = S.Context.UnsignedCharTy;
7349 else if (lhptee->hasSignedIntegerRepresentation())
7350 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7352 if (rhptee->isCharType())
7353 rtrans = S.Context.UnsignedCharTy;
7354 else if (rhptee->hasSignedIntegerRepresentation())
7355 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7357 if (ltrans == rtrans) {
7358 // Types are compatible ignoring the sign. Qualifier incompatibility
7359 // takes priority over sign incompatibility because the sign
7360 // warning can be disabled.
7361 if (ConvTy != Sema::Compatible)
7364 return Sema::IncompatiblePointerSign;
7367 // If we are a multi-level pointer, it's possible that our issue is simply
7368 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7369 // the eventual target type is the same and the pointers have the same
7370 // level of indirection, this must be the issue.
7371 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7373 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7374 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7375 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7377 if (lhptee == rhptee)
7378 return Sema::IncompatibleNestedPointerQualifiers;
7381 // General pointer incompatibility takes priority over qualifiers.
7382 return Sema::IncompatiblePointer;
7384 if (!S.getLangOpts().CPlusPlus &&
7385 S.IsFunctionConversion(ltrans, rtrans, ltrans))
7386 return Sema::IncompatiblePointer;
7390 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7391 /// block pointer types are compatible or whether a block and normal pointer
7392 /// are compatible. It is more restrict than comparing two function pointer
7394 static Sema::AssignConvertType
7395 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7397 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7398 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7400 QualType lhptee, rhptee;
7402 // get the "pointed to" type (ignoring qualifiers at the top level)
7403 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7404 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7406 // In C++, the types have to match exactly.
7407 if (S.getLangOpts().CPlusPlus)
7408 return Sema::IncompatibleBlockPointer;
7410 Sema::AssignConvertType ConvTy = Sema::Compatible;
7412 // For blocks we enforce that qualifiers are identical.
7413 Qualifiers LQuals = lhptee.getLocalQualifiers();
7414 Qualifiers RQuals = rhptee.getLocalQualifiers();
7415 if (S.getLangOpts().OpenCL) {
7416 LQuals.removeAddressSpace();
7417 RQuals.removeAddressSpace();
7419 if (LQuals != RQuals)
7420 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7422 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7424 // The current behavior is similar to C++ lambdas. A block might be
7425 // assigned to a variable iff its return type and parameters are compatible
7426 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7427 // an assignment. Presumably it should behave in way that a function pointer
7428 // assignment does in C, so for each parameter and return type:
7429 // * CVR and address space of LHS should be a superset of CVR and address
7431 // * unqualified types should be compatible.
7432 if (S.getLangOpts().OpenCL) {
7433 if (!S.Context.typesAreBlockPointerCompatible(
7434 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7435 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7436 return Sema::IncompatibleBlockPointer;
7437 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7438 return Sema::IncompatibleBlockPointer;
7443 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7444 /// for assignment compatibility.
7445 static Sema::AssignConvertType
7446 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7448 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7449 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7451 if (LHSType->isObjCBuiltinType()) {
7452 // Class is not compatible with ObjC object pointers.
7453 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7454 !RHSType->isObjCQualifiedClassType())
7455 return Sema::IncompatiblePointer;
7456 return Sema::Compatible;
7458 if (RHSType->isObjCBuiltinType()) {
7459 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7460 !LHSType->isObjCQualifiedClassType())
7461 return Sema::IncompatiblePointer;
7462 return Sema::Compatible;
7464 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7465 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7467 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7468 // make an exception for id<P>
7469 !LHSType->isObjCQualifiedIdType())
7470 return Sema::CompatiblePointerDiscardsQualifiers;
7472 if (S.Context.typesAreCompatible(LHSType, RHSType))
7473 return Sema::Compatible;
7474 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7475 return Sema::IncompatibleObjCQualifiedId;
7476 return Sema::IncompatiblePointer;
7479 Sema::AssignConvertType
7480 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7481 QualType LHSType, QualType RHSType) {
7482 // Fake up an opaque expression. We don't actually care about what
7483 // cast operations are required, so if CheckAssignmentConstraints
7484 // adds casts to this they'll be wasted, but fortunately that doesn't
7485 // usually happen on valid code.
7486 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7487 ExprResult RHSPtr = &RHSExpr;
7488 CastKind K = CK_Invalid;
7490 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7493 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7494 /// has code to accommodate several GCC extensions when type checking
7495 /// pointers. Here are some objectionable examples that GCC considers warnings:
7499 /// struct foo *pfoo;
7501 /// pint = pshort; // warning: assignment from incompatible pointer type
7502 /// a = pint; // warning: assignment makes integer from pointer without a cast
7503 /// pint = a; // warning: assignment makes pointer from integer without a cast
7504 /// pint = pfoo; // warning: assignment from incompatible pointer type
7506 /// As a result, the code for dealing with pointers is more complex than the
7507 /// C99 spec dictates.
7509 /// Sets 'Kind' for any result kind except Incompatible.
7510 Sema::AssignConvertType
7511 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7512 CastKind &Kind, bool ConvertRHS) {
7513 QualType RHSType = RHS.get()->getType();
7514 QualType OrigLHSType = LHSType;
7516 // Get canonical types. We're not formatting these types, just comparing
7518 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7519 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7521 // Common case: no conversion required.
7522 if (LHSType == RHSType) {
7527 // If we have an atomic type, try a non-atomic assignment, then just add an
7528 // atomic qualification step.
7529 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7530 Sema::AssignConvertType result =
7531 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7532 if (result != Compatible)
7534 if (Kind != CK_NoOp && ConvertRHS)
7535 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7536 Kind = CK_NonAtomicToAtomic;
7540 // If the left-hand side is a reference type, then we are in a
7541 // (rare!) case where we've allowed the use of references in C,
7542 // e.g., as a parameter type in a built-in function. In this case,
7543 // just make sure that the type referenced is compatible with the
7544 // right-hand side type. The caller is responsible for adjusting
7545 // LHSType so that the resulting expression does not have reference
7547 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7548 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7549 Kind = CK_LValueBitCast;
7552 return Incompatible;
7555 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7556 // to the same ExtVector type.
7557 if (LHSType->isExtVectorType()) {
7558 if (RHSType->isExtVectorType())
7559 return Incompatible;
7560 if (RHSType->isArithmeticType()) {
7561 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7563 RHS = prepareVectorSplat(LHSType, RHS.get());
7564 Kind = CK_VectorSplat;
7569 // Conversions to or from vector type.
7570 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7571 if (LHSType->isVectorType() && RHSType->isVectorType()) {
7572 // Allow assignments of an AltiVec vector type to an equivalent GCC
7573 // vector type and vice versa
7574 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7579 // If we are allowing lax vector conversions, and LHS and RHS are both
7580 // vectors, the total size only needs to be the same. This is a bitcast;
7581 // no bits are changed but the result type is different.
7582 if (isLaxVectorConversion(RHSType, LHSType)) {
7584 return IncompatibleVectors;
7588 // When the RHS comes from another lax conversion (e.g. binops between
7589 // scalars and vectors) the result is canonicalized as a vector. When the
7590 // LHS is also a vector, the lax is allowed by the condition above. Handle
7591 // the case where LHS is a scalar.
7592 if (LHSType->isScalarType()) {
7593 const VectorType *VecType = RHSType->getAs<VectorType>();
7594 if (VecType && VecType->getNumElements() == 1 &&
7595 isLaxVectorConversion(RHSType, LHSType)) {
7596 ExprResult *VecExpr = &RHS;
7597 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7603 return Incompatible;
7606 // Diagnose attempts to convert between __float128 and long double where
7607 // such conversions currently can't be handled.
7608 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7609 return Incompatible;
7611 // Arithmetic conversions.
7612 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7613 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7615 Kind = PrepareScalarCast(RHS, LHSType);
7619 // Conversions to normal pointers.
7620 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7622 if (isa<PointerType>(RHSType)) {
7623 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7624 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7625 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7626 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7630 if (RHSType->isIntegerType()) {
7631 Kind = CK_IntegralToPointer; // FIXME: null?
7632 return IntToPointer;
7635 // C pointers are not compatible with ObjC object pointers,
7636 // with two exceptions:
7637 if (isa<ObjCObjectPointerType>(RHSType)) {
7638 // - conversions to void*
7639 if (LHSPointer->getPointeeType()->isVoidType()) {
7644 // - conversions from 'Class' to the redefinition type
7645 if (RHSType->isObjCClassType() &&
7646 Context.hasSameType(LHSType,
7647 Context.getObjCClassRedefinitionType())) {
7653 return IncompatiblePointer;
7657 if (RHSType->getAs<BlockPointerType>()) {
7658 if (LHSPointer->getPointeeType()->isVoidType()) {
7659 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7660 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7664 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7669 return Incompatible;
7672 // Conversions to block pointers.
7673 if (isa<BlockPointerType>(LHSType)) {
7675 if (RHSType->isBlockPointerType()) {
7676 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7679 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7682 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7683 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7686 // int or null -> T^
7687 if (RHSType->isIntegerType()) {
7688 Kind = CK_IntegralToPointer; // FIXME: null
7689 return IntToBlockPointer;
7693 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7694 Kind = CK_AnyPointerToBlockPointerCast;
7699 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7700 if (RHSPT->getPointeeType()->isVoidType()) {
7701 Kind = CK_AnyPointerToBlockPointerCast;
7705 return Incompatible;
7708 // Conversions to Objective-C pointers.
7709 if (isa<ObjCObjectPointerType>(LHSType)) {
7711 if (RHSType->isObjCObjectPointerType()) {
7713 Sema::AssignConvertType result =
7714 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7715 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7716 result == Compatible &&
7717 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7718 result = IncompatibleObjCWeakRef;
7722 // int or null -> A*
7723 if (RHSType->isIntegerType()) {
7724 Kind = CK_IntegralToPointer; // FIXME: null
7725 return IntToPointer;
7728 // In general, C pointers are not compatible with ObjC object pointers,
7729 // with two exceptions:
7730 if (isa<PointerType>(RHSType)) {
7731 Kind = CK_CPointerToObjCPointerCast;
7733 // - conversions from 'void*'
7734 if (RHSType->isVoidPointerType()) {
7738 // - conversions to 'Class' from its redefinition type
7739 if (LHSType->isObjCClassType() &&
7740 Context.hasSameType(RHSType,
7741 Context.getObjCClassRedefinitionType())) {
7745 return IncompatiblePointer;
7748 // Only under strict condition T^ is compatible with an Objective-C pointer.
7749 if (RHSType->isBlockPointerType() &&
7750 LHSType->isBlockCompatibleObjCPointerType(Context)) {
7752 maybeExtendBlockObject(RHS);
7753 Kind = CK_BlockPointerToObjCPointerCast;
7757 return Incompatible;
7760 // Conversions from pointers that are not covered by the above.
7761 if (isa<PointerType>(RHSType)) {
7763 if (LHSType == Context.BoolTy) {
7764 Kind = CK_PointerToBoolean;
7769 if (LHSType->isIntegerType()) {
7770 Kind = CK_PointerToIntegral;
7771 return PointerToInt;
7774 return Incompatible;
7777 // Conversions from Objective-C pointers that are not covered by the above.
7778 if (isa<ObjCObjectPointerType>(RHSType)) {
7780 if (LHSType == Context.BoolTy) {
7781 Kind = CK_PointerToBoolean;
7786 if (LHSType->isIntegerType()) {
7787 Kind = CK_PointerToIntegral;
7788 return PointerToInt;
7791 return Incompatible;
7794 // struct A -> struct B
7795 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7796 if (Context.typesAreCompatible(LHSType, RHSType)) {
7802 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7803 Kind = CK_IntToOCLSampler;
7807 return Incompatible;
7810 /// \brief Constructs a transparent union from an expression that is
7811 /// used to initialize the transparent union.
7812 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7813 ExprResult &EResult, QualType UnionType,
7815 // Build an initializer list that designates the appropriate member
7816 // of the transparent union.
7817 Expr *E = EResult.get();
7818 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7819 E, SourceLocation());
7820 Initializer->setType(UnionType);
7821 Initializer->setInitializedFieldInUnion(Field);
7823 // Build a compound literal constructing a value of the transparent
7824 // union type from this initializer list.
7825 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7826 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7827 VK_RValue, Initializer, false);
7830 Sema::AssignConvertType
7831 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7833 QualType RHSType = RHS.get()->getType();
7835 // If the ArgType is a Union type, we want to handle a potential
7836 // transparent_union GCC extension.
7837 const RecordType *UT = ArgType->getAsUnionType();
7838 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7839 return Incompatible;
7841 // The field to initialize within the transparent union.
7842 RecordDecl *UD = UT->getDecl();
7843 FieldDecl *InitField = nullptr;
7844 // It's compatible if the expression matches any of the fields.
7845 for (auto *it : UD->fields()) {
7846 if (it->getType()->isPointerType()) {
7847 // If the transparent union contains a pointer type, we allow:
7849 // 2) null pointer constant
7850 if (RHSType->isPointerType())
7851 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7852 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7857 if (RHS.get()->isNullPointerConstant(Context,
7858 Expr::NPC_ValueDependentIsNull)) {
7859 RHS = ImpCastExprToType(RHS.get(), it->getType(),
7866 CastKind Kind = CK_Invalid;
7867 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7869 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7876 return Incompatible;
7878 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7882 Sema::AssignConvertType
7883 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7885 bool DiagnoseCFAudited,
7887 // We need to be able to tell the caller whether we diagnosed a problem, if
7888 // they ask us to issue diagnostics.
7889 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7891 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7892 // we can't avoid *all* modifications at the moment, so we need some somewhere
7893 // to put the updated value.
7894 ExprResult LocalRHS = CallerRHS;
7895 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7897 if (getLangOpts().CPlusPlus) {
7898 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7899 // C++ 5.17p3: If the left operand is not of class type, the
7900 // expression is implicitly converted (C++ 4) to the
7901 // cv-unqualified type of the left operand.
7902 QualType RHSType = RHS.get()->getType();
7904 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7907 ImplicitConversionSequence ICS =
7908 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7909 /*SuppressUserConversions=*/false,
7910 /*AllowExplicit=*/false,
7911 /*InOverloadResolution=*/false,
7913 /*AllowObjCWritebackConversion=*/false);
7914 if (ICS.isFailure())
7915 return Incompatible;
7916 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7919 if (RHS.isInvalid())
7920 return Incompatible;
7921 Sema::AssignConvertType result = Compatible;
7922 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7923 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7924 result = IncompatibleObjCWeakRef;
7928 // FIXME: Currently, we fall through and treat C++ classes like C
7930 // FIXME: We also fall through for atomics; not sure what should
7931 // happen there, though.
7932 } else if (RHS.get()->getType() == Context.OverloadTy) {
7933 // As a set of extensions to C, we support overloading on functions. These
7934 // functions need to be resolved here.
7936 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7937 RHS.get(), LHSType, /*Complain=*/false, DAP))
7938 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7940 return Incompatible;
7943 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7944 // a null pointer constant.
7945 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7946 LHSType->isBlockPointerType()) &&
7947 RHS.get()->isNullPointerConstant(Context,
7948 Expr::NPC_ValueDependentIsNull)) {
7949 if (Diagnose || ConvertRHS) {
7952 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7953 /*IgnoreBaseAccess=*/false, Diagnose);
7955 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7960 // This check seems unnatural, however it is necessary to ensure the proper
7961 // conversion of functions/arrays. If the conversion were done for all
7962 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7963 // expressions that suppress this implicit conversion (&, sizeof).
7965 // Suppress this for references: C++ 8.5.3p5.
7966 if (!LHSType->isReferenceType()) {
7967 // FIXME: We potentially allocate here even if ConvertRHS is false.
7968 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7969 if (RHS.isInvalid())
7970 return Incompatible;
7973 Expr *PRE = RHS.get()->IgnoreParenCasts();
7974 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7975 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7976 if (PDecl && !PDecl->hasDefinition()) {
7977 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7978 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7982 CastKind Kind = CK_Invalid;
7983 Sema::AssignConvertType result =
7984 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7986 // C99 6.5.16.1p2: The value of the right operand is converted to the
7987 // type of the assignment expression.
7988 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7989 // so that we can use references in built-in functions even in C.
7990 // The getNonReferenceType() call makes sure that the resulting expression
7991 // does not have reference type.
7992 if (result != Incompatible && RHS.get()->getType() != LHSType) {
7993 QualType Ty = LHSType.getNonLValueExprType(Context);
7994 Expr *E = RHS.get();
7996 // Check for various Objective-C errors. If we are not reporting
7997 // diagnostics and just checking for errors, e.g., during overload
7998 // resolution, return Incompatible to indicate the failure.
7999 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8000 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8001 Diagnose, DiagnoseCFAudited) != ACR_okay) {
8003 return Incompatible;
8005 if (getLangOpts().ObjC1 &&
8006 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8007 E->getType(), E, Diagnose) ||
8008 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8010 return Incompatible;
8011 // Replace the expression with a corrected version and continue so we
8012 // can find further errors.
8018 RHS = ImpCastExprToType(E, Ty, Kind);
8023 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8025 Diag(Loc, diag::err_typecheck_invalid_operands)
8026 << LHS.get()->getType() << RHS.get()->getType()
8027 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8031 /// Try to convert a value of non-vector type to a vector type by converting
8032 /// the type to the element type of the vector and then performing a splat.
8033 /// If the language is OpenCL, we only use conversions that promote scalar
8034 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8037 /// \param scalar - if non-null, actually perform the conversions
8038 /// \return true if the operation fails (but without diagnosing the failure)
8039 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8041 QualType vectorEltTy,
8042 QualType vectorTy) {
8043 // The conversion to apply to the scalar before splatting it,
8045 CastKind scalarCast = CK_Invalid;
8047 if (vectorEltTy->isIntegralType(S.Context)) {
8048 if (!scalarTy->isIntegralType(S.Context))
8050 if (S.getLangOpts().OpenCL &&
8051 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8053 scalarCast = CK_IntegralCast;
8054 } else if (vectorEltTy->isRealFloatingType()) {
8055 if (scalarTy->isRealFloatingType()) {
8056 if (S.getLangOpts().OpenCL &&
8057 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8059 scalarCast = CK_FloatingCast;
8061 else if (scalarTy->isIntegralType(S.Context))
8062 scalarCast = CK_IntegralToFloating;
8069 // Adjust scalar if desired.
8071 if (scalarCast != CK_Invalid)
8072 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8073 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8078 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8079 SourceLocation Loc, bool IsCompAssign,
8081 bool AllowBoolConversions) {
8082 if (!IsCompAssign) {
8083 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8084 if (LHS.isInvalid())
8087 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8088 if (RHS.isInvalid())
8091 // For conversion purposes, we ignore any qualifiers.
8092 // For example, "const float" and "float" are equivalent.
8093 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8094 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8096 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8097 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8098 assert(LHSVecType || RHSVecType);
8100 // AltiVec-style "vector bool op vector bool" combinations are allowed
8101 // for some operators but not others.
8102 if (!AllowBothBool &&
8103 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8104 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8105 return InvalidOperands(Loc, LHS, RHS);
8107 // If the vector types are identical, return.
8108 if (Context.hasSameType(LHSType, RHSType))
8111 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8112 if (LHSVecType && RHSVecType &&
8113 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8114 if (isa<ExtVectorType>(LHSVecType)) {
8115 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8120 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8124 // AllowBoolConversions says that bool and non-bool AltiVec vectors
8125 // can be mixed, with the result being the non-bool type. The non-bool
8126 // operand must have integer element type.
8127 if (AllowBoolConversions && LHSVecType && RHSVecType &&
8128 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8129 (Context.getTypeSize(LHSVecType->getElementType()) ==
8130 Context.getTypeSize(RHSVecType->getElementType()))) {
8131 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8132 LHSVecType->getElementType()->isIntegerType() &&
8133 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8134 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8137 if (!IsCompAssign &&
8138 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8139 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8140 RHSVecType->getElementType()->isIntegerType()) {
8141 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8146 // If there's an ext-vector type and a scalar, try to convert the scalar to
8147 // the vector element type and splat.
8148 // FIXME: this should also work for regular vector types as supported in GCC.
8149 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8150 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8151 LHSVecType->getElementType(), LHSType))
8154 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8155 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8156 LHSType, RHSVecType->getElementType(),
8161 // FIXME: The code below also handles conversion between vectors and
8162 // non-scalars, we should break this down into fine grained specific checks
8163 // and emit proper diagnostics.
8164 QualType VecType = LHSVecType ? LHSType : RHSType;
8165 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8166 QualType OtherType = LHSVecType ? RHSType : LHSType;
8167 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8168 if (isLaxVectorConversion(OtherType, VecType)) {
8169 // If we're allowing lax vector conversions, only the total (data) size
8170 // needs to be the same. For non compound assignment, if one of the types is
8171 // scalar, the result is always the vector type.
8172 if (!IsCompAssign) {
8173 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8175 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8176 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8177 // type. Note that this is already done by non-compound assignments in
8178 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8179 // <1 x T> -> T. The result is also a vector type.
8180 } else if (OtherType->isExtVectorType() ||
8181 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8182 ExprResult *RHSExpr = &RHS;
8183 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8188 // Okay, the expression is invalid.
8190 // If there's a non-vector, non-real operand, diagnose that.
8191 if ((!RHSVecType && !RHSType->isRealType()) ||
8192 (!LHSVecType && !LHSType->isRealType())) {
8193 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8194 << LHSType << RHSType
8195 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8199 // OpenCL V1.1 6.2.6.p1:
8200 // If the operands are of more than one vector type, then an error shall
8201 // occur. Implicit conversions between vector types are not permitted, per
8203 if (getLangOpts().OpenCL &&
8204 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8205 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8206 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8211 // Otherwise, use the generic diagnostic.
8212 Diag(Loc, diag::err_typecheck_vector_not_convertable)
8213 << LHSType << RHSType
8214 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8218 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8219 // expression. These are mainly cases where the null pointer is used as an
8220 // integer instead of a pointer.
8221 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8222 SourceLocation Loc, bool IsCompare) {
8223 // The canonical way to check for a GNU null is with isNullPointerConstant,
8224 // but we use a bit of a hack here for speed; this is a relatively
8225 // hot path, and isNullPointerConstant is slow.
8226 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8227 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8229 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8231 // Avoid analyzing cases where the result will either be invalid (and
8232 // diagnosed as such) or entirely valid and not something to warn about.
8233 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8234 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8237 // Comparison operations would not make sense with a null pointer no matter
8238 // what the other expression is.
8240 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8241 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8242 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8246 // The rest of the operations only make sense with a null pointer
8247 // if the other expression is a pointer.
8248 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8249 NonNullType->canDecayToPointerType())
8252 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8253 << LHSNull /* LHS is NULL */ << NonNullType
8254 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8257 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8259 SourceLocation Loc, bool IsDiv) {
8260 // Check for division/remainder by zero.
8261 llvm::APSInt RHSValue;
8262 if (!RHS.get()->isValueDependent() &&
8263 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8264 S.DiagRuntimeBehavior(Loc, RHS.get(),
8265 S.PDiag(diag::warn_remainder_division_by_zero)
8266 << IsDiv << RHS.get()->getSourceRange());
8269 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8271 bool IsCompAssign, bool IsDiv) {
8272 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8274 if (LHS.get()->getType()->isVectorType() ||
8275 RHS.get()->getType()->isVectorType())
8276 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8277 /*AllowBothBool*/getLangOpts().AltiVec,
8278 /*AllowBoolConversions*/false);
8280 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8281 if (LHS.isInvalid() || RHS.isInvalid())
8285 if (compType.isNull() || !compType->isArithmeticType())
8286 return InvalidOperands(Loc, LHS, RHS);
8288 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8292 QualType Sema::CheckRemainderOperands(
8293 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8294 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8296 if (LHS.get()->getType()->isVectorType() ||
8297 RHS.get()->getType()->isVectorType()) {
8298 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8299 RHS.get()->getType()->hasIntegerRepresentation())
8300 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8301 /*AllowBothBool*/getLangOpts().AltiVec,
8302 /*AllowBoolConversions*/false);
8303 return InvalidOperands(Loc, LHS, RHS);
8306 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8307 if (LHS.isInvalid() || RHS.isInvalid())
8310 if (compType.isNull() || !compType->isIntegerType())
8311 return InvalidOperands(Loc, LHS, RHS);
8312 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8316 /// \brief Diagnose invalid arithmetic on two void pointers.
8317 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8318 Expr *LHSExpr, Expr *RHSExpr) {
8319 S.Diag(Loc, S.getLangOpts().CPlusPlus
8320 ? diag::err_typecheck_pointer_arith_void_type
8321 : diag::ext_gnu_void_ptr)
8322 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8323 << RHSExpr->getSourceRange();
8326 /// \brief Diagnose invalid arithmetic on a void pointer.
8327 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8329 S.Diag(Loc, S.getLangOpts().CPlusPlus
8330 ? diag::err_typecheck_pointer_arith_void_type
8331 : diag::ext_gnu_void_ptr)
8332 << 0 /* one pointer */ << Pointer->getSourceRange();
8335 /// \brief Diagnose invalid arithmetic on two function pointers.
8336 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8337 Expr *LHS, Expr *RHS) {
8338 assert(LHS->getType()->isAnyPointerType());
8339 assert(RHS->getType()->isAnyPointerType());
8340 S.Diag(Loc, S.getLangOpts().CPlusPlus
8341 ? diag::err_typecheck_pointer_arith_function_type
8342 : diag::ext_gnu_ptr_func_arith)
8343 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8344 // We only show the second type if it differs from the first.
8345 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8347 << RHS->getType()->getPointeeType()
8348 << LHS->getSourceRange() << RHS->getSourceRange();
8351 /// \brief Diagnose invalid arithmetic on a function pointer.
8352 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8354 assert(Pointer->getType()->isAnyPointerType());
8355 S.Diag(Loc, S.getLangOpts().CPlusPlus
8356 ? diag::err_typecheck_pointer_arith_function_type
8357 : diag::ext_gnu_ptr_func_arith)
8358 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8359 << 0 /* one pointer, so only one type */
8360 << Pointer->getSourceRange();
8363 /// \brief Emit error if Operand is incomplete pointer type
8365 /// \returns True if pointer has incomplete type
8366 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8368 QualType ResType = Operand->getType();
8369 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8370 ResType = ResAtomicType->getValueType();
8372 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8373 QualType PointeeTy = ResType->getPointeeType();
8374 return S.RequireCompleteType(Loc, PointeeTy,
8375 diag::err_typecheck_arithmetic_incomplete_type,
8376 PointeeTy, Operand->getSourceRange());
8379 /// \brief Check the validity of an arithmetic pointer operand.
8381 /// If the operand has pointer type, this code will check for pointer types
8382 /// which are invalid in arithmetic operations. These will be diagnosed
8383 /// appropriately, including whether or not the use is supported as an
8386 /// \returns True when the operand is valid to use (even if as an extension).
8387 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8389 QualType ResType = Operand->getType();
8390 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8391 ResType = ResAtomicType->getValueType();
8393 if (!ResType->isAnyPointerType()) return true;
8395 QualType PointeeTy = ResType->getPointeeType();
8396 if (PointeeTy->isVoidType()) {
8397 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8398 return !S.getLangOpts().CPlusPlus;
8400 if (PointeeTy->isFunctionType()) {
8401 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8402 return !S.getLangOpts().CPlusPlus;
8405 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8410 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8413 /// This routine will diagnose any invalid arithmetic on pointer operands much
8414 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8415 /// for emitting a single diagnostic even for operations where both LHS and RHS
8416 /// are (potentially problematic) pointers.
8418 /// \returns True when the operand is valid to use (even if as an extension).
8419 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8420 Expr *LHSExpr, Expr *RHSExpr) {
8421 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8422 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8423 if (!isLHSPointer && !isRHSPointer) return true;
8425 QualType LHSPointeeTy, RHSPointeeTy;
8426 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8427 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8429 // if both are pointers check if operation is valid wrt address spaces
8430 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8431 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8432 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8433 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8435 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8436 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8437 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8442 // Check for arithmetic on pointers to incomplete types.
8443 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8444 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8445 if (isLHSVoidPtr || isRHSVoidPtr) {
8446 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8447 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8448 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8450 return !S.getLangOpts().CPlusPlus;
8453 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8454 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8455 if (isLHSFuncPtr || isRHSFuncPtr) {
8456 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8457 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8459 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8461 return !S.getLangOpts().CPlusPlus;
8464 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8466 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8472 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8474 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8475 Expr *LHSExpr, Expr *RHSExpr) {
8476 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8477 Expr* IndexExpr = RHSExpr;
8479 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8480 IndexExpr = LHSExpr;
8483 bool IsStringPlusInt = StrExpr &&
8484 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8485 if (!IsStringPlusInt || IndexExpr->isValueDependent())
8489 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8490 unsigned StrLenWithNull = StrExpr->getLength() + 1;
8491 if (index.isNonNegative() &&
8492 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8493 index.isUnsigned()))
8497 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8498 Self.Diag(OpLoc, diag::warn_string_plus_int)
8499 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8501 // Only print a fixit for "str" + int, not for int + "str".
8502 if (IndexExpr == RHSExpr) {
8503 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8504 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8505 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8506 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8507 << FixItHint::CreateInsertion(EndLoc, "]");
8509 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8512 /// \brief Emit a warning when adding a char literal to a string.
8513 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8514 Expr *LHSExpr, Expr *RHSExpr) {
8515 const Expr *StringRefExpr = LHSExpr;
8516 const CharacterLiteral *CharExpr =
8517 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8520 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8521 StringRefExpr = RHSExpr;
8524 if (!CharExpr || !StringRefExpr)
8527 const QualType StringType = StringRefExpr->getType();
8529 // Return if not a PointerType.
8530 if (!StringType->isAnyPointerType())
8533 // Return if not a CharacterType.
8534 if (!StringType->getPointeeType()->isAnyCharacterType())
8537 ASTContext &Ctx = Self.getASTContext();
8538 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8540 const QualType CharType = CharExpr->getType();
8541 if (!CharType->isAnyCharacterType() &&
8542 CharType->isIntegerType() &&
8543 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8544 Self.Diag(OpLoc, diag::warn_string_plus_char)
8545 << DiagRange << Ctx.CharTy;
8547 Self.Diag(OpLoc, diag::warn_string_plus_char)
8548 << DiagRange << CharExpr->getType();
8551 // Only print a fixit for str + char, not for char + str.
8552 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8553 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8554 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8555 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8556 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8557 << FixItHint::CreateInsertion(EndLoc, "]");
8559 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8563 /// \brief Emit error when two pointers are incompatible.
8564 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8565 Expr *LHSExpr, Expr *RHSExpr) {
8566 assert(LHSExpr->getType()->isAnyPointerType());
8567 assert(RHSExpr->getType()->isAnyPointerType());
8568 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8569 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8570 << RHSExpr->getSourceRange();
8574 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8575 SourceLocation Loc, BinaryOperatorKind Opc,
8576 QualType* CompLHSTy) {
8577 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8579 if (LHS.get()->getType()->isVectorType() ||
8580 RHS.get()->getType()->isVectorType()) {
8581 QualType compType = CheckVectorOperands(
8582 LHS, RHS, Loc, CompLHSTy,
8583 /*AllowBothBool*/getLangOpts().AltiVec,
8584 /*AllowBoolConversions*/getLangOpts().ZVector);
8585 if (CompLHSTy) *CompLHSTy = compType;
8589 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8590 if (LHS.isInvalid() || RHS.isInvalid())
8593 // Diagnose "string literal" '+' int and string '+' "char literal".
8594 if (Opc == BO_Add) {
8595 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8596 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8599 // handle the common case first (both operands are arithmetic).
8600 if (!compType.isNull() && compType->isArithmeticType()) {
8601 if (CompLHSTy) *CompLHSTy = compType;
8605 // Type-checking. Ultimately the pointer's going to be in PExp;
8606 // note that we bias towards the LHS being the pointer.
8607 Expr *PExp = LHS.get(), *IExp = RHS.get();
8610 if (PExp->getType()->isPointerType()) {
8611 isObjCPointer = false;
8612 } else if (PExp->getType()->isObjCObjectPointerType()) {
8613 isObjCPointer = true;
8615 std::swap(PExp, IExp);
8616 if (PExp->getType()->isPointerType()) {
8617 isObjCPointer = false;
8618 } else if (PExp->getType()->isObjCObjectPointerType()) {
8619 isObjCPointer = true;
8621 return InvalidOperands(Loc, LHS, RHS);
8624 assert(PExp->getType()->isAnyPointerType());
8626 if (!IExp->getType()->isIntegerType())
8627 return InvalidOperands(Loc, LHS, RHS);
8629 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8632 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8635 // Check array bounds for pointer arithemtic
8636 CheckArrayAccess(PExp, IExp);
8639 QualType LHSTy = Context.isPromotableBitField(LHS.get());
8640 if (LHSTy.isNull()) {
8641 LHSTy = LHS.get()->getType();
8642 if (LHSTy->isPromotableIntegerType())
8643 LHSTy = Context.getPromotedIntegerType(LHSTy);
8648 return PExp->getType();
8652 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8654 QualType* CompLHSTy) {
8655 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8657 if (LHS.get()->getType()->isVectorType() ||
8658 RHS.get()->getType()->isVectorType()) {
8659 QualType compType = CheckVectorOperands(
8660 LHS, RHS, Loc, CompLHSTy,
8661 /*AllowBothBool*/getLangOpts().AltiVec,
8662 /*AllowBoolConversions*/getLangOpts().ZVector);
8663 if (CompLHSTy) *CompLHSTy = compType;
8667 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8668 if (LHS.isInvalid() || RHS.isInvalid())
8671 // Enforce type constraints: C99 6.5.6p3.
8673 // Handle the common case first (both operands are arithmetic).
8674 if (!compType.isNull() && compType->isArithmeticType()) {
8675 if (CompLHSTy) *CompLHSTy = compType;
8679 // Either ptr - int or ptr - ptr.
8680 if (LHS.get()->getType()->isAnyPointerType()) {
8681 QualType lpointee = LHS.get()->getType()->getPointeeType();
8683 // Diagnose bad cases where we step over interface counts.
8684 if (LHS.get()->getType()->isObjCObjectPointerType() &&
8685 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8688 // The result type of a pointer-int computation is the pointer type.
8689 if (RHS.get()->getType()->isIntegerType()) {
8690 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8693 // Check array bounds for pointer arithemtic
8694 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8695 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8697 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8698 return LHS.get()->getType();
8701 // Handle pointer-pointer subtractions.
8702 if (const PointerType *RHSPTy
8703 = RHS.get()->getType()->getAs<PointerType>()) {
8704 QualType rpointee = RHSPTy->getPointeeType();
8706 if (getLangOpts().CPlusPlus) {
8707 // Pointee types must be the same: C++ [expr.add]
8708 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8709 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8712 // Pointee types must be compatible C99 6.5.6p3
8713 if (!Context.typesAreCompatible(
8714 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8715 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8716 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8721 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8722 LHS.get(), RHS.get()))
8725 // The pointee type may have zero size. As an extension, a structure or
8726 // union may have zero size or an array may have zero length. In this
8727 // case subtraction does not make sense.
8728 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8729 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8730 if (ElementSize.isZero()) {
8731 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8732 << rpointee.getUnqualifiedType()
8733 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8737 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8738 return Context.getPointerDiffType();
8742 return InvalidOperands(Loc, LHS, RHS);
8745 static bool isScopedEnumerationType(QualType T) {
8746 if (const EnumType *ET = T->getAs<EnumType>())
8747 return ET->getDecl()->isScoped();
8751 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8752 SourceLocation Loc, BinaryOperatorKind Opc,
8754 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8755 // so skip remaining warnings as we don't want to modify values within Sema.
8756 if (S.getLangOpts().OpenCL)
8760 // Check right/shifter operand
8761 if (RHS.get()->isValueDependent() ||
8762 !RHS.get()->EvaluateAsInt(Right, S.Context))
8765 if (Right.isNegative()) {
8766 S.DiagRuntimeBehavior(Loc, RHS.get(),
8767 S.PDiag(diag::warn_shift_negative)
8768 << RHS.get()->getSourceRange());
8771 llvm::APInt LeftBits(Right.getBitWidth(),
8772 S.Context.getTypeSize(LHS.get()->getType()));
8773 if (Right.uge(LeftBits)) {
8774 S.DiagRuntimeBehavior(Loc, RHS.get(),
8775 S.PDiag(diag::warn_shift_gt_typewidth)
8776 << RHS.get()->getSourceRange());
8782 // When left shifting an ICE which is signed, we can check for overflow which
8783 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8784 // integers have defined behavior modulo one more than the maximum value
8785 // representable in the result type, so never warn for those.
8787 if (LHS.get()->isValueDependent() ||
8788 LHSType->hasUnsignedIntegerRepresentation() ||
8789 !LHS.get()->EvaluateAsInt(Left, S.Context))
8792 // If LHS does not have a signed type and non-negative value
8793 // then, the behavior is undefined. Warn about it.
8794 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8795 S.DiagRuntimeBehavior(Loc, LHS.get(),
8796 S.PDiag(diag::warn_shift_lhs_negative)
8797 << LHS.get()->getSourceRange());
8801 llvm::APInt ResultBits =
8802 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8803 if (LeftBits.uge(ResultBits))
8805 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8806 Result = Result.shl(Right);
8808 // Print the bit representation of the signed integer as an unsigned
8809 // hexadecimal number.
8810 SmallString<40> HexResult;
8811 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8813 // If we are only missing a sign bit, this is less likely to result in actual
8814 // bugs -- if the result is cast back to an unsigned type, it will have the
8815 // expected value. Thus we place this behind a different warning that can be
8816 // turned off separately if needed.
8817 if (LeftBits == ResultBits - 1) {
8818 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8819 << HexResult << LHSType
8820 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8824 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8825 << HexResult.str() << Result.getMinSignedBits() << LHSType
8826 << Left.getBitWidth() << LHS.get()->getSourceRange()
8827 << RHS.get()->getSourceRange();
8830 /// \brief Return the resulting type when a vector is shifted
8831 /// by a scalar or vector shift amount.
8832 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8833 SourceLocation Loc, bool IsCompAssign) {
8834 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8835 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8836 !LHS.get()->getType()->isVectorType()) {
8837 S.Diag(Loc, diag::err_shift_rhs_only_vector)
8838 << RHS.get()->getType() << LHS.get()->getType()
8839 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8843 if (!IsCompAssign) {
8844 LHS = S.UsualUnaryConversions(LHS.get());
8845 if (LHS.isInvalid()) return QualType();
8848 RHS = S.UsualUnaryConversions(RHS.get());
8849 if (RHS.isInvalid()) return QualType();
8851 QualType LHSType = LHS.get()->getType();
8852 // Note that LHS might be a scalar because the routine calls not only in
8854 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8855 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8857 // Note that RHS might not be a vector.
8858 QualType RHSType = RHS.get()->getType();
8859 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8860 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8862 // The operands need to be integers.
8863 if (!LHSEleType->isIntegerType()) {
8864 S.Diag(Loc, diag::err_typecheck_expect_int)
8865 << LHS.get()->getType() << LHS.get()->getSourceRange();
8869 if (!RHSEleType->isIntegerType()) {
8870 S.Diag(Loc, diag::err_typecheck_expect_int)
8871 << RHS.get()->getType() << RHS.get()->getSourceRange();
8879 if (LHSEleType != RHSEleType) {
8880 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8881 LHSEleType = RHSEleType;
8884 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8885 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8887 } else if (RHSVecTy) {
8888 // OpenCL v1.1 s6.3.j says that for vector types, the operators
8889 // are applied component-wise. So if RHS is a vector, then ensure
8890 // that the number of elements is the same as LHS...
8891 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8892 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8893 << LHS.get()->getType() << RHS.get()->getType()
8894 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8897 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8898 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8899 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8900 if (LHSBT != RHSBT &&
8901 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8902 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8903 << LHS.get()->getType() << RHS.get()->getType()
8904 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8908 // ...else expand RHS to match the number of elements in LHS.
8910 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8911 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8918 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8919 SourceLocation Loc, BinaryOperatorKind Opc,
8920 bool IsCompAssign) {
8921 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8923 // Vector shifts promote their scalar inputs to vector type.
8924 if (LHS.get()->getType()->isVectorType() ||
8925 RHS.get()->getType()->isVectorType()) {
8926 if (LangOpts.ZVector) {
8927 // The shift operators for the z vector extensions work basically
8928 // like general shifts, except that neither the LHS nor the RHS is
8929 // allowed to be a "vector bool".
8930 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8931 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8932 return InvalidOperands(Loc, LHS, RHS);
8933 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8934 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8935 return InvalidOperands(Loc, LHS, RHS);
8937 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8940 // Shifts don't perform usual arithmetic conversions, they just do integer
8941 // promotions on each operand. C99 6.5.7p3
8943 // For the LHS, do usual unary conversions, but then reset them away
8944 // if this is a compound assignment.
8945 ExprResult OldLHS = LHS;
8946 LHS = UsualUnaryConversions(LHS.get());
8947 if (LHS.isInvalid())
8949 QualType LHSType = LHS.get()->getType();
8950 if (IsCompAssign) LHS = OldLHS;
8952 // The RHS is simpler.
8953 RHS = UsualUnaryConversions(RHS.get());
8954 if (RHS.isInvalid())
8956 QualType RHSType = RHS.get()->getType();
8958 // C99 6.5.7p2: Each of the operands shall have integer type.
8959 if (!LHSType->hasIntegerRepresentation() ||
8960 !RHSType->hasIntegerRepresentation())
8961 return InvalidOperands(Loc, LHS, RHS);
8963 // C++0x: Don't allow scoped enums. FIXME: Use something better than
8964 // hasIntegerRepresentation() above instead of this.
8965 if (isScopedEnumerationType(LHSType) ||
8966 isScopedEnumerationType(RHSType)) {
8967 return InvalidOperands(Loc, LHS, RHS);
8969 // Sanity-check shift operands
8970 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8972 // "The type of the result is that of the promoted left operand."
8976 static bool IsWithinTemplateSpecialization(Decl *D) {
8977 if (DeclContext *DC = D->getDeclContext()) {
8978 if (isa<ClassTemplateSpecializationDecl>(DC))
8980 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8981 return FD->isFunctionTemplateSpecialization();
8986 /// If two different enums are compared, raise a warning.
8987 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8989 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8990 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8992 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8995 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8999 // Ignore anonymous enums.
9000 if (!LHSEnumType->getDecl()->getIdentifier())
9002 if (!RHSEnumType->getDecl()->getIdentifier())
9005 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9008 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9009 << LHSStrippedType << RHSStrippedType
9010 << LHS->getSourceRange() << RHS->getSourceRange();
9013 /// \brief Diagnose bad pointer comparisons.
9014 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9015 ExprResult &LHS, ExprResult &RHS,
9017 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9018 : diag::ext_typecheck_comparison_of_distinct_pointers)
9019 << LHS.get()->getType() << RHS.get()->getType()
9020 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9023 /// \brief Returns false if the pointers are converted to a composite type,
9025 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9026 ExprResult &LHS, ExprResult &RHS) {
9027 // C++ [expr.rel]p2:
9028 // [...] Pointer conversions (4.10) and qualification
9029 // conversions (4.4) are performed on pointer operands (or on
9030 // a pointer operand and a null pointer constant) to bring
9031 // them to their composite pointer type. [...]
9033 // C++ [expr.eq]p1 uses the same notion for (in)equality
9034 // comparisons of pointers.
9036 QualType LHSType = LHS.get()->getType();
9037 QualType RHSType = RHS.get()->getType();
9038 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9039 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9041 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9043 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9044 (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9045 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9047 S.InvalidOperands(Loc, LHS, RHS);
9051 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9052 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9056 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9060 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9061 : diag::ext_typecheck_comparison_of_fptr_to_void)
9062 << LHS.get()->getType() << RHS.get()->getType()
9063 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9066 static bool isObjCObjectLiteral(ExprResult &E) {
9067 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9068 case Stmt::ObjCArrayLiteralClass:
9069 case Stmt::ObjCDictionaryLiteralClass:
9070 case Stmt::ObjCStringLiteralClass:
9071 case Stmt::ObjCBoxedExprClass:
9074 // Note that ObjCBoolLiteral is NOT an object literal!
9079 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9080 const ObjCObjectPointerType *Type =
9081 LHS->getType()->getAs<ObjCObjectPointerType>();
9083 // If this is not actually an Objective-C object, bail out.
9087 // Get the LHS object's interface type.
9088 QualType InterfaceType = Type->getPointeeType();
9090 // If the RHS isn't an Objective-C object, bail out.
9091 if (!RHS->getType()->isObjCObjectPointerType())
9094 // Try to find the -isEqual: method.
9095 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9096 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9100 if (Type->isObjCIdType()) {
9101 // For 'id', just check the global pool.
9102 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9103 /*receiverId=*/true);
9106 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9114 QualType T = Method->parameters()[0]->getType();
9115 if (!T->isObjCObjectPointerType())
9118 QualType R = Method->getReturnType();
9119 if (!R->isScalarType())
9125 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9126 FromE = FromE->IgnoreParenImpCasts();
9127 switch (FromE->getStmtClass()) {
9130 case Stmt::ObjCStringLiteralClass:
9133 case Stmt::ObjCArrayLiteralClass:
9136 case Stmt::ObjCDictionaryLiteralClass:
9137 // "dictionary literal"
9138 return LK_Dictionary;
9139 case Stmt::BlockExprClass:
9141 case Stmt::ObjCBoxedExprClass: {
9142 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9143 switch (Inner->getStmtClass()) {
9144 case Stmt::IntegerLiteralClass:
9145 case Stmt::FloatingLiteralClass:
9146 case Stmt::CharacterLiteralClass:
9147 case Stmt::ObjCBoolLiteralExprClass:
9148 case Stmt::CXXBoolLiteralExprClass:
9149 // "numeric literal"
9151 case Stmt::ImplicitCastExprClass: {
9152 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9153 // Boolean literals can be represented by implicit casts.
9154 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9167 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9168 ExprResult &LHS, ExprResult &RHS,
9169 BinaryOperator::Opcode Opc){
9172 if (isObjCObjectLiteral(LHS)) {
9173 Literal = LHS.get();
9176 Literal = RHS.get();
9180 // Don't warn on comparisons against nil.
9181 Other = Other->IgnoreParenCasts();
9182 if (Other->isNullPointerConstant(S.getASTContext(),
9183 Expr::NPC_ValueDependentIsNotNull))
9186 // This should be kept in sync with warn_objc_literal_comparison.
9187 // LK_String should always be after the other literals, since it has its own
9189 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9190 assert(LiteralKind != Sema::LK_Block);
9191 if (LiteralKind == Sema::LK_None) {
9192 llvm_unreachable("Unknown Objective-C object literal kind");
9195 if (LiteralKind == Sema::LK_String)
9196 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9197 << Literal->getSourceRange();
9199 S.Diag(Loc, diag::warn_objc_literal_comparison)
9200 << LiteralKind << Literal->getSourceRange();
9202 if (BinaryOperator::isEqualityOp(Opc) &&
9203 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9204 SourceLocation Start = LHS.get()->getLocStart();
9205 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9206 CharSourceRange OpRange =
9207 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9209 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9210 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9211 << FixItHint::CreateReplacement(OpRange, " isEqual:")
9212 << FixItHint::CreateInsertion(End, "]");
9216 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9217 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9218 ExprResult &RHS, SourceLocation Loc,
9219 BinaryOperatorKind Opc) {
9220 // Check that left hand side is !something.
9221 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9222 if (!UO || UO->getOpcode() != UO_LNot) return;
9224 // Only check if the right hand side is non-bool arithmetic type.
9225 if (RHS.get()->isKnownToHaveBooleanValue()) return;
9227 // Make sure that the something in !something is not bool.
9228 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9229 if (SubExpr->isKnownToHaveBooleanValue()) return;
9232 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9233 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9234 << Loc << IsBitwiseOp;
9236 // First note suggest !(x < y)
9237 SourceLocation FirstOpen = SubExpr->getLocStart();
9238 SourceLocation FirstClose = RHS.get()->getLocEnd();
9239 FirstClose = S.getLocForEndOfToken(FirstClose);
9240 if (FirstClose.isInvalid())
9241 FirstOpen = SourceLocation();
9242 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9244 << FixItHint::CreateInsertion(FirstOpen, "(")
9245 << FixItHint::CreateInsertion(FirstClose, ")");
9247 // Second note suggests (!x) < y
9248 SourceLocation SecondOpen = LHS.get()->getLocStart();
9249 SourceLocation SecondClose = LHS.get()->getLocEnd();
9250 SecondClose = S.getLocForEndOfToken(SecondClose);
9251 if (SecondClose.isInvalid())
9252 SecondOpen = SourceLocation();
9253 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9254 << FixItHint::CreateInsertion(SecondOpen, "(")
9255 << FixItHint::CreateInsertion(SecondClose, ")");
9258 // Get the decl for a simple expression: a reference to a variable,
9259 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9260 static ValueDecl *getCompareDecl(Expr *E) {
9261 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9262 return DR->getDecl();
9263 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9264 if (Ivar->isFreeIvar())
9265 return Ivar->getDecl();
9267 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9268 if (Mem->isImplicitAccess())
9269 return Mem->getMemberDecl();
9274 // C99 6.5.8, C++ [expr.rel]
9275 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9276 SourceLocation Loc, BinaryOperatorKind Opc,
9277 bool IsRelational) {
9278 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9280 // Handle vector comparisons separately.
9281 if (LHS.get()->getType()->isVectorType() ||
9282 RHS.get()->getType()->isVectorType())
9283 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9285 QualType LHSType = LHS.get()->getType();
9286 QualType RHSType = RHS.get()->getType();
9288 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9289 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9291 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9292 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9294 if (!LHSType->hasFloatingRepresentation() &&
9295 !(LHSType->isBlockPointerType() && IsRelational) &&
9296 !LHS.get()->getLocStart().isMacroID() &&
9297 !RHS.get()->getLocStart().isMacroID() &&
9298 !inTemplateInstantiation()) {
9299 // For non-floating point types, check for self-comparisons of the form
9300 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9301 // often indicate logic errors in the program.
9303 // NOTE: Don't warn about comparison expressions resulting from macro
9304 // expansion. Also don't warn about comparisons which are only self
9305 // comparisons within a template specialization. The warnings should catch
9306 // obvious cases in the definition of the template anyways. The idea is to
9307 // warn when the typed comparison operator will always evaluate to the same
9309 ValueDecl *DL = getCompareDecl(LHSStripped);
9310 ValueDecl *DR = getCompareDecl(RHSStripped);
9311 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9312 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9317 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9318 !DL->getType()->isReferenceType() &&
9319 !DR->getType()->isReferenceType()) {
9320 // what is it always going to eval to?
9321 char always_evals_to;
9323 case BO_EQ: // e.g. array1 == array2
9324 always_evals_to = 0; // false
9326 case BO_NE: // e.g. array1 != array2
9327 always_evals_to = 1; // true
9330 // best we can say is 'a constant'
9331 always_evals_to = 2; // e.g. array1 <= array2
9334 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9336 << always_evals_to);
9339 if (isa<CastExpr>(LHSStripped))
9340 LHSStripped = LHSStripped->IgnoreParenCasts();
9341 if (isa<CastExpr>(RHSStripped))
9342 RHSStripped = RHSStripped->IgnoreParenCasts();
9344 // Warn about comparisons against a string constant (unless the other
9345 // operand is null), the user probably wants strcmp.
9346 Expr *literalString = nullptr;
9347 Expr *literalStringStripped = nullptr;
9348 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9349 !RHSStripped->isNullPointerConstant(Context,
9350 Expr::NPC_ValueDependentIsNull)) {
9351 literalString = LHS.get();
9352 literalStringStripped = LHSStripped;
9353 } else if ((isa<StringLiteral>(RHSStripped) ||
9354 isa<ObjCEncodeExpr>(RHSStripped)) &&
9355 !LHSStripped->isNullPointerConstant(Context,
9356 Expr::NPC_ValueDependentIsNull)) {
9357 literalString = RHS.get();
9358 literalStringStripped = RHSStripped;
9361 if (literalString) {
9362 DiagRuntimeBehavior(Loc, nullptr,
9363 PDiag(diag::warn_stringcompare)
9364 << isa<ObjCEncodeExpr>(literalStringStripped)
9365 << literalString->getSourceRange());
9369 // C99 6.5.8p3 / C99 6.5.9p4
9370 UsualArithmeticConversions(LHS, RHS);
9371 if (LHS.isInvalid() || RHS.isInvalid())
9374 LHSType = LHS.get()->getType();
9375 RHSType = RHS.get()->getType();
9377 // The result of comparisons is 'bool' in C++, 'int' in C.
9378 QualType ResultTy = Context.getLogicalOperationType();
9381 if (LHSType->isRealType() && RHSType->isRealType())
9384 // Check for comparisons of floating point operands using != and ==.
9385 if (LHSType->hasFloatingRepresentation())
9386 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9388 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9392 const Expr::NullPointerConstantKind LHSNullKind =
9393 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9394 const Expr::NullPointerConstantKind RHSNullKind =
9395 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9396 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9397 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9399 if (!IsRelational && LHSIsNull != RHSIsNull) {
9400 bool IsEquality = Opc == BO_EQ;
9402 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9403 RHS.get()->getSourceRange());
9405 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9406 LHS.get()->getSourceRange());
9409 if ((LHSType->isIntegerType() && !LHSIsNull) ||
9410 (RHSType->isIntegerType() && !RHSIsNull)) {
9411 // Skip normal pointer conversion checks in this case; we have better
9412 // diagnostics for this below.
9413 } else if (getLangOpts().CPlusPlus) {
9414 // Equality comparison of a function pointer to a void pointer is invalid,
9415 // but we allow it as an extension.
9416 // FIXME: If we really want to allow this, should it be part of composite
9417 // pointer type computation so it works in conditionals too?
9418 if (!IsRelational &&
9419 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9420 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9421 // This is a gcc extension compatibility comparison.
9422 // In a SFINAE context, we treat this as a hard error to maintain
9423 // conformance with the C++ standard.
9424 diagnoseFunctionPointerToVoidComparison(
9425 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9427 if (isSFINAEContext())
9430 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9435 // If at least one operand is a pointer [...] bring them to their
9436 // composite pointer type.
9437 // C++ [expr.rel]p2:
9438 // If both operands are pointers, [...] bring them to their composite
9440 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9441 (IsRelational ? 2 : 1) &&
9442 (!LangOpts.ObjCAutoRefCount ||
9443 !(LHSType->isObjCObjectPointerType() ||
9444 RHSType->isObjCObjectPointerType()))) {
9445 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9450 } else if (LHSType->isPointerType() &&
9451 RHSType->isPointerType()) { // C99 6.5.8p2
9452 // All of the following pointer-related warnings are GCC extensions, except
9453 // when handling null pointer constants.
9454 QualType LCanPointeeTy =
9455 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9456 QualType RCanPointeeTy =
9457 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9459 // C99 6.5.9p2 and C99 6.5.8p2
9460 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9461 RCanPointeeTy.getUnqualifiedType())) {
9462 // Valid unless a relational comparison of function pointers
9463 if (IsRelational && LCanPointeeTy->isFunctionType()) {
9464 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9465 << LHSType << RHSType << LHS.get()->getSourceRange()
9466 << RHS.get()->getSourceRange();
9468 } else if (!IsRelational &&
9469 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9470 // Valid unless comparison between non-null pointer and function pointer
9471 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9472 && !LHSIsNull && !RHSIsNull)
9473 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9477 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9479 if (LCanPointeeTy != RCanPointeeTy) {
9480 // Treat NULL constant as a special case in OpenCL.
9481 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9482 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9483 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9485 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9486 << LHSType << RHSType << 0 /* comparison */
9487 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9490 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9491 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9492 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9494 if (LHSIsNull && !RHSIsNull)
9495 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9497 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9502 if (getLangOpts().CPlusPlus) {
9504 // Two operands of type std::nullptr_t or one operand of type
9505 // std::nullptr_t and the other a null pointer constant compare equal.
9506 if (!IsRelational && LHSIsNull && RHSIsNull) {
9507 if (LHSType->isNullPtrType()) {
9508 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9511 if (RHSType->isNullPtrType()) {
9512 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9517 // Comparison of Objective-C pointers and block pointers against nullptr_t.
9518 // These aren't covered by the composite pointer type rules.
9519 if (!IsRelational && RHSType->isNullPtrType() &&
9520 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9521 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9524 if (!IsRelational && LHSType->isNullPtrType() &&
9525 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9526 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9531 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9532 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9533 // HACK: Relational comparison of nullptr_t against a pointer type is
9534 // invalid per DR583, but we allow it within std::less<> and friends,
9535 // since otherwise common uses of it break.
9536 // FIXME: Consider removing this hack once LWG fixes std::less<> and
9537 // friends to have std::nullptr_t overload candidates.
9538 DeclContext *DC = CurContext;
9539 if (isa<FunctionDecl>(DC))
9540 DC = DC->getParent();
9541 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9542 if (CTSD->isInStdNamespace() &&
9543 llvm::StringSwitch<bool>(CTSD->getName())
9544 .Cases("less", "less_equal", "greater", "greater_equal", true)
9546 if (RHSType->isNullPtrType())
9547 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9549 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9556 // If at least one operand is a pointer to member, [...] bring them to
9557 // their composite pointer type.
9558 if (!IsRelational &&
9559 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9560 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9566 // Handle scoped enumeration types specifically, since they don't promote
9568 if (LHS.get()->getType()->isEnumeralType() &&
9569 Context.hasSameUnqualifiedType(LHS.get()->getType(),
9570 RHS.get()->getType()))
9574 // Handle block pointer types.
9575 if (!IsRelational && LHSType->isBlockPointerType() &&
9576 RHSType->isBlockPointerType()) {
9577 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9578 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9580 if (!LHSIsNull && !RHSIsNull &&
9581 !Context.typesAreCompatible(lpointee, rpointee)) {
9582 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9583 << LHSType << RHSType << LHS.get()->getSourceRange()
9584 << RHS.get()->getSourceRange();
9586 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9590 // Allow block pointers to be compared with null pointer constants.
9592 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9593 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9594 if (!LHSIsNull && !RHSIsNull) {
9595 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9596 ->getPointeeType()->isVoidType())
9597 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9598 ->getPointeeType()->isVoidType())))
9599 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9600 << LHSType << RHSType << LHS.get()->getSourceRange()
9601 << RHS.get()->getSourceRange();
9603 if (LHSIsNull && !RHSIsNull)
9604 LHS = ImpCastExprToType(LHS.get(), RHSType,
9605 RHSType->isPointerType() ? CK_BitCast
9606 : CK_AnyPointerToBlockPointerCast);
9608 RHS = ImpCastExprToType(RHS.get(), LHSType,
9609 LHSType->isPointerType() ? CK_BitCast
9610 : CK_AnyPointerToBlockPointerCast);
9614 if (LHSType->isObjCObjectPointerType() ||
9615 RHSType->isObjCObjectPointerType()) {
9616 const PointerType *LPT = LHSType->getAs<PointerType>();
9617 const PointerType *RPT = RHSType->getAs<PointerType>();
9619 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9620 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9622 if (!LPtrToVoid && !RPtrToVoid &&
9623 !Context.typesAreCompatible(LHSType, RHSType)) {
9624 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9627 if (LHSIsNull && !RHSIsNull) {
9628 Expr *E = LHS.get();
9629 if (getLangOpts().ObjCAutoRefCount)
9630 CheckObjCConversion(SourceRange(), RHSType, E,
9631 CCK_ImplicitConversion);
9632 LHS = ImpCastExprToType(E, RHSType,
9633 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9636 Expr *E = RHS.get();
9637 if (getLangOpts().ObjCAutoRefCount)
9638 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9640 /*DiagnoseCFAudited=*/false, Opc);
9641 RHS = ImpCastExprToType(E, LHSType,
9642 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9646 if (LHSType->isObjCObjectPointerType() &&
9647 RHSType->isObjCObjectPointerType()) {
9648 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9649 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9651 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9652 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9654 if (LHSIsNull && !RHSIsNull)
9655 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9657 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9661 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9662 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9663 unsigned DiagID = 0;
9664 bool isError = false;
9665 if (LangOpts.DebuggerSupport) {
9666 // Under a debugger, allow the comparison of pointers to integers,
9667 // since users tend to want to compare addresses.
9668 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9669 (RHSIsNull && RHSType->isIntegerType())) {
9671 isError = getLangOpts().CPlusPlus;
9673 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9674 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9676 } else if (getLangOpts().CPlusPlus) {
9677 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9679 } else if (IsRelational)
9680 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9682 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9686 << LHSType << RHSType << LHS.get()->getSourceRange()
9687 << RHS.get()->getSourceRange();
9692 if (LHSType->isIntegerType())
9693 LHS = ImpCastExprToType(LHS.get(), RHSType,
9694 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9696 RHS = ImpCastExprToType(RHS.get(), LHSType,
9697 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9701 // Handle block pointers.
9702 if (!IsRelational && RHSIsNull
9703 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9704 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9707 if (!IsRelational && LHSIsNull
9708 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9709 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9713 if (getLangOpts().OpenCLVersion >= 200) {
9714 if (LHSIsNull && RHSType->isQueueT()) {
9715 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9719 if (LHSType->isQueueT() && RHSIsNull) {
9720 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9725 return InvalidOperands(Loc, LHS, RHS);
9728 // Return a signed ext_vector_type that is of identical size and number of
9729 // elements. For floating point vectors, return an integer type of identical
9730 // size and number of elements. In the non ext_vector_type case, search from
9731 // the largest type to the smallest type to avoid cases where long long == long,
9732 // where long gets picked over long long.
9733 QualType Sema::GetSignedVectorType(QualType V) {
9734 const VectorType *VTy = V->getAs<VectorType>();
9735 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9737 if (isa<ExtVectorType>(VTy)) {
9738 if (TypeSize == Context.getTypeSize(Context.CharTy))
9739 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9740 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9741 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9742 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9743 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9744 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9745 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9746 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9747 "Unhandled vector element size in vector compare");
9748 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9751 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9752 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9753 VectorType::GenericVector);
9754 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9755 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9756 VectorType::GenericVector);
9757 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9758 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9759 VectorType::GenericVector);
9760 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9761 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9762 VectorType::GenericVector);
9763 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9764 "Unhandled vector element size in vector compare");
9765 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9766 VectorType::GenericVector);
9769 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9770 /// operates on extended vector types. Instead of producing an IntTy result,
9771 /// like a scalar comparison, a vector comparison produces a vector of integer
9773 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9775 bool IsRelational) {
9776 // Check to make sure we're operating on vectors of the same type and width,
9777 // Allowing one side to be a scalar of element type.
9778 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9779 /*AllowBothBool*/true,
9780 /*AllowBoolConversions*/getLangOpts().ZVector);
9784 QualType LHSType = LHS.get()->getType();
9786 // If AltiVec, the comparison results in a numeric type, i.e.
9787 // bool for C++, int for C
9788 if (getLangOpts().AltiVec &&
9789 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9790 return Context.getLogicalOperationType();
9792 // For non-floating point types, check for self-comparisons of the form
9793 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9794 // often indicate logic errors in the program.
9795 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9796 if (DeclRefExpr* DRL
9797 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9798 if (DeclRefExpr* DRR
9799 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9800 if (DRL->getDecl() == DRR->getDecl())
9801 DiagRuntimeBehavior(Loc, nullptr,
9802 PDiag(diag::warn_comparison_always)
9804 << 2 // "a constant"
9808 // Check for comparisons of floating point operands using != and ==.
9809 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9810 assert (RHS.get()->getType()->hasFloatingRepresentation());
9811 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9814 // Return a signed type for the vector.
9815 return GetSignedVectorType(vType);
9818 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9819 SourceLocation Loc) {
9820 // Ensure that either both operands are of the same vector type, or
9821 // one operand is of a vector type and the other is of its element type.
9822 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9823 /*AllowBothBool*/true,
9824 /*AllowBoolConversions*/false);
9826 return InvalidOperands(Loc, LHS, RHS);
9827 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9828 vType->hasFloatingRepresentation())
9829 return InvalidOperands(Loc, LHS, RHS);
9831 return GetSignedVectorType(LHS.get()->getType());
9834 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9836 BinaryOperatorKind Opc) {
9837 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9840 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9842 if (LHS.get()->getType()->isVectorType() ||
9843 RHS.get()->getType()->isVectorType()) {
9844 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9845 RHS.get()->getType()->hasIntegerRepresentation())
9846 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9847 /*AllowBothBool*/true,
9848 /*AllowBoolConversions*/getLangOpts().ZVector);
9849 return InvalidOperands(Loc, LHS, RHS);
9853 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9855 ExprResult LHSResult = LHS, RHSResult = RHS;
9856 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9858 if (LHSResult.isInvalid() || RHSResult.isInvalid())
9860 LHS = LHSResult.get();
9861 RHS = RHSResult.get();
9863 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9865 return InvalidOperands(Loc, LHS, RHS);
9869 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9871 BinaryOperatorKind Opc) {
9872 // Check vector operands differently.
9873 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9874 return CheckVectorLogicalOperands(LHS, RHS, Loc);
9876 // Diagnose cases where the user write a logical and/or but probably meant a
9877 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
9879 if (LHS.get()->getType()->isIntegerType() &&
9880 !LHS.get()->getType()->isBooleanType() &&
9881 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9882 // Don't warn in macros or template instantiations.
9883 !Loc.isMacroID() && !inTemplateInstantiation()) {
9884 // If the RHS can be constant folded, and if it constant folds to something
9885 // that isn't 0 or 1 (which indicate a potential logical operation that
9886 // happened to fold to true/false) then warn.
9887 // Parens on the RHS are ignored.
9888 llvm::APSInt Result;
9889 if (RHS.get()->EvaluateAsInt(Result, Context))
9890 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9891 !RHS.get()->getExprLoc().isMacroID()) ||
9892 (Result != 0 && Result != 1)) {
9893 Diag(Loc, diag::warn_logical_instead_of_bitwise)
9894 << RHS.get()->getSourceRange()
9895 << (Opc == BO_LAnd ? "&&" : "||");
9896 // Suggest replacing the logical operator with the bitwise version
9897 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9898 << (Opc == BO_LAnd ? "&" : "|")
9899 << FixItHint::CreateReplacement(SourceRange(
9900 Loc, getLocForEndOfToken(Loc)),
9901 Opc == BO_LAnd ? "&" : "|");
9903 // Suggest replacing "Foo() && kNonZero" with "Foo()"
9904 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9905 << FixItHint::CreateRemoval(
9906 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9907 RHS.get()->getLocEnd()));
9911 if (!Context.getLangOpts().CPlusPlus) {
9912 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9913 // not operate on the built-in scalar and vector float types.
9914 if (Context.getLangOpts().OpenCL &&
9915 Context.getLangOpts().OpenCLVersion < 120) {
9916 if (LHS.get()->getType()->isFloatingType() ||
9917 RHS.get()->getType()->isFloatingType())
9918 return InvalidOperands(Loc, LHS, RHS);
9921 LHS = UsualUnaryConversions(LHS.get());
9922 if (LHS.isInvalid())
9925 RHS = UsualUnaryConversions(RHS.get());
9926 if (RHS.isInvalid())
9929 if (!LHS.get()->getType()->isScalarType() ||
9930 !RHS.get()->getType()->isScalarType())
9931 return InvalidOperands(Loc, LHS, RHS);
9933 return Context.IntTy;
9936 // The following is safe because we only use this method for
9937 // non-overloadable operands.
9939 // C++ [expr.log.and]p1
9940 // C++ [expr.log.or]p1
9941 // The operands are both contextually converted to type bool.
9942 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9943 if (LHSRes.isInvalid())
9944 return InvalidOperands(Loc, LHS, RHS);
9947 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9948 if (RHSRes.isInvalid())
9949 return InvalidOperands(Loc, LHS, RHS);
9952 // C++ [expr.log.and]p2
9953 // C++ [expr.log.or]p2
9954 // The result is a bool.
9955 return Context.BoolTy;
9958 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9959 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9960 if (!ME) return false;
9961 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9962 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9963 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9964 if (!Base) return false;
9965 return Base->getMethodDecl() != nullptr;
9968 /// Is the given expression (which must be 'const') a reference to a
9969 /// variable which was originally non-const, but which has become
9970 /// 'const' due to being captured within a block?
9971 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9972 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9973 assert(E->isLValue() && E->getType().isConstQualified());
9974 E = E->IgnoreParens();
9976 // Must be a reference to a declaration from an enclosing scope.
9977 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9978 if (!DRE) return NCCK_None;
9979 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9981 // The declaration must be a variable which is not declared 'const'.
9982 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9983 if (!var) return NCCK_None;
9984 if (var->getType().isConstQualified()) return NCCK_None;
9985 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9987 // Decide whether the first capture was for a block or a lambda.
9988 DeclContext *DC = S.CurContext, *Prev = nullptr;
9989 // Decide whether the first capture was for a block or a lambda.
9991 // For init-capture, it is possible that the variable belongs to the
9992 // template pattern of the current context.
9993 if (auto *FD = dyn_cast<FunctionDecl>(DC))
9994 if (var->isInitCapture() &&
9995 FD->getTemplateInstantiationPattern() == var->getDeclContext())
9997 if (DC == var->getDeclContext())
10000 DC = DC->getParent();
10002 // Unless we have an init-capture, we've gone one step too far.
10003 if (!var->isInitCapture())
10005 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10008 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10009 Ty = Ty.getNonReferenceType();
10010 if (IsDereference && Ty->isPointerType())
10011 Ty = Ty->getPointeeType();
10012 return !Ty.isConstQualified();
10015 /// Emit the "read-only variable not assignable" error and print notes to give
10016 /// more information about why the variable is not assignable, such as pointing
10017 /// to the declaration of a const variable, showing that a method is const, or
10018 /// that the function is returning a const reference.
10019 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10020 SourceLocation Loc) {
10021 // Update err_typecheck_assign_const and note_typecheck_assign_const
10022 // when this enum is changed.
10028 ConstUnknown, // Keep as last element
10031 SourceRange ExprRange = E->getSourceRange();
10033 // Only emit one error on the first const found. All other consts will emit
10034 // a note to the error.
10035 bool DiagnosticEmitted = false;
10037 // Track if the current expression is the result of a dereference, and if the
10038 // next checked expression is the result of a dereference.
10039 bool IsDereference = false;
10040 bool NextIsDereference = false;
10042 // Loop to process MemberExpr chains.
10044 IsDereference = NextIsDereference;
10046 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10047 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10048 NextIsDereference = ME->isArrow();
10049 const ValueDecl *VD = ME->getMemberDecl();
10050 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10051 // Mutable fields can be modified even if the class is const.
10052 if (Field->isMutable()) {
10053 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10057 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10058 if (!DiagnosticEmitted) {
10059 S.Diag(Loc, diag::err_typecheck_assign_const)
10060 << ExprRange << ConstMember << false /*static*/ << Field
10061 << Field->getType();
10062 DiagnosticEmitted = true;
10064 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10065 << ConstMember << false /*static*/ << Field << Field->getType()
10066 << Field->getSourceRange();
10070 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10071 if (VDecl->getType().isConstQualified()) {
10072 if (!DiagnosticEmitted) {
10073 S.Diag(Loc, diag::err_typecheck_assign_const)
10074 << ExprRange << ConstMember << true /*static*/ << VDecl
10075 << VDecl->getType();
10076 DiagnosticEmitted = true;
10078 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10079 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10080 << VDecl->getSourceRange();
10082 // Static fields do not inherit constness from parents.
10086 } // End MemberExpr
10090 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10092 const FunctionDecl *FD = CE->getDirectCallee();
10093 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10094 if (!DiagnosticEmitted) {
10095 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10096 << ConstFunction << FD;
10097 DiagnosticEmitted = true;
10099 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10100 diag::note_typecheck_assign_const)
10101 << ConstFunction << FD << FD->getReturnType()
10102 << FD->getReturnTypeSourceRange();
10104 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10105 // Point to variable declaration.
10106 if (const ValueDecl *VD = DRE->getDecl()) {
10107 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10108 if (!DiagnosticEmitted) {
10109 S.Diag(Loc, diag::err_typecheck_assign_const)
10110 << ExprRange << ConstVariable << VD << VD->getType();
10111 DiagnosticEmitted = true;
10113 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10114 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10117 } else if (isa<CXXThisExpr>(E)) {
10118 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10119 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10120 if (MD->isConst()) {
10121 if (!DiagnosticEmitted) {
10122 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10123 << ConstMethod << MD;
10124 DiagnosticEmitted = true;
10126 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10127 << ConstMethod << MD << MD->getSourceRange();
10133 if (DiagnosticEmitted)
10136 // Can't determine a more specific message, so display the generic error.
10137 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10140 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
10141 /// emit an error and return true. If so, return false.
10142 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10143 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10145 S.CheckShadowingDeclModification(E, Loc);
10147 SourceLocation OrigLoc = Loc;
10148 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10150 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10151 IsLV = Expr::MLV_InvalidMessageExpression;
10152 if (IsLV == Expr::MLV_Valid)
10155 unsigned DiagID = 0;
10156 bool NeedType = false;
10157 switch (IsLV) { // C99 6.5.16p2
10158 case Expr::MLV_ConstQualified:
10159 // Use a specialized diagnostic when we're assigning to an object
10160 // from an enclosing function or block.
10161 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10162 if (NCCK == NCCK_Block)
10163 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10165 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10169 // In ARC, use some specialized diagnostics for occasions where we
10170 // infer 'const'. These are always pseudo-strong variables.
10171 if (S.getLangOpts().ObjCAutoRefCount) {
10172 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10173 if (declRef && isa<VarDecl>(declRef->getDecl())) {
10174 VarDecl *var = cast<VarDecl>(declRef->getDecl());
10176 // Use the normal diagnostic if it's pseudo-__strong but the
10177 // user actually wrote 'const'.
10178 if (var->isARCPseudoStrong() &&
10179 (!var->getTypeSourceInfo() ||
10180 !var->getTypeSourceInfo()->getType().isConstQualified())) {
10181 // There are two pseudo-strong cases:
10183 ObjCMethodDecl *method = S.getCurMethodDecl();
10184 if (method && var == method->getSelfDecl())
10185 DiagID = method->isClassMethod()
10186 ? diag::err_typecheck_arc_assign_self_class_method
10187 : diag::err_typecheck_arc_assign_self;
10189 // - fast enumeration variables
10191 DiagID = diag::err_typecheck_arr_assign_enumeration;
10193 SourceRange Assign;
10194 if (Loc != OrigLoc)
10195 Assign = SourceRange(OrigLoc, OrigLoc);
10196 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10197 // We need to preserve the AST regardless, so migration tool
10204 // If none of the special cases above are triggered, then this is a
10205 // simple const assignment.
10207 DiagnoseConstAssignment(S, E, Loc);
10212 case Expr::MLV_ConstAddrSpace:
10213 DiagnoseConstAssignment(S, E, Loc);
10215 case Expr::MLV_ArrayType:
10216 case Expr::MLV_ArrayTemporary:
10217 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10220 case Expr::MLV_NotObjectType:
10221 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10224 case Expr::MLV_LValueCast:
10225 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10227 case Expr::MLV_Valid:
10228 llvm_unreachable("did not take early return for MLV_Valid");
10229 case Expr::MLV_InvalidExpression:
10230 case Expr::MLV_MemberFunction:
10231 case Expr::MLV_ClassTemporary:
10232 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10234 case Expr::MLV_IncompleteType:
10235 case Expr::MLV_IncompleteVoidType:
10236 return S.RequireCompleteType(Loc, E->getType(),
10237 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10238 case Expr::MLV_DuplicateVectorComponents:
10239 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10241 case Expr::MLV_NoSetterProperty:
10242 llvm_unreachable("readonly properties should be processed differently");
10243 case Expr::MLV_InvalidMessageExpression:
10244 DiagID = diag::err_readonly_message_assignment;
10246 case Expr::MLV_SubObjCPropertySetting:
10247 DiagID = diag::err_no_subobject_property_setting;
10251 SourceRange Assign;
10252 if (Loc != OrigLoc)
10253 Assign = SourceRange(OrigLoc, OrigLoc);
10255 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10257 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10261 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10262 SourceLocation Loc,
10265 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10266 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10267 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10268 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10269 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10272 // Objective-C instance variables
10273 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10274 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10275 if (OL && OR && OL->getDecl() == OR->getDecl()) {
10276 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10277 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10278 if (RL && RR && RL->getDecl() == RR->getDecl())
10279 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10284 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10285 SourceLocation Loc,
10286 QualType CompoundType) {
10287 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10289 // Verify that LHS is a modifiable lvalue, and emit error if not.
10290 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10293 QualType LHSType = LHSExpr->getType();
10294 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10296 // OpenCL v1.2 s6.1.1.1 p2:
10297 // The half data type can only be used to declare a pointer to a buffer that
10298 // contains half values
10299 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10300 LHSType->isHalfType()) {
10301 Diag(Loc, diag::err_opencl_half_load_store) << 1
10302 << LHSType.getUnqualifiedType();
10306 AssignConvertType ConvTy;
10307 if (CompoundType.isNull()) {
10308 Expr *RHSCheck = RHS.get();
10310 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10312 QualType LHSTy(LHSType);
10313 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10314 if (RHS.isInvalid())
10316 // Special case of NSObject attributes on c-style pointer types.
10317 if (ConvTy == IncompatiblePointer &&
10318 ((Context.isObjCNSObjectType(LHSType) &&
10319 RHSType->isObjCObjectPointerType()) ||
10320 (Context.isObjCNSObjectType(RHSType) &&
10321 LHSType->isObjCObjectPointerType())))
10322 ConvTy = Compatible;
10324 if (ConvTy == Compatible &&
10325 LHSType->isObjCObjectType())
10326 Diag(Loc, diag::err_objc_object_assignment)
10329 // If the RHS is a unary plus or minus, check to see if they = and + are
10330 // right next to each other. If so, the user may have typo'd "x =+ 4"
10331 // instead of "x += 4".
10332 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10333 RHSCheck = ICE->getSubExpr();
10334 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10335 if ((UO->getOpcode() == UO_Plus ||
10336 UO->getOpcode() == UO_Minus) &&
10337 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10338 // Only if the two operators are exactly adjacent.
10339 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10340 // And there is a space or other character before the subexpr of the
10341 // unary +/-. We don't want to warn on "x=-1".
10342 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10343 UO->getSubExpr()->getLocStart().isFileID()) {
10344 Diag(Loc, diag::warn_not_compound_assign)
10345 << (UO->getOpcode() == UO_Plus ? "+" : "-")
10346 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10350 if (ConvTy == Compatible) {
10351 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10352 // Warn about retain cycles where a block captures the LHS, but
10353 // not if the LHS is a simple variable into which the block is
10354 // being stored...unless that variable can be captured by reference!
10355 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10356 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10357 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10358 checkRetainCycles(LHSExpr, RHS.get());
10361 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10362 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10363 // It is safe to assign a weak reference into a strong variable.
10364 // Although this code can still have problems:
10365 // id x = self.weakProp;
10366 // id y = self.weakProp;
10367 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10368 // paths through the function. This should be revisited if
10369 // -Wrepeated-use-of-weak is made flow-sensitive.
10370 // For ObjCWeak only, we do not warn if the assign is to a non-weak
10371 // variable, which will be valid for the current autorelease scope.
10372 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10373 RHS.get()->getLocStart()))
10374 getCurFunction()->markSafeWeakUse(RHS.get());
10376 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10377 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10381 // Compound assignment "x += y"
10382 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10385 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10386 RHS.get(), AA_Assigning))
10389 CheckForNullPointerDereference(*this, LHSExpr);
10391 // C99 6.5.16p3: The type of an assignment expression is the type of the
10392 // left operand unless the left operand has qualified type, in which case
10393 // it is the unqualified version of the type of the left operand.
10394 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10395 // is converted to the type of the assignment expression (above).
10396 // C++ 5.17p1: the type of the assignment expression is that of its left
10398 return (getLangOpts().CPlusPlus
10399 ? LHSType : LHSType.getUnqualifiedType());
10402 // Only ignore explicit casts to void.
10403 static bool IgnoreCommaOperand(const Expr *E) {
10404 E = E->IgnoreParens();
10406 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10407 if (CE->getCastKind() == CK_ToVoid) {
10415 // Look for instances where it is likely the comma operator is confused with
10416 // another operator. There is a whitelist of acceptable expressions for the
10417 // left hand side of the comma operator, otherwise emit a warning.
10418 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10419 // No warnings in macros
10420 if (Loc.isMacroID())
10423 // Don't warn in template instantiations.
10424 if (inTemplateInstantiation())
10427 // Scope isn't fine-grained enough to whitelist the specific cases, so
10428 // instead, skip more than needed, then call back into here with the
10429 // CommaVisitor in SemaStmt.cpp.
10430 // The whitelisted locations are the initialization and increment portions
10431 // of a for loop. The additional checks are on the condition of
10432 // if statements, do/while loops, and for loops.
10433 const unsigned ForIncrementFlags =
10434 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10435 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10436 const unsigned ScopeFlags = getCurScope()->getFlags();
10437 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10438 (ScopeFlags & ForInitFlags) == ForInitFlags)
10441 // If there are multiple comma operators used together, get the RHS of the
10442 // of the comma operator as the LHS.
10443 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10444 if (BO->getOpcode() != BO_Comma)
10446 LHS = BO->getRHS();
10449 // Only allow some expressions on LHS to not warn.
10450 if (IgnoreCommaOperand(LHS))
10453 Diag(Loc, diag::warn_comma_operator);
10454 Diag(LHS->getLocStart(), diag::note_cast_to_void)
10455 << LHS->getSourceRange()
10456 << FixItHint::CreateInsertion(LHS->getLocStart(),
10457 LangOpts.CPlusPlus ? "static_cast<void>("
10459 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10464 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10465 SourceLocation Loc) {
10466 LHS = S.CheckPlaceholderExpr(LHS.get());
10467 RHS = S.CheckPlaceholderExpr(RHS.get());
10468 if (LHS.isInvalid() || RHS.isInvalid())
10471 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10472 // operands, but not unary promotions.
10473 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10475 // So we treat the LHS as a ignored value, and in C++ we allow the
10476 // containing site to determine what should be done with the RHS.
10477 LHS = S.IgnoredValueConversions(LHS.get());
10478 if (LHS.isInvalid())
10481 S.DiagnoseUnusedExprResult(LHS.get());
10483 if (!S.getLangOpts().CPlusPlus) {
10484 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10485 if (RHS.isInvalid())
10487 if (!RHS.get()->getType()->isVoidType())
10488 S.RequireCompleteType(Loc, RHS.get()->getType(),
10489 diag::err_incomplete_type);
10492 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10493 S.DiagnoseCommaOperator(LHS.get(), Loc);
10495 return RHS.get()->getType();
10498 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10499 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10500 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10502 ExprObjectKind &OK,
10503 SourceLocation OpLoc,
10504 bool IsInc, bool IsPrefix) {
10505 if (Op->isTypeDependent())
10506 return S.Context.DependentTy;
10508 QualType ResType = Op->getType();
10509 // Atomic types can be used for increment / decrement where the non-atomic
10510 // versions can, so ignore the _Atomic() specifier for the purpose of
10512 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10513 ResType = ResAtomicType->getValueType();
10515 assert(!ResType.isNull() && "no type for increment/decrement expression");
10517 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10518 // Decrement of bool is not allowed.
10520 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10523 // Increment of bool sets it to true, but is deprecated.
10524 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10525 : diag::warn_increment_bool)
10526 << Op->getSourceRange();
10527 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10528 // Error on enum increments and decrements in C++ mode
10529 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10531 } else if (ResType->isRealType()) {
10533 } else if (ResType->isPointerType()) {
10534 // C99 6.5.2.4p2, 6.5.6p2
10535 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10537 } else if (ResType->isObjCObjectPointerType()) {
10538 // On modern runtimes, ObjC pointer arithmetic is forbidden.
10539 // Otherwise, we just need a complete type.
10540 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10541 checkArithmeticOnObjCPointer(S, OpLoc, Op))
10543 } else if (ResType->isAnyComplexType()) {
10544 // C99 does not support ++/-- on complex types, we allow as an extension.
10545 S.Diag(OpLoc, diag::ext_integer_increment_complex)
10546 << ResType << Op->getSourceRange();
10547 } else if (ResType->isPlaceholderType()) {
10548 ExprResult PR = S.CheckPlaceholderExpr(Op);
10549 if (PR.isInvalid()) return QualType();
10550 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10552 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10553 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10554 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10555 (ResType->getAs<VectorType>()->getVectorKind() !=
10556 VectorType::AltiVecBool)) {
10557 // The z vector extensions allow ++ and -- for non-bool vectors.
10558 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10559 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10560 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10562 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10563 << ResType << int(IsInc) << Op->getSourceRange();
10566 // At this point, we know we have a real, complex or pointer type.
10567 // Now make sure the operand is a modifiable lvalue.
10568 if (CheckForModifiableLvalue(Op, OpLoc, S))
10570 // In C++, a prefix increment is the same type as the operand. Otherwise
10571 // (in C or with postfix), the increment is the unqualified type of the
10573 if (IsPrefix && S.getLangOpts().CPlusPlus) {
10575 OK = Op->getObjectKind();
10579 return ResType.getUnqualifiedType();
10584 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10585 /// This routine allows us to typecheck complex/recursive expressions
10586 /// where the declaration is needed for type checking. We only need to
10587 /// handle cases when the expression references a function designator
10588 /// or is an lvalue. Here are some examples:
10590 /// - &*****f => f for f a function designator.
10592 /// - &s.zz[1].yy -> s, if zz is an array
10593 /// - *(x + 1) -> x, if x is an array
10594 /// - &"123"[2] -> 0
10595 /// - & __real__ x -> x
10596 static ValueDecl *getPrimaryDecl(Expr *E) {
10597 switch (E->getStmtClass()) {
10598 case Stmt::DeclRefExprClass:
10599 return cast<DeclRefExpr>(E)->getDecl();
10600 case Stmt::MemberExprClass:
10601 // If this is an arrow operator, the address is an offset from
10602 // the base's value, so the object the base refers to is
10604 if (cast<MemberExpr>(E)->isArrow())
10606 // Otherwise, the expression refers to a part of the base
10607 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10608 case Stmt::ArraySubscriptExprClass: {
10609 // FIXME: This code shouldn't be necessary! We should catch the implicit
10610 // promotion of register arrays earlier.
10611 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10612 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10613 if (ICE->getSubExpr()->getType()->isArrayType())
10614 return getPrimaryDecl(ICE->getSubExpr());
10618 case Stmt::UnaryOperatorClass: {
10619 UnaryOperator *UO = cast<UnaryOperator>(E);
10621 switch(UO->getOpcode()) {
10625 return getPrimaryDecl(UO->getSubExpr());
10630 case Stmt::ParenExprClass:
10631 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10632 case Stmt::ImplicitCastExprClass:
10633 // If the result of an implicit cast is an l-value, we care about
10634 // the sub-expression; otherwise, the result here doesn't matter.
10635 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10644 AO_Vector_Element = 1,
10645 AO_Property_Expansion = 2,
10646 AO_Register_Variable = 3,
10650 /// \brief Diagnose invalid operand for address of operations.
10652 /// \param Type The type of operand which cannot have its address taken.
10653 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10654 Expr *E, unsigned Type) {
10655 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10658 /// CheckAddressOfOperand - The operand of & must be either a function
10659 /// designator or an lvalue designating an object. If it is an lvalue, the
10660 /// object cannot be declared with storage class register or be a bit field.
10661 /// Note: The usual conversions are *not* applied to the operand of the &
10662 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10663 /// In C++, the operand might be an overloaded function name, in which case
10664 /// we allow the '&' but retain the overloaded-function type.
10665 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10666 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10667 if (PTy->getKind() == BuiltinType::Overload) {
10668 Expr *E = OrigOp.get()->IgnoreParens();
10669 if (!isa<OverloadExpr>(E)) {
10670 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10671 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10672 << OrigOp.get()->getSourceRange();
10676 OverloadExpr *Ovl = cast<OverloadExpr>(E);
10677 if (isa<UnresolvedMemberExpr>(Ovl))
10678 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10679 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10680 << OrigOp.get()->getSourceRange();
10684 return Context.OverloadTy;
10687 if (PTy->getKind() == BuiltinType::UnknownAny)
10688 return Context.UnknownAnyTy;
10690 if (PTy->getKind() == BuiltinType::BoundMember) {
10691 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10692 << OrigOp.get()->getSourceRange();
10696 OrigOp = CheckPlaceholderExpr(OrigOp.get());
10697 if (OrigOp.isInvalid()) return QualType();
10700 if (OrigOp.get()->isTypeDependent())
10701 return Context.DependentTy;
10703 assert(!OrigOp.get()->getType()->isPlaceholderType());
10705 // Make sure to ignore parentheses in subsequent checks
10706 Expr *op = OrigOp.get()->IgnoreParens();
10708 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10709 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10710 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10714 if (getLangOpts().C99) {
10715 // Implement C99-only parts of addressof rules.
10716 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10717 if (uOp->getOpcode() == UO_Deref)
10718 // Per C99 6.5.3.2, the address of a deref always returns a valid result
10719 // (assuming the deref expression is valid).
10720 return uOp->getSubExpr()->getType();
10722 // Technically, there should be a check for array subscript
10723 // expressions here, but the result of one is always an lvalue anyway.
10725 ValueDecl *dcl = getPrimaryDecl(op);
10727 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10728 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10729 op->getLocStart()))
10732 Expr::LValueClassification lval = op->ClassifyLValue(Context);
10733 unsigned AddressOfError = AO_No_Error;
10735 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10736 bool sfinae = (bool)isSFINAEContext();
10737 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10738 : diag::ext_typecheck_addrof_temporary)
10739 << op->getType() << op->getSourceRange();
10742 // Materialize the temporary as an lvalue so that we can take its address.
10744 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10745 } else if (isa<ObjCSelectorExpr>(op)) {
10746 return Context.getPointerType(op->getType());
10747 } else if (lval == Expr::LV_MemberFunction) {
10748 // If it's an instance method, make a member pointer.
10749 // The expression must have exactly the form &A::foo.
10751 // If the underlying expression isn't a decl ref, give up.
10752 if (!isa<DeclRefExpr>(op)) {
10753 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10754 << OrigOp.get()->getSourceRange();
10757 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10758 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10760 // The id-expression was parenthesized.
10761 if (OrigOp.get() != DRE) {
10762 Diag(OpLoc, diag::err_parens_pointer_member_function)
10763 << OrigOp.get()->getSourceRange();
10765 // The method was named without a qualifier.
10766 } else if (!DRE->getQualifier()) {
10767 if (MD->getParent()->getName().empty())
10768 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10769 << op->getSourceRange();
10771 SmallString<32> Str;
10772 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10773 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10774 << op->getSourceRange()
10775 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10779 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10780 if (isa<CXXDestructorDecl>(MD))
10781 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10783 QualType MPTy = Context.getMemberPointerType(
10784 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10785 // Under the MS ABI, lock down the inheritance model now.
10786 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10787 (void)isCompleteType(OpLoc, MPTy);
10789 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10791 // The operand must be either an l-value or a function designator
10792 if (!op->getType()->isFunctionType()) {
10793 // Use a special diagnostic for loads from property references.
10794 if (isa<PseudoObjectExpr>(op)) {
10795 AddressOfError = AO_Property_Expansion;
10797 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10798 << op->getType() << op->getSourceRange();
10802 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10803 // The operand cannot be a bit-field
10804 AddressOfError = AO_Bit_Field;
10805 } else if (op->getObjectKind() == OK_VectorComponent) {
10806 // The operand cannot be an element of a vector
10807 AddressOfError = AO_Vector_Element;
10808 } else if (dcl) { // C99 6.5.3.2p1
10809 // We have an lvalue with a decl. Make sure the decl is not declared
10810 // with the register storage-class specifier.
10811 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10812 // in C++ it is not error to take address of a register
10813 // variable (c++03 7.1.1P3)
10814 if (vd->getStorageClass() == SC_Register &&
10815 !getLangOpts().CPlusPlus) {
10816 AddressOfError = AO_Register_Variable;
10818 } else if (isa<MSPropertyDecl>(dcl)) {
10819 AddressOfError = AO_Property_Expansion;
10820 } else if (isa<FunctionTemplateDecl>(dcl)) {
10821 return Context.OverloadTy;
10822 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10823 // Okay: we can take the address of a field.
10824 // Could be a pointer to member, though, if there is an explicit
10825 // scope qualifier for the class.
10826 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10827 DeclContext *Ctx = dcl->getDeclContext();
10828 if (Ctx && Ctx->isRecord()) {
10829 if (dcl->getType()->isReferenceType()) {
10831 diag::err_cannot_form_pointer_to_member_of_reference_type)
10832 << dcl->getDeclName() << dcl->getType();
10836 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10837 Ctx = Ctx->getParent();
10839 QualType MPTy = Context.getMemberPointerType(
10841 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10842 // Under the MS ABI, lock down the inheritance model now.
10843 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10844 (void)isCompleteType(OpLoc, MPTy);
10848 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10849 !isa<BindingDecl>(dcl))
10850 llvm_unreachable("Unknown/unexpected decl type");
10853 if (AddressOfError != AO_No_Error) {
10854 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10858 if (lval == Expr::LV_IncompleteVoidType) {
10859 // Taking the address of a void variable is technically illegal, but we
10860 // allow it in cases which are otherwise valid.
10861 // Example: "extern void x; void* y = &x;".
10862 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10865 // If the operand has type "type", the result has type "pointer to type".
10866 if (op->getType()->isObjCObjectType())
10867 return Context.getObjCObjectPointerType(op->getType());
10869 CheckAddressOfPackedMember(op);
10871 return Context.getPointerType(op->getType());
10874 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10875 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10878 const Decl *D = DRE->getDecl();
10881 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10884 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10885 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10887 if (FunctionScopeInfo *FD = S.getCurFunction())
10888 if (!FD->ModifiedNonNullParams.count(Param))
10889 FD->ModifiedNonNullParams.insert(Param);
10892 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10893 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10894 SourceLocation OpLoc) {
10895 if (Op->isTypeDependent())
10896 return S.Context.DependentTy;
10898 ExprResult ConvResult = S.UsualUnaryConversions(Op);
10899 if (ConvResult.isInvalid())
10901 Op = ConvResult.get();
10902 QualType OpTy = Op->getType();
10905 if (isa<CXXReinterpretCastExpr>(Op)) {
10906 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10907 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10908 Op->getSourceRange());
10911 if (const PointerType *PT = OpTy->getAs<PointerType>())
10913 Result = PT->getPointeeType();
10915 else if (const ObjCObjectPointerType *OPT =
10916 OpTy->getAs<ObjCObjectPointerType>())
10917 Result = OPT->getPointeeType();
10919 ExprResult PR = S.CheckPlaceholderExpr(Op);
10920 if (PR.isInvalid()) return QualType();
10921 if (PR.get() != Op)
10922 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10925 if (Result.isNull()) {
10926 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10927 << OpTy << Op->getSourceRange();
10931 // Note that per both C89 and C99, indirection is always legal, even if Result
10932 // is an incomplete type or void. It would be possible to warn about
10933 // dereferencing a void pointer, but it's completely well-defined, and such a
10934 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10935 // for pointers to 'void' but is fine for any other pointer type:
10937 // C++ [expr.unary.op]p1:
10938 // [...] the expression to which [the unary * operator] is applied shall
10939 // be a pointer to an object type, or a pointer to a function type
10940 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10941 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10942 << OpTy << Op->getSourceRange();
10944 // Dereferences are usually l-values...
10947 // ...except that certain expressions are never l-values in C.
10948 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10954 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10955 BinaryOperatorKind Opc;
10957 default: llvm_unreachable("Unknown binop!");
10958 case tok::periodstar: Opc = BO_PtrMemD; break;
10959 case tok::arrowstar: Opc = BO_PtrMemI; break;
10960 case tok::star: Opc = BO_Mul; break;
10961 case tok::slash: Opc = BO_Div; break;
10962 case tok::percent: Opc = BO_Rem; break;
10963 case tok::plus: Opc = BO_Add; break;
10964 case tok::minus: Opc = BO_Sub; break;
10965 case tok::lessless: Opc = BO_Shl; break;
10966 case tok::greatergreater: Opc = BO_Shr; break;
10967 case tok::lessequal: Opc = BO_LE; break;
10968 case tok::less: Opc = BO_LT; break;
10969 case tok::greaterequal: Opc = BO_GE; break;
10970 case tok::greater: Opc = BO_GT; break;
10971 case tok::exclaimequal: Opc = BO_NE; break;
10972 case tok::equalequal: Opc = BO_EQ; break;
10973 case tok::amp: Opc = BO_And; break;
10974 case tok::caret: Opc = BO_Xor; break;
10975 case tok::pipe: Opc = BO_Or; break;
10976 case tok::ampamp: Opc = BO_LAnd; break;
10977 case tok::pipepipe: Opc = BO_LOr; break;
10978 case tok::equal: Opc = BO_Assign; break;
10979 case tok::starequal: Opc = BO_MulAssign; break;
10980 case tok::slashequal: Opc = BO_DivAssign; break;
10981 case tok::percentequal: Opc = BO_RemAssign; break;
10982 case tok::plusequal: Opc = BO_AddAssign; break;
10983 case tok::minusequal: Opc = BO_SubAssign; break;
10984 case tok::lesslessequal: Opc = BO_ShlAssign; break;
10985 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
10986 case tok::ampequal: Opc = BO_AndAssign; break;
10987 case tok::caretequal: Opc = BO_XorAssign; break;
10988 case tok::pipeequal: Opc = BO_OrAssign; break;
10989 case tok::comma: Opc = BO_Comma; break;
10994 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10995 tok::TokenKind Kind) {
10996 UnaryOperatorKind Opc;
10998 default: llvm_unreachable("Unknown unary op!");
10999 case tok::plusplus: Opc = UO_PreInc; break;
11000 case tok::minusminus: Opc = UO_PreDec; break;
11001 case tok::amp: Opc = UO_AddrOf; break;
11002 case tok::star: Opc = UO_Deref; break;
11003 case tok::plus: Opc = UO_Plus; break;
11004 case tok::minus: Opc = UO_Minus; break;
11005 case tok::tilde: Opc = UO_Not; break;
11006 case tok::exclaim: Opc = UO_LNot; break;
11007 case tok::kw___real: Opc = UO_Real; break;
11008 case tok::kw___imag: Opc = UO_Imag; break;
11009 case tok::kw___extension__: Opc = UO_Extension; break;
11014 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11015 /// This warning is only emitted for builtin assignment operations. It is also
11016 /// suppressed in the event of macro expansions.
11017 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11018 SourceLocation OpLoc) {
11019 if (S.inTemplateInstantiation())
11021 if (OpLoc.isInvalid() || OpLoc.isMacroID())
11023 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11024 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11025 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11026 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11027 if (!LHSDeclRef || !RHSDeclRef ||
11028 LHSDeclRef->getLocation().isMacroID() ||
11029 RHSDeclRef->getLocation().isMacroID())
11031 const ValueDecl *LHSDecl =
11032 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11033 const ValueDecl *RHSDecl =
11034 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11035 if (LHSDecl != RHSDecl)
11037 if (LHSDecl->getType().isVolatileQualified())
11039 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11040 if (RefTy->getPointeeType().isVolatileQualified())
11043 S.Diag(OpLoc, diag::warn_self_assignment)
11044 << LHSDeclRef->getType()
11045 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11048 /// Check if a bitwise-& is performed on an Objective-C pointer. This
11049 /// is usually indicative of introspection within the Objective-C pointer.
11050 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11051 SourceLocation OpLoc) {
11052 if (!S.getLangOpts().ObjC1)
11055 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11056 const Expr *LHS = L.get();
11057 const Expr *RHS = R.get();
11059 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11060 ObjCPointerExpr = LHS;
11063 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11064 ObjCPointerExpr = RHS;
11068 // This warning is deliberately made very specific to reduce false
11069 // positives with logic that uses '&' for hashing. This logic mainly
11070 // looks for code trying to introspect into tagged pointers, which
11071 // code should generally never do.
11072 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11073 unsigned Diag = diag::warn_objc_pointer_masking;
11074 // Determine if we are introspecting the result of performSelectorXXX.
11075 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11076 // Special case messages to -performSelector and friends, which
11077 // can return non-pointer values boxed in a pointer value.
11078 // Some clients may wish to silence warnings in this subcase.
11079 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11080 Selector S = ME->getSelector();
11081 StringRef SelArg0 = S.getNameForSlot(0);
11082 if (SelArg0.startswith("performSelector"))
11083 Diag = diag::warn_objc_pointer_masking_performSelector;
11086 S.Diag(OpLoc, Diag)
11087 << ObjCPointerExpr->getSourceRange();
11091 static NamedDecl *getDeclFromExpr(Expr *E) {
11094 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11095 return DRE->getDecl();
11096 if (auto *ME = dyn_cast<MemberExpr>(E))
11097 return ME->getMemberDecl();
11098 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11099 return IRE->getDecl();
11103 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11104 /// operator @p Opc at location @c TokLoc. This routine only supports
11105 /// built-in operations; ActOnBinOp handles overloaded operators.
11106 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11107 BinaryOperatorKind Opc,
11108 Expr *LHSExpr, Expr *RHSExpr) {
11109 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11110 // The syntax only allows initializer lists on the RHS of assignment,
11111 // so we don't need to worry about accepting invalid code for
11112 // non-assignment operators.
11114 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11115 // of x = {} is x = T().
11116 InitializationKind Kind =
11117 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11118 InitializedEntity Entity =
11119 InitializedEntity::InitializeTemporary(LHSExpr->getType());
11120 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11121 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11122 if (Init.isInvalid())
11124 RHSExpr = Init.get();
11127 ExprResult LHS = LHSExpr, RHS = RHSExpr;
11128 QualType ResultTy; // Result type of the binary operator.
11129 // The following two variables are used for compound assignment operators
11130 QualType CompLHSTy; // Type of LHS after promotions for computation
11131 QualType CompResultTy; // Type of computation result
11132 ExprValueKind VK = VK_RValue;
11133 ExprObjectKind OK = OK_Ordinary;
11135 if (!getLangOpts().CPlusPlus) {
11136 // C cannot handle TypoExpr nodes on either side of a binop because it
11137 // doesn't handle dependent types properly, so make sure any TypoExprs have
11138 // been dealt with before checking the operands.
11139 LHS = CorrectDelayedTyposInExpr(LHSExpr);
11140 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11141 if (Opc != BO_Assign)
11142 return ExprResult(E);
11143 // Avoid correcting the RHS to the same Expr as the LHS.
11144 Decl *D = getDeclFromExpr(E);
11145 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11147 if (!LHS.isUsable() || !RHS.isUsable())
11148 return ExprError();
11151 if (getLangOpts().OpenCL) {
11152 QualType LHSTy = LHSExpr->getType();
11153 QualType RHSTy = RHSExpr->getType();
11154 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11155 // the ATOMIC_VAR_INIT macro.
11156 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11157 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11158 if (BO_Assign == Opc)
11159 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11161 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11162 return ExprError();
11165 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11166 // only with a builtin functions and therefore should be disallowed here.
11167 if (LHSTy->isImageType() || RHSTy->isImageType() ||
11168 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11169 LHSTy->isPipeType() || RHSTy->isPipeType() ||
11170 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11171 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11172 return ExprError();
11178 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11179 if (getLangOpts().CPlusPlus &&
11180 LHS.get()->getObjectKind() != OK_ObjCProperty) {
11181 VK = LHS.get()->getValueKind();
11182 OK = LHS.get()->getObjectKind();
11184 if (!ResultTy.isNull()) {
11185 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11186 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11188 RecordModifiableNonNullParam(*this, LHS.get());
11192 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11193 Opc == BO_PtrMemI);
11197 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11201 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11204 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11207 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11211 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11217 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11221 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11224 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11227 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11231 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11235 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11236 Opc == BO_DivAssign);
11237 CompLHSTy = CompResultTy;
11238 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11239 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11242 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11243 CompLHSTy = CompResultTy;
11244 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11245 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11248 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11249 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11250 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11253 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11254 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11255 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11259 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11260 CompLHSTy = CompResultTy;
11261 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11262 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11265 case BO_OrAssign: // fallthrough
11266 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11268 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11269 CompLHSTy = CompResultTy;
11270 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11271 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11274 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11275 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11276 VK = RHS.get()->getValueKind();
11277 OK = RHS.get()->getObjectKind();
11281 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11282 return ExprError();
11284 // Check for array bounds violations for both sides of the BinaryOperator
11285 CheckArrayAccess(LHS.get());
11286 CheckArrayAccess(RHS.get());
11288 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11289 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11290 &Context.Idents.get("object_setClass"),
11291 SourceLocation(), LookupOrdinaryName);
11292 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11293 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11294 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11295 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11296 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11297 FixItHint::CreateInsertion(RHSLocEnd, ")");
11300 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11302 else if (const ObjCIvarRefExpr *OIRE =
11303 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11304 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11306 if (CompResultTy.isNull())
11307 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11308 OK, OpLoc, FPFeatures);
11309 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11312 OK = LHS.get()->getObjectKind();
11314 return new (Context) CompoundAssignOperator(
11315 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11316 OpLoc, FPFeatures);
11319 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11320 /// operators are mixed in a way that suggests that the programmer forgot that
11321 /// comparison operators have higher precedence. The most typical example of
11322 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11323 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11324 SourceLocation OpLoc, Expr *LHSExpr,
11326 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11327 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11329 // Check that one of the sides is a comparison operator and the other isn't.
11330 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11331 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11332 if (isLeftComp == isRightComp)
11335 // Bitwise operations are sometimes used as eager logical ops.
11336 // Don't diagnose this.
11337 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11338 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11339 if (isLeftBitwise || isRightBitwise)
11342 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11344 : SourceRange(OpLoc, RHSExpr->getLocEnd());
11345 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11346 SourceRange ParensRange = isLeftComp ?
11347 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11348 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11350 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11351 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11352 SuggestParentheses(Self, OpLoc,
11353 Self.PDiag(diag::note_precedence_silence) << OpStr,
11354 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11355 SuggestParentheses(Self, OpLoc,
11356 Self.PDiag(diag::note_precedence_bitwise_first)
11357 << BinaryOperator::getOpcodeStr(Opc),
11361 /// \brief It accepts a '&&' expr that is inside a '||' one.
11362 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11363 /// in parentheses.
11365 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11366 BinaryOperator *Bop) {
11367 assert(Bop->getOpcode() == BO_LAnd);
11368 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11369 << Bop->getSourceRange() << OpLoc;
11370 SuggestParentheses(Self, Bop->getOperatorLoc(),
11371 Self.PDiag(diag::note_precedence_silence)
11372 << Bop->getOpcodeStr(),
11373 Bop->getSourceRange());
11376 /// \brief Returns true if the given expression can be evaluated as a constant
11378 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11380 return !E->isValueDependent() &&
11381 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11384 /// \brief Returns true if the given expression can be evaluated as a constant
11386 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11388 return !E->isValueDependent() &&
11389 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11392 /// \brief Look for '&&' in the left hand of a '||' expr.
11393 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11394 Expr *LHSExpr, Expr *RHSExpr) {
11395 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11396 if (Bop->getOpcode() == BO_LAnd) {
11397 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11398 if (EvaluatesAsFalse(S, RHSExpr))
11400 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11401 if (!EvaluatesAsTrue(S, Bop->getLHS()))
11402 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11403 } else if (Bop->getOpcode() == BO_LOr) {
11404 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11405 // If it's "a || b && 1 || c" we didn't warn earlier for
11406 // "a || b && 1", but warn now.
11407 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11408 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11414 /// \brief Look for '&&' in the right hand of a '||' expr.
11415 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11416 Expr *LHSExpr, Expr *RHSExpr) {
11417 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11418 if (Bop->getOpcode() == BO_LAnd) {
11419 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11420 if (EvaluatesAsFalse(S, LHSExpr))
11422 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11423 if (!EvaluatesAsTrue(S, Bop->getRHS()))
11424 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11429 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11430 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11431 /// the '&' expression in parentheses.
11432 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11433 SourceLocation OpLoc, Expr *SubExpr) {
11434 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11435 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11436 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11437 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11438 << Bop->getSourceRange() << OpLoc;
11439 SuggestParentheses(S, Bop->getOperatorLoc(),
11440 S.PDiag(diag::note_precedence_silence)
11441 << Bop->getOpcodeStr(),
11442 Bop->getSourceRange());
11447 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11448 Expr *SubExpr, StringRef Shift) {
11449 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11450 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11451 StringRef Op = Bop->getOpcodeStr();
11452 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11453 << Bop->getSourceRange() << OpLoc << Shift << Op;
11454 SuggestParentheses(S, Bop->getOperatorLoc(),
11455 S.PDiag(diag::note_precedence_silence) << Op,
11456 Bop->getSourceRange());
11461 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11462 Expr *LHSExpr, Expr *RHSExpr) {
11463 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11467 FunctionDecl *FD = OCE->getDirectCallee();
11468 if (!FD || !FD->isOverloadedOperator())
11471 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11472 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11475 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11476 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11477 << (Kind == OO_LessLess);
11478 SuggestParentheses(S, OCE->getOperatorLoc(),
11479 S.PDiag(diag::note_precedence_silence)
11480 << (Kind == OO_LessLess ? "<<" : ">>"),
11481 OCE->getSourceRange());
11482 SuggestParentheses(S, OpLoc,
11483 S.PDiag(diag::note_evaluate_comparison_first),
11484 SourceRange(OCE->getArg(1)->getLocStart(),
11485 RHSExpr->getLocEnd()));
11488 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11490 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11491 SourceLocation OpLoc, Expr *LHSExpr,
11493 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11494 if (BinaryOperator::isBitwiseOp(Opc))
11495 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11497 // Diagnose "arg1 & arg2 | arg3"
11498 if ((Opc == BO_Or || Opc == BO_Xor) &&
11499 !OpLoc.isMacroID()/* Don't warn in macros. */) {
11500 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11501 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11504 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11505 // We don't warn for 'assert(a || b && "bad")' since this is safe.
11506 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11507 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11508 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11511 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11512 || Opc == BO_Shr) {
11513 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11514 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11515 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11518 // Warn on overloaded shift operators and comparisons, such as:
11520 if (BinaryOperator::isComparisonOp(Opc))
11521 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11524 // Binary Operators. 'Tok' is the token for the operator.
11525 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11526 tok::TokenKind Kind,
11527 Expr *LHSExpr, Expr *RHSExpr) {
11528 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11529 assert(LHSExpr && "ActOnBinOp(): missing left expression");
11530 assert(RHSExpr && "ActOnBinOp(): missing right expression");
11532 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11533 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11535 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11538 /// Build an overloaded binary operator expression in the given scope.
11539 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11540 BinaryOperatorKind Opc,
11541 Expr *LHS, Expr *RHS) {
11542 // Find all of the overloaded operators visible from this
11543 // point. We perform both an operator-name lookup from the local
11544 // scope and an argument-dependent lookup based on the types of
11546 UnresolvedSet<16> Functions;
11547 OverloadedOperatorKind OverOp
11548 = BinaryOperator::getOverloadedOperator(Opc);
11549 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11550 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11551 RHS->getType(), Functions);
11553 // Build the (potentially-overloaded, potentially-dependent)
11554 // binary operation.
11555 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11558 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11559 BinaryOperatorKind Opc,
11560 Expr *LHSExpr, Expr *RHSExpr) {
11561 // We want to end up calling one of checkPseudoObjectAssignment
11562 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11563 // both expressions are overloadable or either is type-dependent),
11564 // or CreateBuiltinBinOp (in any other case). We also want to get
11565 // any placeholder types out of the way.
11567 // Handle pseudo-objects in the LHS.
11568 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11569 // Assignments with a pseudo-object l-value need special analysis.
11570 if (pty->getKind() == BuiltinType::PseudoObject &&
11571 BinaryOperator::isAssignmentOp(Opc))
11572 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11574 // Don't resolve overloads if the other type is overloadable.
11575 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11576 // We can't actually test that if we still have a placeholder,
11577 // though. Fortunately, none of the exceptions we see in that
11578 // code below are valid when the LHS is an overload set. Note
11579 // that an overload set can be dependently-typed, but it never
11580 // instantiates to having an overloadable type.
11581 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11582 if (resolvedRHS.isInvalid()) return ExprError();
11583 RHSExpr = resolvedRHS.get();
11585 if (RHSExpr->isTypeDependent() ||
11586 RHSExpr->getType()->isOverloadableType())
11587 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11590 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11591 if (LHS.isInvalid()) return ExprError();
11592 LHSExpr = LHS.get();
11595 // Handle pseudo-objects in the RHS.
11596 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11597 // An overload in the RHS can potentially be resolved by the type
11598 // being assigned to.
11599 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11600 if (getLangOpts().CPlusPlus &&
11601 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11602 LHSExpr->getType()->isOverloadableType()))
11603 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11605 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11608 // Don't resolve overloads if the other type is overloadable.
11609 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11610 LHSExpr->getType()->isOverloadableType())
11611 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11613 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11614 if (!resolvedRHS.isUsable()) return ExprError();
11615 RHSExpr = resolvedRHS.get();
11618 if (getLangOpts().CPlusPlus) {
11619 // If either expression is type-dependent, always build an
11621 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11622 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11624 // Otherwise, build an overloaded op if either expression has an
11625 // overloadable type.
11626 if (LHSExpr->getType()->isOverloadableType() ||
11627 RHSExpr->getType()->isOverloadableType())
11628 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11631 // Build a built-in binary operation.
11632 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11635 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11636 UnaryOperatorKind Opc,
11638 ExprResult Input = InputExpr;
11639 ExprValueKind VK = VK_RValue;
11640 ExprObjectKind OK = OK_Ordinary;
11641 QualType resultType;
11642 if (getLangOpts().OpenCL) {
11643 QualType Ty = InputExpr->getType();
11644 // The only legal unary operation for atomics is '&'.
11645 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11646 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11647 // only with a builtin functions and therefore should be disallowed here.
11648 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11649 || Ty->isBlockPointerType())) {
11650 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11651 << InputExpr->getType()
11652 << Input.get()->getSourceRange());
11660 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11662 Opc == UO_PreInc ||
11664 Opc == UO_PreInc ||
11668 resultType = CheckAddressOfOperand(Input, OpLoc);
11669 RecordModifiableNonNullParam(*this, InputExpr);
11672 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11673 if (Input.isInvalid()) return ExprError();
11674 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11679 Input = UsualUnaryConversions(Input.get());
11680 if (Input.isInvalid()) return ExprError();
11681 resultType = Input.get()->getType();
11682 if (resultType->isDependentType())
11684 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11686 else if (resultType->isVectorType() &&
11687 // The z vector extensions don't allow + or - with bool vectors.
11688 (!Context.getLangOpts().ZVector ||
11689 resultType->getAs<VectorType>()->getVectorKind() !=
11690 VectorType::AltiVecBool))
11692 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11694 resultType->isPointerType())
11697 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11698 << resultType << Input.get()->getSourceRange());
11700 case UO_Not: // bitwise complement
11701 Input = UsualUnaryConversions(Input.get());
11702 if (Input.isInvalid())
11703 return ExprError();
11704 resultType = Input.get()->getType();
11705 if (resultType->isDependentType())
11707 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11708 if (resultType->isComplexType() || resultType->isComplexIntegerType())
11709 // C99 does not support '~' for complex conjugation.
11710 Diag(OpLoc, diag::ext_integer_complement_complex)
11711 << resultType << Input.get()->getSourceRange();
11712 else if (resultType->hasIntegerRepresentation())
11714 else if (resultType->isExtVectorType()) {
11715 if (Context.getLangOpts().OpenCL) {
11716 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11717 // on vector float types.
11718 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11719 if (!T->isIntegerType())
11720 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11721 << resultType << Input.get()->getSourceRange());
11725 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11726 << resultType << Input.get()->getSourceRange());
11730 case UO_LNot: // logical negation
11731 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11732 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11733 if (Input.isInvalid()) return ExprError();
11734 resultType = Input.get()->getType();
11736 // Though we still have to promote half FP to float...
11737 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11738 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11739 resultType = Context.FloatTy;
11742 if (resultType->isDependentType())
11744 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11745 // C99 6.5.3.3p1: ok, fallthrough;
11746 if (Context.getLangOpts().CPlusPlus) {
11747 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11748 // operand contextually converted to bool.
11749 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11750 ScalarTypeToBooleanCastKind(resultType));
11751 } else if (Context.getLangOpts().OpenCL &&
11752 Context.getLangOpts().OpenCLVersion < 120) {
11753 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11754 // operate on scalar float types.
11755 if (!resultType->isIntegerType() && !resultType->isPointerType())
11756 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11757 << resultType << Input.get()->getSourceRange());
11759 } else if (resultType->isExtVectorType()) {
11760 if (Context.getLangOpts().OpenCL &&
11761 Context.getLangOpts().OpenCLVersion < 120) {
11762 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11763 // operate on vector float types.
11764 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11765 if (!T->isIntegerType())
11766 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11767 << resultType << Input.get()->getSourceRange());
11769 // Vector logical not returns the signed variant of the operand type.
11770 resultType = GetSignedVectorType(resultType);
11773 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11774 << resultType << Input.get()->getSourceRange());
11777 // LNot always has type int. C99 6.5.3.3p5.
11778 // In C++, it's bool. C++ 5.3.1p8
11779 resultType = Context.getLogicalOperationType();
11783 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11784 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11785 // complex l-values to ordinary l-values and all other values to r-values.
11786 if (Input.isInvalid()) return ExprError();
11787 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11788 if (Input.get()->getValueKind() != VK_RValue &&
11789 Input.get()->getObjectKind() == OK_Ordinary)
11790 VK = Input.get()->getValueKind();
11791 } else if (!getLangOpts().CPlusPlus) {
11792 // In C, a volatile scalar is read by __imag. In C++, it is not.
11793 Input = DefaultLvalueConversion(Input.get());
11798 resultType = Input.get()->getType();
11799 VK = Input.get()->getValueKind();
11800 OK = Input.get()->getObjectKind();
11803 if (resultType.isNull() || Input.isInvalid())
11804 return ExprError();
11806 // Check for array bounds violations in the operand of the UnaryOperator,
11807 // except for the '*' and '&' operators that have to be handled specially
11808 // by CheckArrayAccess (as there are special cases like &array[arraysize]
11809 // that are explicitly defined as valid by the standard).
11810 if (Opc != UO_AddrOf && Opc != UO_Deref)
11811 CheckArrayAccess(Input.get());
11813 return new (Context)
11814 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11817 /// \brief Determine whether the given expression is a qualified member
11818 /// access expression, of a form that could be turned into a pointer to member
11819 /// with the address-of operator.
11820 static bool isQualifiedMemberAccess(Expr *E) {
11821 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11822 if (!DRE->getQualifier())
11825 ValueDecl *VD = DRE->getDecl();
11826 if (!VD->isCXXClassMember())
11829 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11831 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11832 return Method->isInstance();
11837 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11838 if (!ULE->getQualifier())
11841 for (NamedDecl *D : ULE->decls()) {
11842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11843 if (Method->isInstance())
11846 // Overload set does not contain methods.
11857 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11858 UnaryOperatorKind Opc, Expr *Input) {
11859 // First things first: handle placeholders so that the
11860 // overloaded-operator check considers the right type.
11861 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11862 // Increment and decrement of pseudo-object references.
11863 if (pty->getKind() == BuiltinType::PseudoObject &&
11864 UnaryOperator::isIncrementDecrementOp(Opc))
11865 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11867 // extension is always a builtin operator.
11868 if (Opc == UO_Extension)
11869 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11871 // & gets special logic for several kinds of placeholder.
11872 // The builtin code knows what to do.
11873 if (Opc == UO_AddrOf &&
11874 (pty->getKind() == BuiltinType::Overload ||
11875 pty->getKind() == BuiltinType::UnknownAny ||
11876 pty->getKind() == BuiltinType::BoundMember))
11877 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11879 // Anything else needs to be handled now.
11880 ExprResult Result = CheckPlaceholderExpr(Input);
11881 if (Result.isInvalid()) return ExprError();
11882 Input = Result.get();
11885 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11886 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11887 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11888 // Find all of the overloaded operators visible from this
11889 // point. We perform both an operator-name lookup from the local
11890 // scope and an argument-dependent lookup based on the types of
11892 UnresolvedSet<16> Functions;
11893 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11894 if (S && OverOp != OO_None)
11895 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11898 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11901 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11904 // Unary Operators. 'Tok' is the token for the operator.
11905 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11906 tok::TokenKind Op, Expr *Input) {
11907 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11910 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11911 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11912 LabelDecl *TheDecl) {
11913 TheDecl->markUsed(Context);
11914 // Create the AST node. The address of a label always has type 'void*'.
11915 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11916 Context.getPointerType(Context.VoidTy));
11919 /// Given the last statement in a statement-expression, check whether
11920 /// the result is a producing expression (like a call to an
11921 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11922 /// release out of the full-expression. Otherwise, return null.
11924 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11925 // Should always be wrapped with one of these.
11926 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11927 if (!cleanups) return nullptr;
11929 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11930 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11933 // Splice out the cast. This shouldn't modify any interesting
11934 // features of the statement.
11935 Expr *producer = cast->getSubExpr();
11936 assert(producer->getType() == cast->getType());
11937 assert(producer->getValueKind() == cast->getValueKind());
11938 cleanups->setSubExpr(producer);
11942 void Sema::ActOnStartStmtExpr() {
11943 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11946 void Sema::ActOnStmtExprError() {
11947 // Note that function is also called by TreeTransform when leaving a
11948 // StmtExpr scope without rebuilding anything.
11950 DiscardCleanupsInEvaluationContext();
11951 PopExpressionEvaluationContext();
11955 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11956 SourceLocation RPLoc) { // "({..})"
11957 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11958 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11960 if (hasAnyUnrecoverableErrorsInThisFunction())
11961 DiscardCleanupsInEvaluationContext();
11962 assert(!Cleanup.exprNeedsCleanups() &&
11963 "cleanups within StmtExpr not correctly bound!");
11964 PopExpressionEvaluationContext();
11966 // FIXME: there are a variety of strange constraints to enforce here, for
11967 // example, it is not possible to goto into a stmt expression apparently.
11968 // More semantic analysis is needed.
11970 // If there are sub-stmts in the compound stmt, take the type of the last one
11971 // as the type of the stmtexpr.
11972 QualType Ty = Context.VoidTy;
11973 bool StmtExprMayBindToTemp = false;
11974 if (!Compound->body_empty()) {
11975 Stmt *LastStmt = Compound->body_back();
11976 LabelStmt *LastLabelStmt = nullptr;
11977 // If LastStmt is a label, skip down through into the body.
11978 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11979 LastLabelStmt = Label;
11980 LastStmt = Label->getSubStmt();
11983 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11984 // Do function/array conversion on the last expression, but not
11985 // lvalue-to-rvalue. However, initialize an unqualified type.
11986 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11987 if (LastExpr.isInvalid())
11988 return ExprError();
11989 Ty = LastExpr.get()->getType().getUnqualifiedType();
11991 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11992 // In ARC, if the final expression ends in a consume, splice
11993 // the consume out and bind it later. In the alternate case
11994 // (when dealing with a retainable type), the result
11995 // initialization will create a produce. In both cases the
11996 // result will be +1, and we'll need to balance that out with
11998 if (Expr *rebuiltLastStmt
11999 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12000 LastExpr = rebuiltLastStmt;
12002 LastExpr = PerformCopyInitialization(
12003 InitializedEntity::InitializeResult(LPLoc,
12010 if (LastExpr.isInvalid())
12011 return ExprError();
12012 if (LastExpr.get() != nullptr) {
12013 if (!LastLabelStmt)
12014 Compound->setLastStmt(LastExpr.get());
12016 LastLabelStmt->setSubStmt(LastExpr.get());
12017 StmtExprMayBindToTemp = true;
12023 // FIXME: Check that expression type is complete/non-abstract; statement
12024 // expressions are not lvalues.
12025 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12026 if (StmtExprMayBindToTemp)
12027 return MaybeBindToTemporary(ResStmtExpr);
12028 return ResStmtExpr;
12031 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12032 TypeSourceInfo *TInfo,
12033 ArrayRef<OffsetOfComponent> Components,
12034 SourceLocation RParenLoc) {
12035 QualType ArgTy = TInfo->getType();
12036 bool Dependent = ArgTy->isDependentType();
12037 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12039 // We must have at least one component that refers to the type, and the first
12040 // one is known to be a field designator. Verify that the ArgTy represents
12041 // a struct/union/class.
12042 if (!Dependent && !ArgTy->isRecordType())
12043 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12044 << ArgTy << TypeRange);
12046 // Type must be complete per C99 7.17p3 because a declaring a variable
12047 // with an incomplete type would be ill-formed.
12049 && RequireCompleteType(BuiltinLoc, ArgTy,
12050 diag::err_offsetof_incomplete_type, TypeRange))
12051 return ExprError();
12053 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12054 // GCC extension, diagnose them.
12055 // FIXME: This diagnostic isn't actually visible because the location is in
12056 // a system header!
12057 if (Components.size() != 1)
12058 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12059 << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12061 bool DidWarnAboutNonPOD = false;
12062 QualType CurrentType = ArgTy;
12063 SmallVector<OffsetOfNode, 4> Comps;
12064 SmallVector<Expr*, 4> Exprs;
12065 for (const OffsetOfComponent &OC : Components) {
12066 if (OC.isBrackets) {
12067 // Offset of an array sub-field. TODO: Should we allow vector elements?
12068 if (!CurrentType->isDependentType()) {
12069 const ArrayType *AT = Context.getAsArrayType(CurrentType);
12071 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12073 CurrentType = AT->getElementType();
12075 CurrentType = Context.DependentTy;
12077 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12078 if (IdxRval.isInvalid())
12079 return ExprError();
12080 Expr *Idx = IdxRval.get();
12082 // The expression must be an integral expression.
12083 // FIXME: An integral constant expression?
12084 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12085 !Idx->getType()->isIntegerType())
12086 return ExprError(Diag(Idx->getLocStart(),
12087 diag::err_typecheck_subscript_not_integer)
12088 << Idx->getSourceRange());
12090 // Record this array index.
12091 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12092 Exprs.push_back(Idx);
12096 // Offset of a field.
12097 if (CurrentType->isDependentType()) {
12098 // We have the offset of a field, but we can't look into the dependent
12099 // type. Just record the identifier of the field.
12100 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12101 CurrentType = Context.DependentTy;
12105 // We need to have a complete type to look into.
12106 if (RequireCompleteType(OC.LocStart, CurrentType,
12107 diag::err_offsetof_incomplete_type))
12108 return ExprError();
12110 // Look for the designated field.
12111 const RecordType *RC = CurrentType->getAs<RecordType>();
12113 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12115 RecordDecl *RD = RC->getDecl();
12117 // C++ [lib.support.types]p5:
12118 // The macro offsetof accepts a restricted set of type arguments in this
12119 // International Standard. type shall be a POD structure or a POD union
12121 // C++11 [support.types]p4:
12122 // If type is not a standard-layout class (Clause 9), the results are
12124 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12125 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12127 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12128 : diag::ext_offsetof_non_pod_type;
12130 if (!IsSafe && !DidWarnAboutNonPOD &&
12131 DiagRuntimeBehavior(BuiltinLoc, nullptr,
12133 << SourceRange(Components[0].LocStart, OC.LocEnd)
12135 DidWarnAboutNonPOD = true;
12138 // Look for the field.
12139 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12140 LookupQualifiedName(R, RD);
12141 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12142 IndirectFieldDecl *IndirectMemberDecl = nullptr;
12144 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12145 MemberDecl = IndirectMemberDecl->getAnonField();
12149 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12150 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12154 // (If the specified member is a bit-field, the behavior is undefined.)
12156 // We diagnose this as an error.
12157 if (MemberDecl->isBitField()) {
12158 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12159 << MemberDecl->getDeclName()
12160 << SourceRange(BuiltinLoc, RParenLoc);
12161 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12162 return ExprError();
12165 RecordDecl *Parent = MemberDecl->getParent();
12166 if (IndirectMemberDecl)
12167 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12169 // If the member was found in a base class, introduce OffsetOfNodes for
12170 // the base class indirections.
12171 CXXBasePaths Paths;
12172 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12174 if (Paths.getDetectedVirtual()) {
12175 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12176 << MemberDecl->getDeclName()
12177 << SourceRange(BuiltinLoc, RParenLoc);
12178 return ExprError();
12181 CXXBasePath &Path = Paths.front();
12182 for (const CXXBasePathElement &B : Path)
12183 Comps.push_back(OffsetOfNode(B.Base));
12186 if (IndirectMemberDecl) {
12187 for (auto *FI : IndirectMemberDecl->chain()) {
12188 assert(isa<FieldDecl>(FI));
12189 Comps.push_back(OffsetOfNode(OC.LocStart,
12190 cast<FieldDecl>(FI), OC.LocEnd));
12193 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12195 CurrentType = MemberDecl->getType().getNonReferenceType();
12198 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12199 Comps, Exprs, RParenLoc);
12202 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12203 SourceLocation BuiltinLoc,
12204 SourceLocation TypeLoc,
12205 ParsedType ParsedArgTy,
12206 ArrayRef<OffsetOfComponent> Components,
12207 SourceLocation RParenLoc) {
12209 TypeSourceInfo *ArgTInfo;
12210 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12211 if (ArgTy.isNull())
12212 return ExprError();
12215 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12217 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12221 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12223 Expr *LHSExpr, Expr *RHSExpr,
12224 SourceLocation RPLoc) {
12225 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12227 ExprValueKind VK = VK_RValue;
12228 ExprObjectKind OK = OK_Ordinary;
12230 bool ValueDependent = false;
12231 bool CondIsTrue = false;
12232 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12233 resType = Context.DependentTy;
12234 ValueDependent = true;
12236 // The conditional expression is required to be a constant expression.
12237 llvm::APSInt condEval(32);
12239 = VerifyIntegerConstantExpression(CondExpr, &condEval,
12240 diag::err_typecheck_choose_expr_requires_constant, false);
12241 if (CondICE.isInvalid())
12242 return ExprError();
12243 CondExpr = CondICE.get();
12244 CondIsTrue = condEval.getZExtValue();
12246 // If the condition is > zero, then the AST type is the same as the LSHExpr.
12247 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12249 resType = ActiveExpr->getType();
12250 ValueDependent = ActiveExpr->isValueDependent();
12251 VK = ActiveExpr->getValueKind();
12252 OK = ActiveExpr->getObjectKind();
12255 return new (Context)
12256 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12257 CondIsTrue, resType->isDependentType(), ValueDependent);
12260 //===----------------------------------------------------------------------===//
12261 // Clang Extensions.
12262 //===----------------------------------------------------------------------===//
12264 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12265 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12266 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12268 if (LangOpts.CPlusPlus) {
12269 Decl *ManglingContextDecl;
12270 if (MangleNumberingContext *MCtx =
12271 getCurrentMangleNumberContext(Block->getDeclContext(),
12272 ManglingContextDecl)) {
12273 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12274 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12278 PushBlockScope(CurScope, Block);
12279 CurContext->addDecl(Block);
12281 PushDeclContext(CurScope, Block);
12283 CurContext = Block;
12285 getCurBlock()->HasImplicitReturnType = true;
12287 // Enter a new evaluation context to insulate the block from any
12288 // cleanups from the enclosing full-expression.
12289 PushExpressionEvaluationContext(
12290 ExpressionEvaluationContext::PotentiallyEvaluated);
12293 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12295 assert(ParamInfo.getIdentifier() == nullptr &&
12296 "block-id should have no identifier!");
12297 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12298 BlockScopeInfo *CurBlock = getCurBlock();
12300 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12301 QualType T = Sig->getType();
12303 // FIXME: We should allow unexpanded parameter packs here, but that would,
12304 // in turn, make the block expression contain unexpanded parameter packs.
12305 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12306 // Drop the parameters.
12307 FunctionProtoType::ExtProtoInfo EPI;
12308 EPI.HasTrailingReturn = false;
12309 EPI.TypeQuals |= DeclSpec::TQ_const;
12310 T = Context.getFunctionType(Context.DependentTy, None, EPI);
12311 Sig = Context.getTrivialTypeSourceInfo(T);
12314 // GetTypeForDeclarator always produces a function type for a block
12315 // literal signature. Furthermore, it is always a FunctionProtoType
12316 // unless the function was written with a typedef.
12317 assert(T->isFunctionType() &&
12318 "GetTypeForDeclarator made a non-function block signature");
12320 // Look for an explicit signature in that function type.
12321 FunctionProtoTypeLoc ExplicitSignature;
12323 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12324 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12326 // Check whether that explicit signature was synthesized by
12327 // GetTypeForDeclarator. If so, don't save that as part of the
12328 // written signature.
12329 if (ExplicitSignature.getLocalRangeBegin() ==
12330 ExplicitSignature.getLocalRangeEnd()) {
12331 // This would be much cheaper if we stored TypeLocs instead of
12332 // TypeSourceInfos.
12333 TypeLoc Result = ExplicitSignature.getReturnLoc();
12334 unsigned Size = Result.getFullDataSize();
12335 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12336 Sig->getTypeLoc().initializeFullCopy(Result, Size);
12338 ExplicitSignature = FunctionProtoTypeLoc();
12342 CurBlock->TheDecl->setSignatureAsWritten(Sig);
12343 CurBlock->FunctionType = T;
12345 const FunctionType *Fn = T->getAs<FunctionType>();
12346 QualType RetTy = Fn->getReturnType();
12348 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12350 CurBlock->TheDecl->setIsVariadic(isVariadic);
12352 // Context.DependentTy is used as a placeholder for a missing block
12353 // return type. TODO: what should we do with declarators like:
12355 // If the answer is "apply template argument deduction"....
12356 if (RetTy != Context.DependentTy) {
12357 CurBlock->ReturnType = RetTy;
12358 CurBlock->TheDecl->setBlockMissingReturnType(false);
12359 CurBlock->HasImplicitReturnType = false;
12362 // Push block parameters from the declarator if we had them.
12363 SmallVector<ParmVarDecl*, 8> Params;
12364 if (ExplicitSignature) {
12365 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12366 ParmVarDecl *Param = ExplicitSignature.getParam(I);
12367 if (Param->getIdentifier() == nullptr &&
12368 !Param->isImplicit() &&
12369 !Param->isInvalidDecl() &&
12370 !getLangOpts().CPlusPlus)
12371 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12372 Params.push_back(Param);
12375 // Fake up parameter variables if we have a typedef, like
12376 // ^ fntype { ... }
12377 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12378 for (const auto &I : Fn->param_types()) {
12379 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12380 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12381 Params.push_back(Param);
12385 // Set the parameters on the block decl.
12386 if (!Params.empty()) {
12387 CurBlock->TheDecl->setParams(Params);
12388 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12389 /*CheckParameterNames=*/false);
12392 // Finally we can process decl attributes.
12393 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12395 // Put the parameter variables in scope.
12396 for (auto AI : CurBlock->TheDecl->parameters()) {
12397 AI->setOwningFunction(CurBlock->TheDecl);
12399 // If this has an identifier, add it to the scope stack.
12400 if (AI->getIdentifier()) {
12401 CheckShadow(CurBlock->TheScope, AI);
12403 PushOnScopeChains(AI, CurBlock->TheScope);
12408 /// ActOnBlockError - If there is an error parsing a block, this callback
12409 /// is invoked to pop the information about the block from the action impl.
12410 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12411 // Leave the expression-evaluation context.
12412 DiscardCleanupsInEvaluationContext();
12413 PopExpressionEvaluationContext();
12415 // Pop off CurBlock, handle nested blocks.
12417 PopFunctionScopeInfo();
12420 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12421 /// literal was successfully completed. ^(int x){...}
12422 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12423 Stmt *Body, Scope *CurScope) {
12424 // If blocks are disabled, emit an error.
12425 if (!LangOpts.Blocks)
12426 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12428 // Leave the expression-evaluation context.
12429 if (hasAnyUnrecoverableErrorsInThisFunction())
12430 DiscardCleanupsInEvaluationContext();
12431 assert(!Cleanup.exprNeedsCleanups() &&
12432 "cleanups within block not correctly bound!");
12433 PopExpressionEvaluationContext();
12435 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12437 if (BSI->HasImplicitReturnType)
12438 deduceClosureReturnType(*BSI);
12442 QualType RetTy = Context.VoidTy;
12443 if (!BSI->ReturnType.isNull())
12444 RetTy = BSI->ReturnType;
12446 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12449 // Set the captured variables on the block.
12450 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12451 SmallVector<BlockDecl::Capture, 4> Captures;
12452 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12453 if (Cap.isThisCapture())
12455 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12456 Cap.isNested(), Cap.getInitExpr());
12457 Captures.push_back(NewCap);
12459 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12461 // If the user wrote a function type in some form, try to use that.
12462 if (!BSI->FunctionType.isNull()) {
12463 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12465 FunctionType::ExtInfo Ext = FTy->getExtInfo();
12466 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12468 // Turn protoless block types into nullary block types.
12469 if (isa<FunctionNoProtoType>(FTy)) {
12470 FunctionProtoType::ExtProtoInfo EPI;
12472 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12474 // Otherwise, if we don't need to change anything about the function type,
12475 // preserve its sugar structure.
12476 } else if (FTy->getReturnType() == RetTy &&
12477 (!NoReturn || FTy->getNoReturnAttr())) {
12478 BlockTy = BSI->FunctionType;
12480 // Otherwise, make the minimal modifications to the function type.
12482 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12483 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12484 EPI.TypeQuals = 0; // FIXME: silently?
12486 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12489 // If we don't have a function type, just build one from nothing.
12491 FunctionProtoType::ExtProtoInfo EPI;
12492 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12493 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12496 DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12497 BlockTy = Context.getBlockPointerType(BlockTy);
12499 // If needed, diagnose invalid gotos and switches in the block.
12500 if (getCurFunction()->NeedsScopeChecking() &&
12501 !PP.isCodeCompletionEnabled())
12502 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12504 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12506 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12507 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
12509 // Try to apply the named return value optimization. We have to check again
12510 // if we can do this, though, because blocks keep return statements around
12511 // to deduce an implicit return type.
12512 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12513 !BSI->TheDecl->isDependentContext())
12514 computeNRVO(Body, BSI);
12516 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12517 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12518 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12520 // If the block isn't obviously global, i.e. it captures anything at
12521 // all, then we need to do a few things in the surrounding context:
12522 if (Result->getBlockDecl()->hasCaptures()) {
12523 // First, this expression has a new cleanup object.
12524 ExprCleanupObjects.push_back(Result->getBlockDecl());
12525 Cleanup.setExprNeedsCleanups(true);
12527 // It also gets a branch-protected scope if any of the captured
12528 // variables needs destruction.
12529 for (const auto &CI : Result->getBlockDecl()->captures()) {
12530 const VarDecl *var = CI.getVariable();
12531 if (var->getType().isDestructedType() != QualType::DK_none) {
12532 getCurFunction()->setHasBranchProtectedScope();
12541 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12542 SourceLocation RPLoc) {
12543 TypeSourceInfo *TInfo;
12544 GetTypeFromParser(Ty, &TInfo);
12545 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12548 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12549 Expr *E, TypeSourceInfo *TInfo,
12550 SourceLocation RPLoc) {
12551 Expr *OrigExpr = E;
12554 // CUDA device code does not support varargs.
12555 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12556 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12557 CUDAFunctionTarget T = IdentifyCUDATarget(F);
12558 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12559 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12563 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12564 // as Microsoft ABI on an actual Microsoft platform, where
12565 // __builtin_ms_va_list and __builtin_va_list are the same.)
12566 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12567 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12568 QualType MSVaListType = Context.getBuiltinMSVaListType();
12569 if (Context.hasSameType(MSVaListType, E->getType())) {
12570 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12571 return ExprError();
12576 // Get the va_list type
12577 QualType VaListType = Context.getBuiltinVaListType();
12579 if (VaListType->isArrayType()) {
12580 // Deal with implicit array decay; for example, on x86-64,
12581 // va_list is an array, but it's supposed to decay to
12582 // a pointer for va_arg.
12583 VaListType = Context.getArrayDecayedType(VaListType);
12584 // Make sure the input expression also decays appropriately.
12585 ExprResult Result = UsualUnaryConversions(E);
12586 if (Result.isInvalid())
12587 return ExprError();
12589 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12590 // If va_list is a record type and we are compiling in C++ mode,
12591 // check the argument using reference binding.
12592 InitializedEntity Entity = InitializedEntity::InitializeParameter(
12593 Context, Context.getLValueReferenceType(VaListType), false);
12594 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12595 if (Init.isInvalid())
12596 return ExprError();
12597 E = Init.getAs<Expr>();
12599 // Otherwise, the va_list argument must be an l-value because
12600 // it is modified by va_arg.
12601 if (!E->isTypeDependent() &&
12602 CheckForModifiableLvalue(E, BuiltinLoc, *this))
12603 return ExprError();
12607 if (!IsMS && !E->isTypeDependent() &&
12608 !Context.hasSameType(VaListType, E->getType()))
12609 return ExprError(Diag(E->getLocStart(),
12610 diag::err_first_argument_to_va_arg_not_of_type_va_list)
12611 << OrigExpr->getType() << E->getSourceRange());
12613 if (!TInfo->getType()->isDependentType()) {
12614 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12615 diag::err_second_parameter_to_va_arg_incomplete,
12616 TInfo->getTypeLoc()))
12617 return ExprError();
12619 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12621 diag::err_second_parameter_to_va_arg_abstract,
12622 TInfo->getTypeLoc()))
12623 return ExprError();
12625 if (!TInfo->getType().isPODType(Context)) {
12626 Diag(TInfo->getTypeLoc().getBeginLoc(),
12627 TInfo->getType()->isObjCLifetimeType()
12628 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12629 : diag::warn_second_parameter_to_va_arg_not_pod)
12630 << TInfo->getType()
12631 << TInfo->getTypeLoc().getSourceRange();
12634 // Check for va_arg where arguments of the given type will be promoted
12635 // (i.e. this va_arg is guaranteed to have undefined behavior).
12636 QualType PromoteType;
12637 if (TInfo->getType()->isPromotableIntegerType()) {
12638 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12639 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12640 PromoteType = QualType();
12642 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12643 PromoteType = Context.DoubleTy;
12644 if (!PromoteType.isNull())
12645 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12646 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12647 << TInfo->getType()
12649 << TInfo->getTypeLoc().getSourceRange());
12652 QualType T = TInfo->getType().getNonLValueExprType(Context);
12653 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12656 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12657 // The type of __null will be int or long, depending on the size of
12658 // pointers on the target.
12660 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12661 if (pw == Context.getTargetInfo().getIntWidth())
12662 Ty = Context.IntTy;
12663 else if (pw == Context.getTargetInfo().getLongWidth())
12664 Ty = Context.LongTy;
12665 else if (pw == Context.getTargetInfo().getLongLongWidth())
12666 Ty = Context.LongLongTy;
12668 llvm_unreachable("I don't know size of pointer!");
12671 return new (Context) GNUNullExpr(Ty, TokenLoc);
12674 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12676 if (!getLangOpts().ObjC1)
12679 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12683 if (!PT->isObjCIdType()) {
12684 // Check if the destination is the 'NSString' interface.
12685 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12686 if (!ID || !ID->getIdentifier()->isStr("NSString"))
12690 // Ignore any parens, implicit casts (should only be
12691 // array-to-pointer decays), and not-so-opaque values. The last is
12692 // important for making this trigger for property assignments.
12693 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12694 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12695 if (OV->getSourceExpr())
12696 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12698 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12699 if (!SL || !SL->isAscii())
12702 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12703 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12704 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12709 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12710 const Expr *SrcExpr) {
12711 if (!DstType->isFunctionPointerType() ||
12712 !SrcExpr->getType()->isFunctionType())
12715 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12719 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12723 return !S.checkAddressOfFunctionIsAvailable(FD,
12725 SrcExpr->getLocStart());
12728 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12729 SourceLocation Loc,
12730 QualType DstType, QualType SrcType,
12731 Expr *SrcExpr, AssignmentAction Action,
12732 bool *Complained) {
12734 *Complained = false;
12736 // Decode the result (notice that AST's are still created for extensions).
12737 bool CheckInferredResultType = false;
12738 bool isInvalid = false;
12739 unsigned DiagKind = 0;
12741 ConversionFixItGenerator ConvHints;
12742 bool MayHaveConvFixit = false;
12743 bool MayHaveFunctionDiff = false;
12744 const ObjCInterfaceDecl *IFace = nullptr;
12745 const ObjCProtocolDecl *PDecl = nullptr;
12749 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12753 DiagKind = diag::ext_typecheck_convert_pointer_int;
12754 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12755 MayHaveConvFixit = true;
12758 DiagKind = diag::ext_typecheck_convert_int_pointer;
12759 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12760 MayHaveConvFixit = true;
12762 case IncompatiblePointer:
12763 if (Action == AA_Passing_CFAudited)
12764 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12765 else if (SrcType->isFunctionPointerType() &&
12766 DstType->isFunctionPointerType())
12767 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12769 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12771 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12772 SrcType->isObjCObjectPointerType();
12773 if (Hint.isNull() && !CheckInferredResultType) {
12774 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12776 else if (CheckInferredResultType) {
12777 SrcType = SrcType.getUnqualifiedType();
12778 DstType = DstType.getUnqualifiedType();
12780 MayHaveConvFixit = true;
12782 case IncompatiblePointerSign:
12783 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12785 case FunctionVoidPointer:
12786 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12788 case IncompatiblePointerDiscardsQualifiers: {
12789 // Perform array-to-pointer decay if necessary.
12790 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12792 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12793 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12794 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12795 DiagKind = diag::err_typecheck_incompatible_address_space;
12799 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12800 DiagKind = diag::err_typecheck_incompatible_ownership;
12804 llvm_unreachable("unknown error case for discarding qualifiers!");
12807 case CompatiblePointerDiscardsQualifiers:
12808 // If the qualifiers lost were because we were applying the
12809 // (deprecated) C++ conversion from a string literal to a char*
12810 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
12811 // Ideally, this check would be performed in
12812 // checkPointerTypesForAssignment. However, that would require a
12813 // bit of refactoring (so that the second argument is an
12814 // expression, rather than a type), which should be done as part
12815 // of a larger effort to fix checkPointerTypesForAssignment for
12817 if (getLangOpts().CPlusPlus &&
12818 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12820 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12822 case IncompatibleNestedPointerQualifiers:
12823 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12825 case IntToBlockPointer:
12826 DiagKind = diag::err_int_to_block_pointer;
12828 case IncompatibleBlockPointer:
12829 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12831 case IncompatibleObjCQualifiedId: {
12832 if (SrcType->isObjCQualifiedIdType()) {
12833 const ObjCObjectPointerType *srcOPT =
12834 SrcType->getAs<ObjCObjectPointerType>();
12835 for (auto *srcProto : srcOPT->quals()) {
12839 if (const ObjCInterfaceType *IFaceT =
12840 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12841 IFace = IFaceT->getDecl();
12843 else if (DstType->isObjCQualifiedIdType()) {
12844 const ObjCObjectPointerType *dstOPT =
12845 DstType->getAs<ObjCObjectPointerType>();
12846 for (auto *dstProto : dstOPT->quals()) {
12850 if (const ObjCInterfaceType *IFaceT =
12851 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12852 IFace = IFaceT->getDecl();
12854 DiagKind = diag::warn_incompatible_qualified_id;
12857 case IncompatibleVectors:
12858 DiagKind = diag::warn_incompatible_vectors;
12860 case IncompatibleObjCWeakRef:
12861 DiagKind = diag::err_arc_weak_unavailable_assign;
12864 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12866 *Complained = true;
12870 DiagKind = diag::err_typecheck_convert_incompatible;
12871 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12872 MayHaveConvFixit = true;
12874 MayHaveFunctionDiff = true;
12878 QualType FirstType, SecondType;
12881 case AA_Initializing:
12882 // The destination type comes first.
12883 FirstType = DstType;
12884 SecondType = SrcType;
12889 case AA_Passing_CFAudited:
12890 case AA_Converting:
12893 // The source type comes first.
12894 FirstType = SrcType;
12895 SecondType = DstType;
12899 PartialDiagnostic FDiag = PDiag(DiagKind);
12900 if (Action == AA_Passing_CFAudited)
12901 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12903 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12905 // If we can fix the conversion, suggest the FixIts.
12906 assert(ConvHints.isNull() || Hint.isNull());
12907 if (!ConvHints.isNull()) {
12908 for (FixItHint &H : ConvHints.Hints)
12913 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12915 if (MayHaveFunctionDiff)
12916 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12919 if (DiagKind == diag::warn_incompatible_qualified_id &&
12920 PDecl && IFace && !IFace->hasDefinition())
12921 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12922 << IFace->getName() << PDecl->getName();
12924 if (SecondType == Context.OverloadTy)
12925 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12926 FirstType, /*TakingAddress=*/true);
12928 if (CheckInferredResultType)
12929 EmitRelatedResultTypeNote(SrcExpr);
12931 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12932 EmitRelatedResultTypeNoteForReturn(DstType);
12935 *Complained = true;
12939 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12940 llvm::APSInt *Result) {
12941 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12943 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12944 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12948 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12951 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12952 llvm::APSInt *Result,
12955 class IDDiagnoser : public VerifyICEDiagnoser {
12959 IDDiagnoser(unsigned DiagID)
12960 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12962 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12963 S.Diag(Loc, DiagID) << SR;
12965 } Diagnoser(DiagID);
12967 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12970 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12972 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12976 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12977 VerifyICEDiagnoser &Diagnoser,
12979 SourceLocation DiagLoc = E->getLocStart();
12981 if (getLangOpts().CPlusPlus11) {
12982 // C++11 [expr.const]p5:
12983 // If an expression of literal class type is used in a context where an
12984 // integral constant expression is required, then that class type shall
12985 // have a single non-explicit conversion function to an integral or
12986 // unscoped enumeration type
12987 ExprResult Converted;
12988 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12990 CXX11ConvertDiagnoser(bool Silent)
12991 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12994 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12995 QualType T) override {
12996 return S.Diag(Loc, diag::err_ice_not_integral) << T;
12999 SemaDiagnosticBuilder diagnoseIncomplete(
13000 Sema &S, SourceLocation Loc, QualType T) override {
13001 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13004 SemaDiagnosticBuilder diagnoseExplicitConv(
13005 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13006 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13009 SemaDiagnosticBuilder noteExplicitConv(
13010 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13011 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13012 << ConvTy->isEnumeralType() << ConvTy;
13015 SemaDiagnosticBuilder diagnoseAmbiguous(
13016 Sema &S, SourceLocation Loc, QualType T) override {
13017 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13020 SemaDiagnosticBuilder noteAmbiguous(
13021 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13022 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13023 << ConvTy->isEnumeralType() << ConvTy;
13026 SemaDiagnosticBuilder diagnoseConversion(
13027 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13028 llvm_unreachable("conversion functions are permitted");
13030 } ConvertDiagnoser(Diagnoser.Suppress);
13032 Converted = PerformContextualImplicitConversion(DiagLoc, E,
13034 if (Converted.isInvalid())
13036 E = Converted.get();
13037 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13038 return ExprError();
13039 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13040 // An ICE must be of integral or unscoped enumeration type.
13041 if (!Diagnoser.Suppress)
13042 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13043 return ExprError();
13046 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13047 // in the non-ICE case.
13048 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13050 *Result = E->EvaluateKnownConstInt(Context);
13054 Expr::EvalResult EvalResult;
13055 SmallVector<PartialDiagnosticAt, 8> Notes;
13056 EvalResult.Diag = &Notes;
13058 // Try to evaluate the expression, and produce diagnostics explaining why it's
13059 // not a constant expression as a side-effect.
13060 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13061 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13063 // In C++11, we can rely on diagnostics being produced for any expression
13064 // which is not a constant expression. If no diagnostics were produced, then
13065 // this is a constant expression.
13066 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13068 *Result = EvalResult.Val.getInt();
13072 // If our only note is the usual "invalid subexpression" note, just point
13073 // the caret at its location rather than producing an essentially
13075 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13076 diag::note_invalid_subexpr_in_const_expr) {
13077 DiagLoc = Notes[0].first;
13081 if (!Folded || !AllowFold) {
13082 if (!Diagnoser.Suppress) {
13083 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13084 for (const PartialDiagnosticAt &Note : Notes)
13085 Diag(Note.first, Note.second);
13088 return ExprError();
13091 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13092 for (const PartialDiagnosticAt &Note : Notes)
13093 Diag(Note.first, Note.second);
13096 *Result = EvalResult.Val.getInt();
13101 // Handle the case where we conclude a expression which we speculatively
13102 // considered to be unevaluated is actually evaluated.
13103 class TransformToPE : public TreeTransform<TransformToPE> {
13104 typedef TreeTransform<TransformToPE> BaseTransform;
13107 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13109 // Make sure we redo semantic analysis
13110 bool AlwaysRebuild() { return true; }
13112 // Make sure we handle LabelStmts correctly.
13113 // FIXME: This does the right thing, but maybe we need a more general
13114 // fix to TreeTransform?
13115 StmtResult TransformLabelStmt(LabelStmt *S) {
13116 S->getDecl()->setStmt(nullptr);
13117 return BaseTransform::TransformLabelStmt(S);
13120 // We need to special-case DeclRefExprs referring to FieldDecls which
13121 // are not part of a member pointer formation; normal TreeTransforming
13122 // doesn't catch this case because of the way we represent them in the AST.
13123 // FIXME: This is a bit ugly; is it really the best way to handle this
13126 // Error on DeclRefExprs referring to FieldDecls.
13127 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13128 if (isa<FieldDecl>(E->getDecl()) &&
13129 !SemaRef.isUnevaluatedContext())
13130 return SemaRef.Diag(E->getLocation(),
13131 diag::err_invalid_non_static_member_use)
13132 << E->getDecl() << E->getSourceRange();
13134 return BaseTransform::TransformDeclRefExpr(E);
13137 // Exception: filter out member pointer formation
13138 ExprResult TransformUnaryOperator(UnaryOperator *E) {
13139 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13142 return BaseTransform::TransformUnaryOperator(E);
13145 ExprResult TransformLambdaExpr(LambdaExpr *E) {
13146 // Lambdas never need to be transformed.
13152 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13153 assert(isUnevaluatedContext() &&
13154 "Should only transform unevaluated expressions");
13155 ExprEvalContexts.back().Context =
13156 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13157 if (isUnevaluatedContext())
13159 return TransformToPE(*this).TransformExpr(E);
13163 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13164 Decl *LambdaContextDecl,
13166 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13167 LambdaContextDecl, IsDecltype);
13169 if (!MaybeODRUseExprs.empty())
13170 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13174 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13175 ReuseLambdaContextDecl_t,
13177 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13178 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13181 void Sema::PopExpressionEvaluationContext() {
13182 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13183 unsigned NumTypos = Rec.NumTypos;
13185 if (!Rec.Lambdas.empty()) {
13186 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13188 if (Rec.isUnevaluated()) {
13189 // C++11 [expr.prim.lambda]p2:
13190 // A lambda-expression shall not appear in an unevaluated operand
13192 D = diag::err_lambda_unevaluated_operand;
13194 // C++1y [expr.const]p2:
13195 // A conditional-expression e is a core constant expression unless the
13196 // evaluation of e, following the rules of the abstract machine, would
13197 // evaluate [...] a lambda-expression.
13198 D = diag::err_lambda_in_constant_expression;
13201 // C++1z allows lambda expressions as core constant expressions.
13202 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13203 // 1607) from appearing within template-arguments and array-bounds that
13204 // are part of function-signatures. Be mindful that P0315 (Lambdas in
13205 // unevaluated contexts) might lift some of these restrictions in a
13207 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13208 for (const auto *L : Rec.Lambdas)
13209 Diag(L->getLocStart(), D);
13211 // Mark the capture expressions odr-used. This was deferred
13212 // during lambda expression creation.
13213 for (auto *Lambda : Rec.Lambdas) {
13214 for (auto *C : Lambda->capture_inits())
13215 MarkDeclarationsReferencedInExpr(C);
13220 // When are coming out of an unevaluated context, clear out any
13221 // temporaries that we may have created as part of the evaluation of
13222 // the expression in that context: they aren't relevant because they
13223 // will never be constructed.
13224 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13225 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13226 ExprCleanupObjects.end());
13227 Cleanup = Rec.ParentCleanup;
13228 CleanupVarDeclMarking();
13229 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13230 // Otherwise, merge the contexts together.
13232 Cleanup.mergeFrom(Rec.ParentCleanup);
13233 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13234 Rec.SavedMaybeODRUseExprs.end());
13237 // Pop the current expression evaluation context off the stack.
13238 ExprEvalContexts.pop_back();
13240 if (!ExprEvalContexts.empty())
13241 ExprEvalContexts.back().NumTypos += NumTypos;
13243 assert(NumTypos == 0 && "There are outstanding typos after popping the "
13244 "last ExpressionEvaluationContextRecord");
13247 void Sema::DiscardCleanupsInEvaluationContext() {
13248 ExprCleanupObjects.erase(
13249 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13250 ExprCleanupObjects.end());
13252 MaybeODRUseExprs.clear();
13255 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13256 if (!E->getType()->isVariablyModifiedType())
13258 return TransformToPotentiallyEvaluated(E);
13261 /// Are we within a context in which some evaluation could be performed (be it
13262 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13263 /// captured by C++'s idea of an "unevaluated context".
13264 static bool isEvaluatableContext(Sema &SemaRef) {
13265 switch (SemaRef.ExprEvalContexts.back().Context) {
13266 case Sema::ExpressionEvaluationContext::Unevaluated:
13267 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13268 case Sema::ExpressionEvaluationContext::DiscardedStatement:
13269 // Expressions in this context are never evaluated.
13272 case Sema::ExpressionEvaluationContext::UnevaluatedList:
13273 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13274 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13275 // Expressions in this context could be evaluated.
13278 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13279 // Referenced declarations will only be used if the construct in the
13280 // containing expression is used, at which point we'll be given another
13281 // turn to mark them.
13284 llvm_unreachable("Invalid context");
13287 /// Are we within a context in which references to resolved functions or to
13288 /// variables result in odr-use?
13289 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13290 // An expression in a template is not really an expression until it's been
13291 // instantiated, so it doesn't trigger odr-use.
13292 if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13295 switch (SemaRef.ExprEvalContexts.back().Context) {
13296 case Sema::ExpressionEvaluationContext::Unevaluated:
13297 case Sema::ExpressionEvaluationContext::UnevaluatedList:
13298 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13299 case Sema::ExpressionEvaluationContext::DiscardedStatement:
13302 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13303 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13306 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13309 llvm_unreachable("Invalid context");
13312 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13313 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13314 return Func->isConstexpr() &&
13315 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13318 /// \brief Mark a function referenced, and check whether it is odr-used
13319 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13320 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13321 bool MightBeOdrUse) {
13322 assert(Func && "No function?");
13324 Func->setReferenced();
13326 // C++11 [basic.def.odr]p3:
13327 // A function whose name appears as a potentially-evaluated expression is
13328 // odr-used if it is the unique lookup result or the selected member of a
13329 // set of overloaded functions [...].
13331 // We (incorrectly) mark overload resolution as an unevaluated context, so we
13332 // can just check that here.
13333 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13335 // Determine whether we require a function definition to exist, per
13336 // C++11 [temp.inst]p3:
13337 // Unless a function template specialization has been explicitly
13338 // instantiated or explicitly specialized, the function template
13339 // specialization is implicitly instantiated when the specialization is
13340 // referenced in a context that requires a function definition to exist.
13342 // That is either when this is an odr-use, or when a usage of a constexpr
13343 // function occurs within an evaluatable context.
13344 bool NeedDefinition =
13345 OdrUse || (isEvaluatableContext(*this) &&
13346 isImplicitlyDefinableConstexprFunction(Func));
13348 // C++14 [temp.expl.spec]p6:
13349 // If a template [...] is explicitly specialized then that specialization
13350 // shall be declared before the first use of that specialization that would
13351 // cause an implicit instantiation to take place, in every translation unit
13352 // in which such a use occurs
13353 if (NeedDefinition &&
13354 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13355 Func->getMemberSpecializationInfo()))
13356 checkSpecializationVisibility(Loc, Func);
13358 // C++14 [except.spec]p17:
13359 // An exception-specification is considered to be needed when:
13360 // - the function is odr-used or, if it appears in an unevaluated operand,
13361 // would be odr-used if the expression were potentially-evaluated;
13363 // Note, we do this even if MightBeOdrUse is false. That indicates that the
13364 // function is a pure virtual function we're calling, and in that case the
13365 // function was selected by overload resolution and we need to resolve its
13366 // exception specification for a different reason.
13367 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13368 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13369 ResolveExceptionSpec(Loc, FPT);
13371 // If we don't need to mark the function as used, and we don't need to
13372 // try to provide a definition, there's nothing more to do.
13373 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13374 (!NeedDefinition || Func->getBody()))
13377 // Note that this declaration has been used.
13378 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13379 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13380 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13381 if (Constructor->isDefaultConstructor()) {
13382 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13384 DefineImplicitDefaultConstructor(Loc, Constructor);
13385 } else if (Constructor->isCopyConstructor()) {
13386 DefineImplicitCopyConstructor(Loc, Constructor);
13387 } else if (Constructor->isMoveConstructor()) {
13388 DefineImplicitMoveConstructor(Loc, Constructor);
13390 } else if (Constructor->getInheritedConstructor()) {
13391 DefineInheritingConstructor(Loc, Constructor);
13393 } else if (CXXDestructorDecl *Destructor =
13394 dyn_cast<CXXDestructorDecl>(Func)) {
13395 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13396 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13397 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13399 DefineImplicitDestructor(Loc, Destructor);
13401 if (Destructor->isVirtual() && getLangOpts().AppleKext)
13402 MarkVTableUsed(Loc, Destructor->getParent());
13403 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13404 if (MethodDecl->isOverloadedOperator() &&
13405 MethodDecl->getOverloadedOperator() == OO_Equal) {
13406 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13407 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13408 if (MethodDecl->isCopyAssignmentOperator())
13409 DefineImplicitCopyAssignment(Loc, MethodDecl);
13410 else if (MethodDecl->isMoveAssignmentOperator())
13411 DefineImplicitMoveAssignment(Loc, MethodDecl);
13413 } else if (isa<CXXConversionDecl>(MethodDecl) &&
13414 MethodDecl->getParent()->isLambda()) {
13415 CXXConversionDecl *Conversion =
13416 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13417 if (Conversion->isLambdaToBlockPointerConversion())
13418 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13420 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13421 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13422 MarkVTableUsed(Loc, MethodDecl->getParent());
13425 // Recursive functions should be marked when used from another function.
13426 // FIXME: Is this really right?
13427 if (CurContext == Func) return;
13429 // Implicit instantiation of function templates and member functions of
13430 // class templates.
13431 if (Func->isImplicitlyInstantiable()) {
13432 bool AlreadyInstantiated = false;
13433 SourceLocation PointOfInstantiation = Loc;
13434 if (FunctionTemplateSpecializationInfo *SpecInfo
13435 = Func->getTemplateSpecializationInfo()) {
13436 if (SpecInfo->getPointOfInstantiation().isInvalid())
13437 SpecInfo->setPointOfInstantiation(Loc);
13438 else if (SpecInfo->getTemplateSpecializationKind()
13439 == TSK_ImplicitInstantiation) {
13440 AlreadyInstantiated = true;
13441 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13443 } else if (MemberSpecializationInfo *MSInfo
13444 = Func->getMemberSpecializationInfo()) {
13445 if (MSInfo->getPointOfInstantiation().isInvalid())
13446 MSInfo->setPointOfInstantiation(Loc);
13447 else if (MSInfo->getTemplateSpecializationKind()
13448 == TSK_ImplicitInstantiation) {
13449 AlreadyInstantiated = true;
13450 PointOfInstantiation = MSInfo->getPointOfInstantiation();
13454 if (!AlreadyInstantiated || Func->isConstexpr()) {
13455 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13456 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13457 CodeSynthesisContexts.size())
13458 PendingLocalImplicitInstantiations.push_back(
13459 std::make_pair(Func, PointOfInstantiation));
13460 else if (Func->isConstexpr())
13461 // Do not defer instantiations of constexpr functions, to avoid the
13462 // expression evaluator needing to call back into Sema if it sees a
13463 // call to such a function.
13464 InstantiateFunctionDefinition(PointOfInstantiation, Func);
13466 PendingInstantiations.push_back(std::make_pair(Func,
13467 PointOfInstantiation));
13468 // Notify the consumer that a function was implicitly instantiated.
13469 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13473 // Walk redefinitions, as some of them may be instantiable.
13474 for (auto i : Func->redecls()) {
13475 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13476 MarkFunctionReferenced(Loc, i, OdrUse);
13480 if (!OdrUse) return;
13482 // Keep track of used but undefined functions.
13483 if (!Func->isDefined()) {
13484 if (mightHaveNonExternalLinkage(Func))
13485 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13486 else if (Func->getMostRecentDecl()->isInlined() &&
13487 !LangOpts.GNUInline &&
13488 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13489 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13492 Func->markUsed(Context);
13496 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13497 ValueDecl *var, DeclContext *DC) {
13498 DeclContext *VarDC = var->getDeclContext();
13500 // If the parameter still belongs to the translation unit, then
13501 // we're actually just using one parameter in the declaration of
13503 if (isa<ParmVarDecl>(var) &&
13504 isa<TranslationUnitDecl>(VarDC))
13507 // For C code, don't diagnose about capture if we're not actually in code
13508 // right now; it's impossible to write a non-constant expression outside of
13509 // function context, so we'll get other (more useful) diagnostics later.
13511 // For C++, things get a bit more nasty... it would be nice to suppress this
13512 // diagnostic for certain cases like using a local variable in an array bound
13513 // for a member of a local class, but the correct predicate is not obvious.
13514 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13517 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13518 unsigned ContextKind = 3; // unknown
13519 if (isa<CXXMethodDecl>(VarDC) &&
13520 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13522 } else if (isa<FunctionDecl>(VarDC)) {
13524 } else if (isa<BlockDecl>(VarDC)) {
13528 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13529 << var << ValueKind << ContextKind << VarDC;
13530 S.Diag(var->getLocation(), diag::note_entity_declared_at)
13533 // FIXME: Add additional diagnostic info about class etc. which prevents
13538 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13539 bool &SubCapturesAreNested,
13540 QualType &CaptureType,
13541 QualType &DeclRefType) {
13542 // Check whether we've already captured it.
13543 if (CSI->CaptureMap.count(Var)) {
13544 // If we found a capture, any subcaptures are nested.
13545 SubCapturesAreNested = true;
13547 // Retrieve the capture type for this variable.
13548 CaptureType = CSI->getCapture(Var).getCaptureType();
13550 // Compute the type of an expression that refers to this variable.
13551 DeclRefType = CaptureType.getNonReferenceType();
13553 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13554 // are mutable in the sense that user can change their value - they are
13555 // private instances of the captured declarations.
13556 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13557 if (Cap.isCopyCapture() &&
13558 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13559 !(isa<CapturedRegionScopeInfo>(CSI) &&
13560 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13561 DeclRefType.addConst();
13567 // Only block literals, captured statements, and lambda expressions can
13568 // capture; other scopes don't work.
13569 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13570 SourceLocation Loc,
13571 const bool Diagnose, Sema &S) {
13572 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13573 return getLambdaAwareParentOfDeclContext(DC);
13574 else if (Var->hasLocalStorage()) {
13576 diagnoseUncapturableValueReference(S, Loc, Var, DC);
13581 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13582 // certain types of variables (unnamed, variably modified types etc.)
13583 // so check for eligibility.
13584 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13585 SourceLocation Loc,
13586 const bool Diagnose, Sema &S) {
13588 bool IsBlock = isa<BlockScopeInfo>(CSI);
13589 bool IsLambda = isa<LambdaScopeInfo>(CSI);
13591 // Lambdas are not allowed to capture unnamed variables
13592 // (e.g. anonymous unions).
13593 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13594 // assuming that's the intent.
13595 if (IsLambda && !Var->getDeclName()) {
13597 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13598 S.Diag(Var->getLocation(), diag::note_declared_at);
13603 // Prohibit variably-modified types in blocks; they're difficult to deal with.
13604 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13606 S.Diag(Loc, diag::err_ref_vm_type);
13607 S.Diag(Var->getLocation(), diag::note_previous_decl)
13608 << Var->getDeclName();
13612 // Prohibit structs with flexible array members too.
13613 // We cannot capture what is in the tail end of the struct.
13614 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13615 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13618 S.Diag(Loc, diag::err_ref_flexarray_type);
13620 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13621 << Var->getDeclName();
13622 S.Diag(Var->getLocation(), diag::note_previous_decl)
13623 << Var->getDeclName();
13628 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13629 // Lambdas and captured statements are not allowed to capture __block
13630 // variables; they don't support the expected semantics.
13631 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13633 S.Diag(Loc, diag::err_capture_block_variable)
13634 << Var->getDeclName() << !IsLambda;
13635 S.Diag(Var->getLocation(), diag::note_previous_decl)
13636 << Var->getDeclName();
13640 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13641 if (S.getLangOpts().OpenCL && IsBlock &&
13642 Var->getType()->isBlockPointerType()) {
13644 S.Diag(Loc, diag::err_opencl_block_ref_block);
13651 // Returns true if the capture by block was successful.
13652 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13653 SourceLocation Loc,
13654 const bool BuildAndDiagnose,
13655 QualType &CaptureType,
13656 QualType &DeclRefType,
13659 Expr *CopyExpr = nullptr;
13660 bool ByRef = false;
13662 // Blocks are not allowed to capture arrays.
13663 if (CaptureType->isArrayType()) {
13664 if (BuildAndDiagnose) {
13665 S.Diag(Loc, diag::err_ref_array_type);
13666 S.Diag(Var->getLocation(), diag::note_previous_decl)
13667 << Var->getDeclName();
13672 // Forbid the block-capture of autoreleasing variables.
13673 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13674 if (BuildAndDiagnose) {
13675 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13677 S.Diag(Var->getLocation(), diag::note_previous_decl)
13678 << Var->getDeclName();
13683 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13684 if (const auto *PT = CaptureType->getAs<PointerType>()) {
13685 // This function finds out whether there is an AttributedType of kind
13686 // attr_objc_ownership in Ty. The existence of AttributedType of kind
13687 // attr_objc_ownership implies __autoreleasing was explicitly specified
13688 // rather than being added implicitly by the compiler.
13689 auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13690 while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13691 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13694 // Peel off AttributedTypes that are not of kind objc_ownership.
13695 Ty = AttrTy->getModifiedType();
13701 QualType PointeeTy = PT->getPointeeType();
13703 if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13704 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13705 !IsObjCOwnershipAttributedType(PointeeTy)) {
13706 if (BuildAndDiagnose) {
13707 SourceLocation VarLoc = Var->getLocation();
13708 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13710 auto AddAutoreleaseNote =
13711 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13712 // Provide a fix-it for the '__autoreleasing' keyword at the
13713 // appropriate location in the variable's type.
13714 if (const auto *TSI = Var->getTypeSourceInfo()) {
13715 PointerTypeLoc PTL =
13716 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13718 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13719 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13721 if (Loc.isValid()) {
13722 StringRef CharAtLoc = Lexer::getSourceText(
13723 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13724 S.getSourceManager(), S.getLangOpts());
13725 AddAutoreleaseNote << FixItHint::CreateInsertion(
13726 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13727 ? " __autoreleasing "
13728 : " __autoreleasing");
13733 S.Diag(VarLoc, diag::note_declare_parameter_strong);
13738 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13739 if (HasBlocksAttr || CaptureType->isReferenceType() ||
13740 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13741 // Block capture by reference does not change the capture or
13742 // declaration reference types.
13745 // Block capture by copy introduces 'const'.
13746 CaptureType = CaptureType.getNonReferenceType().withConst();
13747 DeclRefType = CaptureType;
13749 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13750 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13751 // The capture logic needs the destructor, so make sure we mark it.
13752 // Usually this is unnecessary because most local variables have
13753 // their destructors marked at declaration time, but parameters are
13754 // an exception because it's technically only the call site that
13755 // actually requires the destructor.
13756 if (isa<ParmVarDecl>(Var))
13757 S.FinalizeVarWithDestructor(Var, Record);
13759 // Enter a new evaluation context to insulate the copy
13760 // full-expression.
13761 EnterExpressionEvaluationContext scope(
13762 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13764 // According to the blocks spec, the capture of a variable from
13765 // the stack requires a const copy constructor. This is not true
13766 // of the copy/move done to move a __block variable to the heap.
13767 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13768 DeclRefType.withConst(),
13772 = S.PerformCopyInitialization(
13773 InitializedEntity::InitializeBlock(Var->getLocation(),
13774 CaptureType, false),
13777 // Build a full-expression copy expression if initialization
13778 // succeeded and used a non-trivial constructor. Recover from
13779 // errors by pretending that the copy isn't necessary.
13780 if (!Result.isInvalid() &&
13781 !cast<CXXConstructExpr>(Result.get())->getConstructor()
13783 Result = S.MaybeCreateExprWithCleanups(Result);
13784 CopyExpr = Result.get();
13790 // Actually capture the variable.
13791 if (BuildAndDiagnose)
13792 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13793 SourceLocation(), CaptureType, CopyExpr);
13800 /// \brief Capture the given variable in the captured region.
13801 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13803 SourceLocation Loc,
13804 const bool BuildAndDiagnose,
13805 QualType &CaptureType,
13806 QualType &DeclRefType,
13807 const bool RefersToCapturedVariable,
13809 // By default, capture variables by reference.
13811 // Using an LValue reference type is consistent with Lambdas (see below).
13812 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13813 if (S.IsOpenMPCapturedDecl(Var))
13814 DeclRefType = DeclRefType.getUnqualifiedType();
13815 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13819 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13821 CaptureType = DeclRefType;
13823 Expr *CopyExpr = nullptr;
13824 if (BuildAndDiagnose) {
13825 // The current implementation assumes that all variables are captured
13826 // by references. Since there is no capture by copy, no expression
13827 // evaluation will be needed.
13828 RecordDecl *RD = RSI->TheRecordDecl;
13831 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13832 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13833 nullptr, false, ICIS_NoInit);
13834 Field->setImplicit(true);
13835 Field->setAccess(AS_private);
13836 RD->addDecl(Field);
13838 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13839 DeclRefType, VK_LValue, Loc);
13840 Var->setReferenced(true);
13841 Var->markUsed(S.Context);
13844 // Actually capture the variable.
13845 if (BuildAndDiagnose)
13846 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13847 SourceLocation(), CaptureType, CopyExpr);
13853 /// \brief Create a field within the lambda class for the variable
13854 /// being captured.
13855 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13856 QualType FieldType, QualType DeclRefType,
13857 SourceLocation Loc,
13858 bool RefersToCapturedVariable) {
13859 CXXRecordDecl *Lambda = LSI->Lambda;
13861 // Build the non-static data member.
13863 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13864 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13865 nullptr, false, ICIS_NoInit);
13866 Field->setImplicit(true);
13867 Field->setAccess(AS_private);
13868 Lambda->addDecl(Field);
13871 /// \brief Capture the given variable in the lambda.
13872 static bool captureInLambda(LambdaScopeInfo *LSI,
13874 SourceLocation Loc,
13875 const bool BuildAndDiagnose,
13876 QualType &CaptureType,
13877 QualType &DeclRefType,
13878 const bool RefersToCapturedVariable,
13879 const Sema::TryCaptureKind Kind,
13880 SourceLocation EllipsisLoc,
13881 const bool IsTopScope,
13884 // Determine whether we are capturing by reference or by value.
13885 bool ByRef = false;
13886 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13887 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13889 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13892 // Compute the type of the field that will capture this variable.
13894 // C++11 [expr.prim.lambda]p15:
13895 // An entity is captured by reference if it is implicitly or
13896 // explicitly captured but not captured by copy. It is
13897 // unspecified whether additional unnamed non-static data
13898 // members are declared in the closure type for entities
13899 // captured by reference.
13901 // FIXME: It is not clear whether we want to build an lvalue reference
13902 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13903 // to do the former, while EDG does the latter. Core issue 1249 will
13904 // clarify, but for now we follow GCC because it's a more permissive and
13905 // easily defensible position.
13906 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13908 // C++11 [expr.prim.lambda]p14:
13909 // For each entity captured by copy, an unnamed non-static
13910 // data member is declared in the closure type. The
13911 // declaration order of these members is unspecified. The type
13912 // of such a data member is the type of the corresponding
13913 // captured entity if the entity is not a reference to an
13914 // object, or the referenced type otherwise. [Note: If the
13915 // captured entity is a reference to a function, the
13916 // corresponding data member is also a reference to a
13917 // function. - end note ]
13918 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13919 if (!RefType->getPointeeType()->isFunctionType())
13920 CaptureType = RefType->getPointeeType();
13923 // Forbid the lambda copy-capture of autoreleasing variables.
13924 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13925 if (BuildAndDiagnose) {
13926 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13927 S.Diag(Var->getLocation(), diag::note_previous_decl)
13928 << Var->getDeclName();
13933 // Make sure that by-copy captures are of a complete and non-abstract type.
13934 if (BuildAndDiagnose) {
13935 if (!CaptureType->isDependentType() &&
13936 S.RequireCompleteType(Loc, CaptureType,
13937 diag::err_capture_of_incomplete_type,
13938 Var->getDeclName()))
13941 if (S.RequireNonAbstractType(Loc, CaptureType,
13942 diag::err_capture_of_abstract_type))
13947 // Capture this variable in the lambda.
13948 if (BuildAndDiagnose)
13949 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13950 RefersToCapturedVariable);
13952 // Compute the type of a reference to this captured variable.
13954 DeclRefType = CaptureType.getNonReferenceType();
13956 // C++ [expr.prim.lambda]p5:
13957 // The closure type for a lambda-expression has a public inline
13958 // function call operator [...]. This function call operator is
13959 // declared const (9.3.1) if and only if the lambda-expression's
13960 // parameter-declaration-clause is not followed by mutable.
13961 DeclRefType = CaptureType.getNonReferenceType();
13962 if (!LSI->Mutable && !CaptureType->isReferenceType())
13963 DeclRefType.addConst();
13966 // Add the capture.
13967 if (BuildAndDiagnose)
13968 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13969 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13974 bool Sema::tryCaptureVariable(
13975 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13976 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13977 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13978 // An init-capture is notionally from the context surrounding its
13979 // declaration, but its parent DC is the lambda class.
13980 DeclContext *VarDC = Var->getDeclContext();
13981 if (Var->isInitCapture())
13982 VarDC = VarDC->getParent();
13984 DeclContext *DC = CurContext;
13985 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13986 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13987 // We need to sync up the Declaration Context with the
13988 // FunctionScopeIndexToStopAt
13989 if (FunctionScopeIndexToStopAt) {
13990 unsigned FSIndex = FunctionScopes.size() - 1;
13991 while (FSIndex != MaxFunctionScopesIndex) {
13992 DC = getLambdaAwareParentOfDeclContext(DC);
13998 // If the variable is declared in the current context, there is no need to
14000 if (VarDC == DC) return true;
14002 // Capture global variables if it is required to use private copy of this
14004 bool IsGlobal = !Var->hasLocalStorage();
14005 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14008 // Walk up the stack to determine whether we can capture the variable,
14009 // performing the "simple" checks that don't depend on type. We stop when
14010 // we've either hit the declared scope of the variable or find an existing
14011 // capture of that variable. We start from the innermost capturing-entity
14012 // (the DC) and ensure that all intervening capturing-entities
14013 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14014 // declcontext can either capture the variable or have already captured
14016 CaptureType = Var->getType();
14017 DeclRefType = CaptureType.getNonReferenceType();
14018 bool Nested = false;
14019 bool Explicit = (Kind != TryCapture_Implicit);
14020 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14022 // Only block literals, captured statements, and lambda expressions can
14023 // capture; other scopes don't work.
14024 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14028 // We need to check for the parent *first* because, if we *have*
14029 // private-captured a global variable, we need to recursively capture it in
14030 // intermediate blocks, lambdas, etc.
14033 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14039 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
14040 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14043 // Check whether we've already captured it.
14044 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14046 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14049 // If we are instantiating a generic lambda call operator body,
14050 // we do not want to capture new variables. What was captured
14051 // during either a lambdas transformation or initial parsing
14053 if (isGenericLambdaCallOperatorSpecialization(DC)) {
14054 if (BuildAndDiagnose) {
14055 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14056 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14057 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14058 Diag(Var->getLocation(), diag::note_previous_decl)
14059 << Var->getDeclName();
14060 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14062 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14066 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14067 // certain types of variables (unnamed, variably modified types etc.)
14068 // so check for eligibility.
14069 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14072 // Try to capture variable-length arrays types.
14073 if (Var->getType()->isVariablyModifiedType()) {
14074 // We're going to walk down into the type and look for VLA
14076 QualType QTy = Var->getType();
14077 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14078 QTy = PVD->getOriginalType();
14079 captureVariablyModifiedType(Context, QTy, CSI);
14082 if (getLangOpts().OpenMP) {
14083 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14084 // OpenMP private variables should not be captured in outer scope, so
14085 // just break here. Similarly, global variables that are captured in a
14086 // target region should not be captured outside the scope of the region.
14087 if (RSI->CapRegionKind == CR_OpenMP) {
14088 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14089 // When we detect target captures we are looking from inside the
14090 // target region, therefore we need to propagate the capture from the
14091 // enclosing region. Therefore, the capture is not initially nested.
14093 FunctionScopesIndex--;
14095 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14096 Nested = !IsTargetCap;
14097 DeclRefType = DeclRefType.getUnqualifiedType();
14098 CaptureType = Context.getLValueReferenceType(DeclRefType);
14104 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14105 // No capture-default, and this is not an explicit capture
14106 // so cannot capture this variable.
14107 if (BuildAndDiagnose) {
14108 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14109 Diag(Var->getLocation(), diag::note_previous_decl)
14110 << Var->getDeclName();
14111 if (cast<LambdaScopeInfo>(CSI)->Lambda)
14112 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14113 diag::note_lambda_decl);
14114 // FIXME: If we error out because an outer lambda can not implicitly
14115 // capture a variable that an inner lambda explicitly captures, we
14116 // should have the inner lambda do the explicit capture - because
14117 // it makes for cleaner diagnostics later. This would purely be done
14118 // so that the diagnostic does not misleadingly claim that a variable
14119 // can not be captured by a lambda implicitly even though it is captured
14120 // explicitly. Suggestion:
14121 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14122 // at the function head
14123 // - cache the StartingDeclContext - this must be a lambda
14124 // - captureInLambda in the innermost lambda the variable.
14129 FunctionScopesIndex--;
14132 } while (!VarDC->Equals(DC));
14134 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14135 // computing the type of the capture at each step, checking type-specific
14136 // requirements, and adding captures if requested.
14137 // If the variable had already been captured previously, we start capturing
14138 // at the lambda nested within that one.
14139 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14141 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14143 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14144 if (!captureInBlock(BSI, Var, ExprLoc,
14145 BuildAndDiagnose, CaptureType,
14146 DeclRefType, Nested, *this))
14149 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14150 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14151 BuildAndDiagnose, CaptureType,
14152 DeclRefType, Nested, *this))
14156 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14157 if (!captureInLambda(LSI, Var, ExprLoc,
14158 BuildAndDiagnose, CaptureType,
14159 DeclRefType, Nested, Kind, EllipsisLoc,
14160 /*IsTopScope*/I == N - 1, *this))
14168 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14169 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14170 QualType CaptureType;
14171 QualType DeclRefType;
14172 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14173 /*BuildAndDiagnose=*/true, CaptureType,
14174 DeclRefType, nullptr);
14177 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14178 QualType CaptureType;
14179 QualType DeclRefType;
14180 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14181 /*BuildAndDiagnose=*/false, CaptureType,
14182 DeclRefType, nullptr);
14185 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14186 QualType CaptureType;
14187 QualType DeclRefType;
14189 // Determine whether we can capture this variable.
14190 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14191 /*BuildAndDiagnose=*/false, CaptureType,
14192 DeclRefType, nullptr))
14195 return DeclRefType;
14200 // If either the type of the variable or the initializer is dependent,
14201 // return false. Otherwise, determine whether the variable is a constant
14202 // expression. Use this if you need to know if a variable that might or
14203 // might not be dependent is truly a constant expression.
14204 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14205 ASTContext &Context) {
14207 if (Var->getType()->isDependentType())
14209 const VarDecl *DefVD = nullptr;
14210 Var->getAnyInitializer(DefVD);
14213 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14214 Expr *Init = cast<Expr>(Eval->Value);
14215 if (Init->isValueDependent())
14217 return IsVariableAConstantExpression(Var, Context);
14221 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14222 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14223 // an object that satisfies the requirements for appearing in a
14224 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14225 // is immediately applied." This function handles the lvalue-to-rvalue
14226 // conversion part.
14227 MaybeODRUseExprs.erase(E->IgnoreParens());
14229 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14230 // to a variable that is a constant expression, and if so, identify it as
14231 // a reference to a variable that does not involve an odr-use of that
14233 if (LambdaScopeInfo *LSI = getCurLambda()) {
14234 Expr *SansParensExpr = E->IgnoreParens();
14235 VarDecl *Var = nullptr;
14236 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14237 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14238 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14239 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14241 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14242 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14246 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14247 Res = CorrectDelayedTyposInExpr(Res);
14249 if (!Res.isUsable())
14252 // If a constant-expression is a reference to a variable where we delay
14253 // deciding whether it is an odr-use, just assume we will apply the
14254 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
14255 // (a non-type template argument), we have special handling anyway.
14256 UpdateMarkingForLValueToRValue(Res.get());
14260 void Sema::CleanupVarDeclMarking() {
14261 for (Expr *E : MaybeODRUseExprs) {
14263 SourceLocation Loc;
14264 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14265 Var = cast<VarDecl>(DRE->getDecl());
14266 Loc = DRE->getLocation();
14267 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14268 Var = cast<VarDecl>(ME->getMemberDecl());
14269 Loc = ME->getMemberLoc();
14271 llvm_unreachable("Unexpected expression");
14274 MarkVarDeclODRUsed(Var, Loc, *this,
14275 /*MaxFunctionScopeIndex Pointer*/ nullptr);
14278 MaybeODRUseExprs.clear();
14282 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14283 VarDecl *Var, Expr *E) {
14284 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14285 "Invalid Expr argument to DoMarkVarDeclReferenced");
14286 Var->setReferenced();
14288 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14290 bool OdrUseContext = isOdrUseContext(SemaRef);
14291 bool NeedDefinition =
14292 OdrUseContext || (isEvaluatableContext(SemaRef) &&
14293 Var->isUsableInConstantExpressions(SemaRef.Context));
14295 VarTemplateSpecializationDecl *VarSpec =
14296 dyn_cast<VarTemplateSpecializationDecl>(Var);
14297 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14298 "Can't instantiate a partial template specialization.");
14300 // If this might be a member specialization of a static data member, check
14301 // the specialization is visible. We already did the checks for variable
14302 // template specializations when we created them.
14303 if (NeedDefinition && TSK != TSK_Undeclared &&
14304 !isa<VarTemplateSpecializationDecl>(Var))
14305 SemaRef.checkSpecializationVisibility(Loc, Var);
14307 // Perform implicit instantiation of static data members, static data member
14308 // templates of class templates, and variable template specializations. Delay
14309 // instantiations of variable templates, except for those that could be used
14310 // in a constant expression.
14311 if (NeedDefinition && isTemplateInstantiation(TSK)) {
14312 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14314 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14315 if (Var->getPointOfInstantiation().isInvalid()) {
14316 // This is a modification of an existing AST node. Notify listeners.
14317 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14318 L->StaticDataMemberInstantiated(Var);
14319 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14320 // Don't bother trying to instantiate it again, unless we might need
14321 // its initializer before we get to the end of the TU.
14322 TryInstantiating = false;
14325 if (Var->getPointOfInstantiation().isInvalid())
14326 Var->setTemplateSpecializationKind(TSK, Loc);
14328 if (TryInstantiating) {
14329 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14330 bool InstantiationDependent = false;
14331 bool IsNonDependent =
14332 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14333 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14336 // Do not instantiate specializations that are still type-dependent.
14337 if (IsNonDependent) {
14338 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14339 // Do not defer instantiations of variables which could be used in a
14340 // constant expression.
14341 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14343 SemaRef.PendingInstantiations
14344 .push_back(std::make_pair(Var, PointOfInstantiation));
14350 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14351 // the requirements for appearing in a constant expression (5.19) and, if
14352 // it is an object, the lvalue-to-rvalue conversion (4.1)
14353 // is immediately applied." We check the first part here, and
14354 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14355 // Note that we use the C++11 definition everywhere because nothing in
14356 // C++03 depends on whether we get the C++03 version correct. The second
14357 // part does not apply to references, since they are not objects.
14358 if (OdrUseContext && E &&
14359 IsVariableAConstantExpression(Var, SemaRef.Context)) {
14360 // A reference initialized by a constant expression can never be
14361 // odr-used, so simply ignore it.
14362 if (!Var->getType()->isReferenceType())
14363 SemaRef.MaybeODRUseExprs.insert(E);
14364 } else if (OdrUseContext) {
14365 MarkVarDeclODRUsed(Var, Loc, SemaRef,
14366 /*MaxFunctionScopeIndex ptr*/ nullptr);
14367 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14368 // If this is a dependent context, we don't need to mark variables as
14369 // odr-used, but we may still need to track them for lambda capture.
14370 // FIXME: Do we also need to do this inside dependent typeid expressions
14371 // (which are modeled as unevaluated at this point)?
14372 const bool RefersToEnclosingScope =
14373 (SemaRef.CurContext != Var->getDeclContext() &&
14374 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14375 if (RefersToEnclosingScope) {
14376 LambdaScopeInfo *const LSI =
14377 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14378 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14379 // If a variable could potentially be odr-used, defer marking it so
14380 // until we finish analyzing the full expression for any
14381 // lvalue-to-rvalue
14382 // or discarded value conversions that would obviate odr-use.
14383 // Add it to the list of potential captures that will be analyzed
14384 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14385 // unless the variable is a reference that was initialized by a constant
14386 // expression (this will never need to be captured or odr-used).
14387 assert(E && "Capture variable should be used in an expression.");
14388 if (!Var->getType()->isReferenceType() ||
14389 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14390 LSI->addPotentialCapture(E->IgnoreParens());
14396 /// \brief Mark a variable referenced, and check whether it is odr-used
14397 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
14398 /// used directly for normal expressions referring to VarDecl.
14399 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14400 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14403 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14404 Decl *D, Expr *E, bool MightBeOdrUse) {
14405 if (SemaRef.isInOpenMPDeclareTargetContext())
14406 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14408 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14409 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14413 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14415 // If this is a call to a method via a cast, also mark the method in the
14416 // derived class used in case codegen can devirtualize the call.
14417 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14420 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14423 // Only attempt to devirtualize if this is truly a virtual call.
14424 bool IsVirtualCall = MD->isVirtual() &&
14425 ME->performsVirtualDispatch(SemaRef.getLangOpts());
14426 if (!IsVirtualCall)
14428 const Expr *Base = ME->getBase();
14429 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14430 if (!MostDerivedClassDecl)
14432 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14433 if (!DM || DM->isPure())
14435 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14438 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14439 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14440 // TODO: update this with DR# once a defect report is filed.
14441 // C++11 defect. The address of a pure member should not be an ODR use, even
14442 // if it's a qualified reference.
14443 bool OdrUse = true;
14444 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14445 if (Method->isVirtual())
14447 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14450 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14451 void Sema::MarkMemberReferenced(MemberExpr *E) {
14452 // C++11 [basic.def.odr]p2:
14453 // A non-overloaded function whose name appears as a potentially-evaluated
14454 // expression or a member of a set of candidate functions, if selected by
14455 // overload resolution when referred to from a potentially-evaluated
14456 // expression, is odr-used, unless it is a pure virtual function and its
14457 // name is not explicitly qualified.
14458 bool MightBeOdrUse = true;
14459 if (E->performsVirtualDispatch(getLangOpts())) {
14460 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14461 if (Method->isPure())
14462 MightBeOdrUse = false;
14464 SourceLocation Loc = E->getMemberLoc().isValid() ?
14465 E->getMemberLoc() : E->getLocStart();
14466 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14469 /// \brief Perform marking for a reference to an arbitrary declaration. It
14470 /// marks the declaration referenced, and performs odr-use checking for
14471 /// functions and variables. This method should not be used when building a
14472 /// normal expression which refers to a variable.
14473 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14474 bool MightBeOdrUse) {
14475 if (MightBeOdrUse) {
14476 if (auto *VD = dyn_cast<VarDecl>(D)) {
14477 MarkVariableReferenced(Loc, VD);
14481 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14482 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14485 D->setReferenced();
14489 // Mark all of the declarations used by a type as referenced.
14490 // FIXME: Not fully implemented yet! We need to have a better understanding
14491 // of when we're entering a context we should not recurse into.
14492 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14493 // TreeTransforms rebuilding the type in a new context. Rather than
14494 // duplicating the TreeTransform logic, we should consider reusing it here.
14495 // Currently that causes problems when rebuilding LambdaExprs.
14496 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14498 SourceLocation Loc;
14501 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14503 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14505 bool TraverseTemplateArgument(const TemplateArgument &Arg);
14509 bool MarkReferencedDecls::TraverseTemplateArgument(
14510 const TemplateArgument &Arg) {
14512 // A non-type template argument is a constant-evaluated context.
14513 EnterExpressionEvaluationContext Evaluated(
14514 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14515 if (Arg.getKind() == TemplateArgument::Declaration) {
14516 if (Decl *D = Arg.getAsDecl())
14517 S.MarkAnyDeclReferenced(Loc, D, true);
14518 } else if (Arg.getKind() == TemplateArgument::Expression) {
14519 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14523 return Inherited::TraverseTemplateArgument(Arg);
14526 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14527 MarkReferencedDecls Marker(*this, Loc);
14528 Marker.TraverseType(T);
14532 /// \brief Helper class that marks all of the declarations referenced by
14533 /// potentially-evaluated subexpressions as "referenced".
14534 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14536 bool SkipLocalVariables;
14539 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14541 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14542 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14544 void VisitDeclRefExpr(DeclRefExpr *E) {
14545 // If we were asked not to visit local variables, don't.
14546 if (SkipLocalVariables) {
14547 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14548 if (VD->hasLocalStorage())
14552 S.MarkDeclRefReferenced(E);
14555 void VisitMemberExpr(MemberExpr *E) {
14556 S.MarkMemberReferenced(E);
14557 Inherited::VisitMemberExpr(E);
14560 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14561 S.MarkFunctionReferenced(E->getLocStart(),
14562 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14563 Visit(E->getSubExpr());
14566 void VisitCXXNewExpr(CXXNewExpr *E) {
14567 if (E->getOperatorNew())
14568 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14569 if (E->getOperatorDelete())
14570 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14571 Inherited::VisitCXXNewExpr(E);
14574 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14575 if (E->getOperatorDelete())
14576 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14577 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14578 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14579 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14580 S.MarkFunctionReferenced(E->getLocStart(),
14581 S.LookupDestructor(Record));
14584 Inherited::VisitCXXDeleteExpr(E);
14587 void VisitCXXConstructExpr(CXXConstructExpr *E) {
14588 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14589 Inherited::VisitCXXConstructExpr(E);
14592 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14593 Visit(E->getExpr());
14596 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14597 Inherited::VisitImplicitCastExpr(E);
14599 if (E->getCastKind() == CK_LValueToRValue)
14600 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14605 /// \brief Mark any declarations that appear within this expression or any
14606 /// potentially-evaluated subexpressions as "referenced".
14608 /// \param SkipLocalVariables If true, don't mark local variables as
14610 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14611 bool SkipLocalVariables) {
14612 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14615 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14616 /// of the program being compiled.
14618 /// This routine emits the given diagnostic when the code currently being
14619 /// type-checked is "potentially evaluated", meaning that there is a
14620 /// possibility that the code will actually be executable. Code in sizeof()
14621 /// expressions, code used only during overload resolution, etc., are not
14622 /// potentially evaluated. This routine will suppress such diagnostics or,
14623 /// in the absolutely nutty case of potentially potentially evaluated
14624 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14627 /// This routine should be used for all diagnostics that describe the run-time
14628 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14629 /// Failure to do so will likely result in spurious diagnostics or failures
14630 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14631 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14632 const PartialDiagnostic &PD) {
14633 switch (ExprEvalContexts.back().Context) {
14634 case ExpressionEvaluationContext::Unevaluated:
14635 case ExpressionEvaluationContext::UnevaluatedList:
14636 case ExpressionEvaluationContext::UnevaluatedAbstract:
14637 case ExpressionEvaluationContext::DiscardedStatement:
14638 // The argument will never be evaluated, so don't complain.
14641 case ExpressionEvaluationContext::ConstantEvaluated:
14642 // Relevant diagnostics should be produced by constant evaluation.
14645 case ExpressionEvaluationContext::PotentiallyEvaluated:
14646 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14647 if (Statement && getCurFunctionOrMethodDecl()) {
14648 FunctionScopes.back()->PossiblyUnreachableDiags.
14649 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14660 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14661 CallExpr *CE, FunctionDecl *FD) {
14662 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14665 // If we're inside a decltype's expression, don't check for a valid return
14666 // type or construct temporaries until we know whether this is the last call.
14667 if (ExprEvalContexts.back().IsDecltype) {
14668 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14672 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14677 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14678 : FD(FD), CE(CE) { }
14680 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14682 S.Diag(Loc, diag::err_call_incomplete_return)
14683 << T << CE->getSourceRange();
14687 S.Diag(Loc, diag::err_call_function_incomplete_return)
14688 << CE->getSourceRange() << FD->getDeclName() << T;
14689 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14690 << FD->getDeclName();
14692 } Diagnoser(FD, CE);
14694 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14700 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14701 // will prevent this condition from triggering, which is what we want.
14702 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14703 SourceLocation Loc;
14705 unsigned diagnostic = diag::warn_condition_is_assignment;
14706 bool IsOrAssign = false;
14708 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14709 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14712 IsOrAssign = Op->getOpcode() == BO_OrAssign;
14714 // Greylist some idioms by putting them into a warning subcategory.
14715 if (ObjCMessageExpr *ME
14716 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14717 Selector Sel = ME->getSelector();
14719 // self = [<foo> init...]
14720 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14721 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14723 // <foo> = [<bar> nextObject]
14724 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14725 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14728 Loc = Op->getOperatorLoc();
14729 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14730 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14733 IsOrAssign = Op->getOperator() == OO_PipeEqual;
14734 Loc = Op->getOperatorLoc();
14735 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14736 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14738 // Not an assignment.
14742 Diag(Loc, diagnostic) << E->getSourceRange();
14744 SourceLocation Open = E->getLocStart();
14745 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14746 Diag(Loc, diag::note_condition_assign_silence)
14747 << FixItHint::CreateInsertion(Open, "(")
14748 << FixItHint::CreateInsertion(Close, ")");
14751 Diag(Loc, diag::note_condition_or_assign_to_comparison)
14752 << FixItHint::CreateReplacement(Loc, "!=");
14754 Diag(Loc, diag::note_condition_assign_to_comparison)
14755 << FixItHint::CreateReplacement(Loc, "==");
14758 /// \brief Redundant parentheses over an equality comparison can indicate
14759 /// that the user intended an assignment used as condition.
14760 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14761 // Don't warn if the parens came from a macro.
14762 SourceLocation parenLoc = ParenE->getLocStart();
14763 if (parenLoc.isInvalid() || parenLoc.isMacroID())
14765 // Don't warn for dependent expressions.
14766 if (ParenE->isTypeDependent())
14769 Expr *E = ParenE->IgnoreParens();
14771 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14772 if (opE->getOpcode() == BO_EQ &&
14773 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14774 == Expr::MLV_Valid) {
14775 SourceLocation Loc = opE->getOperatorLoc();
14777 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14778 SourceRange ParenERange = ParenE->getSourceRange();
14779 Diag(Loc, diag::note_equality_comparison_silence)
14780 << FixItHint::CreateRemoval(ParenERange.getBegin())
14781 << FixItHint::CreateRemoval(ParenERange.getEnd());
14782 Diag(Loc, diag::note_equality_comparison_to_assign)
14783 << FixItHint::CreateReplacement(Loc, "=");
14787 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14788 bool IsConstexpr) {
14789 DiagnoseAssignmentAsCondition(E);
14790 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14791 DiagnoseEqualityWithExtraParens(parenE);
14793 ExprResult result = CheckPlaceholderExpr(E);
14794 if (result.isInvalid()) return ExprError();
14797 if (!E->isTypeDependent()) {
14798 if (getLangOpts().CPlusPlus)
14799 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14801 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14802 if (ERes.isInvalid())
14803 return ExprError();
14806 QualType T = E->getType();
14807 if (!T->isScalarType()) { // C99 6.8.4.1p1
14808 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14809 << T << E->getSourceRange();
14810 return ExprError();
14812 CheckBoolLikeConversion(E, Loc);
14818 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14819 Expr *SubExpr, ConditionKind CK) {
14820 // Empty conditions are valid in for-statements.
14822 return ConditionResult();
14826 case ConditionKind::Boolean:
14827 Cond = CheckBooleanCondition(Loc, SubExpr);
14830 case ConditionKind::ConstexprIf:
14831 Cond = CheckBooleanCondition(Loc, SubExpr, true);
14834 case ConditionKind::Switch:
14835 Cond = CheckSwitchCondition(Loc, SubExpr);
14838 if (Cond.isInvalid())
14839 return ConditionError();
14841 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14842 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14843 if (!FullExpr.get())
14844 return ConditionError();
14846 return ConditionResult(*this, nullptr, FullExpr,
14847 CK == ConditionKind::ConstexprIf);
14851 /// A visitor for rebuilding a call to an __unknown_any expression
14852 /// to have an appropriate type.
14853 struct RebuildUnknownAnyFunction
14854 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14858 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14860 ExprResult VisitStmt(Stmt *S) {
14861 llvm_unreachable("unexpected statement!");
14864 ExprResult VisitExpr(Expr *E) {
14865 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14866 << E->getSourceRange();
14867 return ExprError();
14870 /// Rebuild an expression which simply semantically wraps another
14871 /// expression which it shares the type and value kind of.
14872 template <class T> ExprResult rebuildSugarExpr(T *E) {
14873 ExprResult SubResult = Visit(E->getSubExpr());
14874 if (SubResult.isInvalid()) return ExprError();
14876 Expr *SubExpr = SubResult.get();
14877 E->setSubExpr(SubExpr);
14878 E->setType(SubExpr->getType());
14879 E->setValueKind(SubExpr->getValueKind());
14880 assert(E->getObjectKind() == OK_Ordinary);
14884 ExprResult VisitParenExpr(ParenExpr *E) {
14885 return rebuildSugarExpr(E);
14888 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14889 return rebuildSugarExpr(E);
14892 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14893 ExprResult SubResult = Visit(E->getSubExpr());
14894 if (SubResult.isInvalid()) return ExprError();
14896 Expr *SubExpr = SubResult.get();
14897 E->setSubExpr(SubExpr);
14898 E->setType(S.Context.getPointerType(SubExpr->getType()));
14899 assert(E->getValueKind() == VK_RValue);
14900 assert(E->getObjectKind() == OK_Ordinary);
14904 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14905 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14907 E->setType(VD->getType());
14909 assert(E->getValueKind() == VK_RValue);
14910 if (S.getLangOpts().CPlusPlus &&
14911 !(isa<CXXMethodDecl>(VD) &&
14912 cast<CXXMethodDecl>(VD)->isInstance()))
14913 E->setValueKind(VK_LValue);
14918 ExprResult VisitMemberExpr(MemberExpr *E) {
14919 return resolveDecl(E, E->getMemberDecl());
14922 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14923 return resolveDecl(E, E->getDecl());
14928 /// Given a function expression of unknown-any type, try to rebuild it
14929 /// to have a function type.
14930 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14931 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14932 if (Result.isInvalid()) return ExprError();
14933 return S.DefaultFunctionArrayConversion(Result.get());
14937 /// A visitor for rebuilding an expression of type __unknown_anytype
14938 /// into one which resolves the type directly on the referring
14939 /// expression. Strict preservation of the original source
14940 /// structure is not a goal.
14941 struct RebuildUnknownAnyExpr
14942 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14946 /// The current destination type.
14949 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14950 : S(S), DestType(CastType) {}
14952 ExprResult VisitStmt(Stmt *S) {
14953 llvm_unreachable("unexpected statement!");
14956 ExprResult VisitExpr(Expr *E) {
14957 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14958 << E->getSourceRange();
14959 return ExprError();
14962 ExprResult VisitCallExpr(CallExpr *E);
14963 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14965 /// Rebuild an expression which simply semantically wraps another
14966 /// expression which it shares the type and value kind of.
14967 template <class T> ExprResult rebuildSugarExpr(T *E) {
14968 ExprResult SubResult = Visit(E->getSubExpr());
14969 if (SubResult.isInvalid()) return ExprError();
14970 Expr *SubExpr = SubResult.get();
14971 E->setSubExpr(SubExpr);
14972 E->setType(SubExpr->getType());
14973 E->setValueKind(SubExpr->getValueKind());
14974 assert(E->getObjectKind() == OK_Ordinary);
14978 ExprResult VisitParenExpr(ParenExpr *E) {
14979 return rebuildSugarExpr(E);
14982 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14983 return rebuildSugarExpr(E);
14986 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14987 const PointerType *Ptr = DestType->getAs<PointerType>();
14989 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14990 << E->getSourceRange();
14991 return ExprError();
14994 if (isa<CallExpr>(E->getSubExpr())) {
14995 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14996 << E->getSourceRange();
14997 return ExprError();
15000 assert(E->getValueKind() == VK_RValue);
15001 assert(E->getObjectKind() == OK_Ordinary);
15002 E->setType(DestType);
15004 // Build the sub-expression as if it were an object of the pointee type.
15005 DestType = Ptr->getPointeeType();
15006 ExprResult SubResult = Visit(E->getSubExpr());
15007 if (SubResult.isInvalid()) return ExprError();
15008 E->setSubExpr(SubResult.get());
15012 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15014 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15016 ExprResult VisitMemberExpr(MemberExpr *E) {
15017 return resolveDecl(E, E->getMemberDecl());
15020 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15021 return resolveDecl(E, E->getDecl());
15026 /// Rebuilds a call expression which yielded __unknown_anytype.
15027 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15028 Expr *CalleeExpr = E->getCallee();
15032 FK_FunctionPointer,
15037 QualType CalleeType = CalleeExpr->getType();
15038 if (CalleeType == S.Context.BoundMemberTy) {
15039 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15040 Kind = FK_MemberFunction;
15041 CalleeType = Expr::findBoundMemberType(CalleeExpr);
15042 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15043 CalleeType = Ptr->getPointeeType();
15044 Kind = FK_FunctionPointer;
15046 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15047 Kind = FK_BlockPointer;
15049 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15051 // Verify that this is a legal result type of a function.
15052 if (DestType->isArrayType() || DestType->isFunctionType()) {
15053 unsigned diagID = diag::err_func_returning_array_function;
15054 if (Kind == FK_BlockPointer)
15055 diagID = diag::err_block_returning_array_function;
15057 S.Diag(E->getExprLoc(), diagID)
15058 << DestType->isFunctionType() << DestType;
15059 return ExprError();
15062 // Otherwise, go ahead and set DestType as the call's result.
15063 E->setType(DestType.getNonLValueExprType(S.Context));
15064 E->setValueKind(Expr::getValueKindForType(DestType));
15065 assert(E->getObjectKind() == OK_Ordinary);
15067 // Rebuild the function type, replacing the result type with DestType.
15068 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15070 // __unknown_anytype(...) is a special case used by the debugger when
15071 // it has no idea what a function's signature is.
15073 // We want to build this call essentially under the K&R
15074 // unprototyped rules, but making a FunctionNoProtoType in C++
15075 // would foul up all sorts of assumptions. However, we cannot
15076 // simply pass all arguments as variadic arguments, nor can we
15077 // portably just call the function under a non-variadic type; see
15078 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15079 // However, it turns out that in practice it is generally safe to
15080 // call a function declared as "A foo(B,C,D);" under the prototype
15081 // "A foo(B,C,D,...);". The only known exception is with the
15082 // Windows ABI, where any variadic function is implicitly cdecl
15083 // regardless of its normal CC. Therefore we change the parameter
15084 // types to match the types of the arguments.
15086 // This is a hack, but it is far superior to moving the
15087 // corresponding target-specific code from IR-gen to Sema/AST.
15089 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15090 SmallVector<QualType, 8> ArgTypes;
15091 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15092 ArgTypes.reserve(E->getNumArgs());
15093 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15094 Expr *Arg = E->getArg(i);
15095 QualType ArgType = Arg->getType();
15096 if (E->isLValue()) {
15097 ArgType = S.Context.getLValueReferenceType(ArgType);
15098 } else if (E->isXValue()) {
15099 ArgType = S.Context.getRValueReferenceType(ArgType);
15101 ArgTypes.push_back(ArgType);
15103 ParamTypes = ArgTypes;
15105 DestType = S.Context.getFunctionType(DestType, ParamTypes,
15106 Proto->getExtProtoInfo());
15108 DestType = S.Context.getFunctionNoProtoType(DestType,
15109 FnType->getExtInfo());
15112 // Rebuild the appropriate pointer-to-function type.
15114 case FK_MemberFunction:
15118 case FK_FunctionPointer:
15119 DestType = S.Context.getPointerType(DestType);
15122 case FK_BlockPointer:
15123 DestType = S.Context.getBlockPointerType(DestType);
15127 // Finally, we can recurse.
15128 ExprResult CalleeResult = Visit(CalleeExpr);
15129 if (!CalleeResult.isUsable()) return ExprError();
15130 E->setCallee(CalleeResult.get());
15132 // Bind a temporary if necessary.
15133 return S.MaybeBindToTemporary(E);
15136 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15137 // Verify that this is a legal result type of a call.
15138 if (DestType->isArrayType() || DestType->isFunctionType()) {
15139 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15140 << DestType->isFunctionType() << DestType;
15141 return ExprError();
15144 // Rewrite the method result type if available.
15145 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15146 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15147 Method->setReturnType(DestType);
15150 // Change the type of the message.
15151 E->setType(DestType.getNonReferenceType());
15152 E->setValueKind(Expr::getValueKindForType(DestType));
15154 return S.MaybeBindToTemporary(E);
15157 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15158 // The only case we should ever see here is a function-to-pointer decay.
15159 if (E->getCastKind() == CK_FunctionToPointerDecay) {
15160 assert(E->getValueKind() == VK_RValue);
15161 assert(E->getObjectKind() == OK_Ordinary);
15163 E->setType(DestType);
15165 // Rebuild the sub-expression as the pointee (function) type.
15166 DestType = DestType->castAs<PointerType>()->getPointeeType();
15168 ExprResult Result = Visit(E->getSubExpr());
15169 if (!Result.isUsable()) return ExprError();
15171 E->setSubExpr(Result.get());
15173 } else if (E->getCastKind() == CK_LValueToRValue) {
15174 assert(E->getValueKind() == VK_RValue);
15175 assert(E->getObjectKind() == OK_Ordinary);
15177 assert(isa<BlockPointerType>(E->getType()));
15179 E->setType(DestType);
15181 // The sub-expression has to be a lvalue reference, so rebuild it as such.
15182 DestType = S.Context.getLValueReferenceType(DestType);
15184 ExprResult Result = Visit(E->getSubExpr());
15185 if (!Result.isUsable()) return ExprError();
15187 E->setSubExpr(Result.get());
15190 llvm_unreachable("Unhandled cast type!");
15194 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15195 ExprValueKind ValueKind = VK_LValue;
15196 QualType Type = DestType;
15198 // We know how to make this work for certain kinds of decls:
15201 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15202 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15203 DestType = Ptr->getPointeeType();
15204 ExprResult Result = resolveDecl(E, VD);
15205 if (Result.isInvalid()) return ExprError();
15206 return S.ImpCastExprToType(Result.get(), Type,
15207 CK_FunctionToPointerDecay, VK_RValue);
15210 if (!Type->isFunctionType()) {
15211 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15212 << VD << E->getSourceRange();
15213 return ExprError();
15215 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15216 // We must match the FunctionDecl's type to the hack introduced in
15217 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15218 // type. See the lengthy commentary in that routine.
15219 QualType FDT = FD->getType();
15220 const FunctionType *FnType = FDT->castAs<FunctionType>();
15221 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15222 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15223 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15224 SourceLocation Loc = FD->getLocation();
15225 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15226 FD->getDeclContext(),
15227 Loc, Loc, FD->getNameInfo().getName(),
15228 DestType, FD->getTypeSourceInfo(),
15229 SC_None, false/*isInlineSpecified*/,
15230 FD->hasPrototype(),
15231 false/*isConstexprSpecified*/);
15233 if (FD->getQualifier())
15234 NewFD->setQualifierInfo(FD->getQualifierLoc());
15236 SmallVector<ParmVarDecl*, 16> Params;
15237 for (const auto &AI : FT->param_types()) {
15238 ParmVarDecl *Param =
15239 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15240 Param->setScopeInfo(0, Params.size());
15241 Params.push_back(Param);
15243 NewFD->setParams(Params);
15244 DRE->setDecl(NewFD);
15245 VD = DRE->getDecl();
15249 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15250 if (MD->isInstance()) {
15251 ValueKind = VK_RValue;
15252 Type = S.Context.BoundMemberTy;
15255 // Function references aren't l-values in C.
15256 if (!S.getLangOpts().CPlusPlus)
15257 ValueKind = VK_RValue;
15260 } else if (isa<VarDecl>(VD)) {
15261 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15262 Type = RefTy->getPointeeType();
15263 } else if (Type->isFunctionType()) {
15264 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15265 << VD << E->getSourceRange();
15266 return ExprError();
15271 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15272 << VD << E->getSourceRange();
15273 return ExprError();
15276 // Modifying the declaration like this is friendly to IR-gen but
15277 // also really dangerous.
15278 VD->setType(DestType);
15280 E->setValueKind(ValueKind);
15284 /// Check a cast of an unknown-any type. We intentionally only
15285 /// trigger this for C-style casts.
15286 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15287 Expr *CastExpr, CastKind &CastKind,
15288 ExprValueKind &VK, CXXCastPath &Path) {
15289 // The type we're casting to must be either void or complete.
15290 if (!CastType->isVoidType() &&
15291 RequireCompleteType(TypeRange.getBegin(), CastType,
15292 diag::err_typecheck_cast_to_incomplete))
15293 return ExprError();
15295 // Rewrite the casted expression from scratch.
15296 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15297 if (!result.isUsable()) return ExprError();
15299 CastExpr = result.get();
15300 VK = CastExpr->getValueKind();
15301 CastKind = CK_NoOp;
15306 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15307 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15310 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15311 Expr *arg, QualType ¶mType) {
15312 // If the syntactic form of the argument is not an explicit cast of
15313 // any sort, just do default argument promotion.
15314 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15316 ExprResult result = DefaultArgumentPromotion(arg);
15317 if (result.isInvalid()) return ExprError();
15318 paramType = result.get()->getType();
15322 // Otherwise, use the type that was written in the explicit cast.
15323 assert(!arg->hasPlaceholderType());
15324 paramType = castArg->getTypeAsWritten();
15326 // Copy-initialize a parameter of that type.
15327 InitializedEntity entity =
15328 InitializedEntity::InitializeParameter(Context, paramType,
15329 /*consumed*/ false);
15330 return PerformCopyInitialization(entity, callLoc, arg);
15333 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15335 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15337 E = E->IgnoreParenImpCasts();
15338 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15339 E = call->getCallee();
15340 diagID = diag::err_uncasted_call_of_unknown_any;
15346 SourceLocation loc;
15348 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15349 loc = ref->getLocation();
15350 d = ref->getDecl();
15351 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15352 loc = mem->getMemberLoc();
15353 d = mem->getMemberDecl();
15354 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15355 diagID = diag::err_uncasted_call_of_unknown_any;
15356 loc = msg->getSelectorStartLoc();
15357 d = msg->getMethodDecl();
15359 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15360 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15361 << orig->getSourceRange();
15362 return ExprError();
15365 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15366 << E->getSourceRange();
15367 return ExprError();
15370 S.Diag(loc, diagID) << d << orig->getSourceRange();
15372 // Never recoverable.
15373 return ExprError();
15376 /// Check for operands with placeholder types and complain if found.
15377 /// Returns true if there was an error and no recovery was possible.
15378 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15379 if (!getLangOpts().CPlusPlus) {
15380 // C cannot handle TypoExpr nodes on either side of a binop because it
15381 // doesn't handle dependent types properly, so make sure any TypoExprs have
15382 // been dealt with before checking the operands.
15383 ExprResult Result = CorrectDelayedTyposInExpr(E);
15384 if (!Result.isUsable()) return ExprError();
15388 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15389 if (!placeholderType) return E;
15391 switch (placeholderType->getKind()) {
15393 // Overloaded expressions.
15394 case BuiltinType::Overload: {
15395 // Try to resolve a single function template specialization.
15396 // This is obligatory.
15397 ExprResult Result = E;
15398 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15401 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15402 // leaves Result unchanged on failure.
15404 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15407 // If that failed, try to recover with a call.
15408 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15409 /*complain*/ true);
15413 // Bound member functions.
15414 case BuiltinType::BoundMember: {
15415 ExprResult result = E;
15416 const Expr *BME = E->IgnoreParens();
15417 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15418 // Try to give a nicer diagnostic if it is a bound member that we recognize.
15419 if (isa<CXXPseudoDestructorExpr>(BME)) {
15420 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15421 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15422 if (ME->getMemberNameInfo().getName().getNameKind() ==
15423 DeclarationName::CXXDestructorName)
15424 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15426 tryToRecoverWithCall(result, PD,
15427 /*complain*/ true);
15431 // ARC unbridged casts.
15432 case BuiltinType::ARCUnbridgedCast: {
15433 Expr *realCast = stripARCUnbridgedCast(E);
15434 diagnoseARCUnbridgedCast(realCast);
15438 // Expressions of unknown type.
15439 case BuiltinType::UnknownAny:
15440 return diagnoseUnknownAnyExpr(*this, E);
15443 case BuiltinType::PseudoObject:
15444 return checkPseudoObjectRValue(E);
15446 case BuiltinType::BuiltinFn: {
15447 // Accept __noop without parens by implicitly converting it to a call expr.
15448 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15450 auto *FD = cast<FunctionDecl>(DRE->getDecl());
15451 if (FD->getBuiltinID() == Builtin::BI__noop) {
15452 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15453 CK_BuiltinFnToFnPtr).get();
15454 return new (Context) CallExpr(Context, E, None, Context.IntTy,
15455 VK_RValue, SourceLocation());
15459 Diag(E->getLocStart(), diag::err_builtin_fn_use);
15460 return ExprError();
15463 // Expressions of unknown type.
15464 case BuiltinType::OMPArraySection:
15465 Diag(E->getLocStart(), diag::err_omp_array_section_use);
15466 return ExprError();
15468 // Everything else should be impossible.
15469 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15470 case BuiltinType::Id:
15471 #include "clang/Basic/OpenCLImageTypes.def"
15472 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15473 #define PLACEHOLDER_TYPE(Id, SingletonId)
15474 #include "clang/AST/BuiltinTypes.def"
15478 llvm_unreachable("invalid placeholder type!");
15481 bool Sema::CheckCaseExpression(Expr *E) {
15482 if (E->isTypeDependent())
15484 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15485 return E->getType()->isIntegralOrEnumerationType();
15489 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15491 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15492 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15493 "Unknown Objective-C Boolean value!");
15494 QualType BoolT = Context.ObjCBuiltinBoolTy;
15495 if (!Context.getBOOLDecl()) {
15496 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15497 Sema::LookupOrdinaryName);
15498 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15499 NamedDecl *ND = Result.getFoundDecl();
15500 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15501 Context.setBOOLDecl(TD);
15504 if (Context.getBOOLDecl())
15505 BoolT = Context.getBOOLType();
15506 return new (Context)
15507 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15510 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15511 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15512 SourceLocation RParen) {
15514 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15516 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15517 [&](const AvailabilitySpec &Spec) {
15518 return Spec.getPlatform() == Platform;
15521 VersionTuple Version;
15522 if (Spec != AvailSpecs.end())
15523 Version = Spec->getVersion();
15525 return new (Context)
15526 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);