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 && S.getCurFunctionOrMethodDecl()) {
175 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
179 const ObjCPropertyDecl *ObjCPDecl = nullptr;
180 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
181 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
182 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
183 if (PDeclResult == Result)
188 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
189 ObjCPDecl, ObjCPropertyAccess);
193 /// \brief Emit a note explaining that this function is deleted.
194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
195 assert(Decl->isDeleted());
197 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
199 if (Method && Method->isDeleted() && Method->isDefaulted()) {
200 // If the method was explicitly defaulted, point at that declaration.
201 if (!Method->isImplicit())
202 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
204 // Try to diagnose why this special member function was implicitly
205 // deleted. This might fail, if that reason no longer applies.
206 CXXSpecialMember CSM = getSpecialMember(Method);
207 if (CSM != CXXInvalid)
208 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
213 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
214 if (Ctor && Ctor->isInheritingConstructor())
215 return NoteDeletedInheritingConstructor(Ctor);
217 Diag(Decl->getLocation(), diag::note_availability_specified_here)
221 /// \brief Determine whether a FunctionDecl was ever declared with an
222 /// explicit storage class.
223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
224 for (auto I : D->redecls()) {
225 if (I->getStorageClass() != SC_None)
231 /// \brief Check whether we're in an extern inline function and referring to a
232 /// variable or function with internal linkage (C11 6.7.4p3).
234 /// This is only a warning because we used to silently accept this code, but
235 /// in many cases it will not behave correctly. This is not enabled in C++ mode
236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
237 /// and so while there may still be user mistakes, most of the time we can't
238 /// prove that there are errors.
239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
241 SourceLocation Loc) {
242 // This is disabled under C++; there are too many ways for this to fire in
243 // contexts where the warning is a false positive, or where it is technically
244 // correct but benign.
245 if (S.getLangOpts().CPlusPlus)
248 // Check if this is an inlined function or method.
249 FunctionDecl *Current = S.getCurFunctionDecl();
252 if (!Current->isInlined())
254 if (!Current->isExternallyVisible())
257 // Check if the decl has internal linkage.
258 if (D->getFormalLinkage() != InternalLinkage)
261 // Downgrade from ExtWarn to Extension if
262 // (1) the supposedly external inline function is in the main file,
263 // and probably won't be included anywhere else.
264 // (2) the thing we're referencing is a pure function.
265 // (3) the thing we're referencing is another inline function.
266 // This last can give us false negatives, but it's better than warning on
267 // wrappers for simple C library functions.
268 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
269 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
270 if (!DowngradeWarning && UsedFn)
271 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
273 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
274 : diag::ext_internal_in_extern_inline)
275 << /*IsVar=*/!UsedFn << D;
277 S.MaybeSuggestAddingStaticToDecl(Current);
279 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
284 const FunctionDecl *First = Cur->getFirstDecl();
286 // Suggest "static" on the function, if possible.
287 if (!hasAnyExplicitStorageClass(First)) {
288 SourceLocation DeclBegin = First->getSourceRange().getBegin();
289 Diag(DeclBegin, diag::note_convert_inline_to_static)
290 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
294 /// \brief Determine whether the use of this declaration is valid, and
295 /// emit any corresponding diagnostics.
297 /// This routine diagnoses various problems with referencing
298 /// declarations that can occur when using a declaration. For example,
299 /// it might warn if a deprecated or unavailable declaration is being
300 /// used, or produce an error (and return true) if a C++0x deleted
301 /// function is being used.
303 /// \returns true if there was an error (this declaration cannot be
304 /// referenced), false otherwise.
306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
307 const ObjCInterfaceDecl *UnknownObjCClass,
308 bool ObjCPropertyAccess) {
309 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
310 // If there were any diagnostics suppressed by template argument deduction,
312 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
313 if (Pos != SuppressedDiagnostics.end()) {
314 for (const PartialDiagnosticAt &Suppressed : Pos->second)
315 Diag(Suppressed.first, Suppressed.second);
317 // Clear out the list of suppressed diagnostics, so that we don't emit
318 // them again for this specialization. However, we don't obsolete this
319 // entry from the table, because we want to avoid ever emitting these
320 // diagnostics again.
324 // C++ [basic.start.main]p3:
325 // The function 'main' shall not be used within a program.
326 if (cast<FunctionDecl>(D)->isMain())
327 Diag(Loc, diag::ext_main_used);
330 // See if this is an auto-typed variable whose initializer we are parsing.
331 if (ParsingInitForAutoVars.count(D)) {
332 if (isa<BindingDecl>(D)) {
333 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
336 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
337 << D->getDeclName() << cast<VarDecl>(D)->getType();
342 // See if this is a deleted function.
343 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
344 if (FD->isDeleted()) {
345 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
346 if (Ctor && Ctor->isInheritingConstructor())
347 Diag(Loc, diag::err_deleted_inherited_ctor_use)
349 << Ctor->getInheritedConstructor().getConstructor()->getParent();
351 Diag(Loc, diag::err_deleted_function_use);
352 NoteDeletedFunction(FD);
356 // If the function has a deduced return type, and we can't deduce it,
357 // then we can't use it either.
358 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
359 DeduceReturnType(FD, Loc))
362 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
365 if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
369 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
370 // Only the variables omp_in and omp_out are allowed in the combiner.
371 // Only the variables omp_priv and omp_orig are allowed in the
372 // initializer-clause.
373 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
374 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
376 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
377 << getCurFunction()->HasOMPDeclareReductionCombiner;
378 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
382 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
385 DiagnoseUnusedOfDecl(*this, D, Loc);
387 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
392 /// \brief Retrieve the message suffix that should be added to a
393 /// diagnostic complaining about the given function being deleted or
395 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
397 if (FD->getAvailability(&Message))
398 return ": " + Message;
400 return std::string();
403 /// DiagnoseSentinelCalls - This routine checks whether a call or
404 /// message-send is to a declaration with the sentinel attribute, and
405 /// if so, it checks that the requirements of the sentinel are
407 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
408 ArrayRef<Expr *> Args) {
409 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
413 // The number of formal parameters of the declaration.
414 unsigned numFormalParams;
416 // The kind of declaration. This is also an index into a %select in
418 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
420 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
421 numFormalParams = MD->param_size();
422 calleeType = CT_Method;
423 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
424 numFormalParams = FD->param_size();
425 calleeType = CT_Function;
426 } else if (isa<VarDecl>(D)) {
427 QualType type = cast<ValueDecl>(D)->getType();
428 const FunctionType *fn = nullptr;
429 if (const PointerType *ptr = type->getAs<PointerType>()) {
430 fn = ptr->getPointeeType()->getAs<FunctionType>();
432 calleeType = CT_Function;
433 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
434 fn = ptr->getPointeeType()->castAs<FunctionType>();
435 calleeType = CT_Block;
440 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
441 numFormalParams = proto->getNumParams();
449 // "nullPos" is the number of formal parameters at the end which
450 // effectively count as part of the variadic arguments. This is
451 // useful if you would prefer to not have *any* formal parameters,
452 // but the language forces you to have at least one.
453 unsigned nullPos = attr->getNullPos();
454 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
455 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
457 // The number of arguments which should follow the sentinel.
458 unsigned numArgsAfterSentinel = attr->getSentinel();
460 // If there aren't enough arguments for all the formal parameters,
461 // the sentinel, and the args after the sentinel, complain.
462 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
463 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
464 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
468 // Otherwise, find the sentinel expression.
469 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
470 if (!sentinelExpr) return;
471 if (sentinelExpr->isValueDependent()) return;
472 if (Context.isSentinelNullExpr(sentinelExpr)) return;
474 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
475 // or 'NULL' if those are actually defined in the context. Only use
476 // 'nil' for ObjC methods, where it's much more likely that the
477 // variadic arguments form a list of object pointers.
478 SourceLocation MissingNilLoc
479 = getLocForEndOfToken(sentinelExpr->getLocEnd());
480 std::string NullValue;
481 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
483 else if (getLangOpts().CPlusPlus11)
484 NullValue = "nullptr";
485 else if (PP.isMacroDefined("NULL"))
488 NullValue = "(void*) 0";
490 if (MissingNilLoc.isInvalid())
491 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
493 Diag(MissingNilLoc, diag::warn_missing_sentinel)
495 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
496 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
499 SourceRange Sema::getExprRange(Expr *E) const {
500 return E ? E->getSourceRange() : SourceRange();
503 //===----------------------------------------------------------------------===//
504 // Standard Promotions and Conversions
505 //===----------------------------------------------------------------------===//
507 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
508 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
509 // Handle any placeholder expressions which made it here.
510 if (E->getType()->isPlaceholderType()) {
511 ExprResult result = CheckPlaceholderExpr(E);
512 if (result.isInvalid()) return ExprError();
516 QualType Ty = E->getType();
517 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
519 if (Ty->isFunctionType()) {
520 // If we are here, we are not calling a function but taking
521 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
522 if (getLangOpts().OpenCL) {
524 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
530 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
533 E = ImpCastExprToType(E, Context.getPointerType(Ty),
534 CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
548 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
549 CK_ArrayToPointerDecay).get();
554 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
555 // Check to see if we are dereferencing a null pointer. If so,
556 // and if not volatile-qualified, this is undefined behavior that the
557 // optimizer will delete, so warn about it. People sometimes try to use this
558 // to get a deterministic trap and are surprised by clang's behavior. This
559 // only handles the pattern "*null", which is a very syntactic check.
560 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
561 if (UO->getOpcode() == UO_Deref &&
562 UO->getSubExpr()->IgnoreParenCasts()->
563 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
564 !UO->getType().isVolatileQualified()) {
565 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
566 S.PDiag(diag::warn_indirection_through_null)
567 << UO->getSubExpr()->getSourceRange());
568 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
569 S.PDiag(diag::note_indirection_through_null));
573 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
574 SourceLocation AssignLoc,
576 const ObjCIvarDecl *IV = OIRE->getDecl();
580 DeclarationName MemberName = IV->getDeclName();
581 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
582 if (!Member || !Member->isStr("isa"))
585 const Expr *Base = OIRE->getBase();
586 QualType BaseType = Base->getType();
588 BaseType = BaseType->getPointeeType();
589 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
590 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
591 ObjCInterfaceDecl *ClassDeclared = nullptr;
592 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
593 if (!ClassDeclared->getSuperClass()
594 && (*ClassDeclared->ivar_begin()) == IV) {
596 NamedDecl *ObjectSetClass =
597 S.LookupSingleName(S.TUScope,
598 &S.Context.Idents.get("object_setClass"),
599 SourceLocation(), S.LookupOrdinaryName);
600 if (ObjectSetClass) {
601 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
602 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
603 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
604 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
606 FixItHint::CreateInsertion(RHSLocEnd, ")");
609 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
611 NamedDecl *ObjectGetClass =
612 S.LookupSingleName(S.TUScope,
613 &S.Context.Idents.get("object_getClass"),
614 SourceLocation(), S.LookupOrdinaryName);
616 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
617 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
618 FixItHint::CreateReplacement(
619 SourceRange(OIRE->getOpLoc(),
620 OIRE->getLocEnd()), ")");
622 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
624 S.Diag(IV->getLocation(), diag::note_ivar_decl);
629 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
630 // Handle any placeholder expressions which made it here.
631 if (E->getType()->isPlaceholderType()) {
632 ExprResult result = CheckPlaceholderExpr(E);
633 if (result.isInvalid()) return ExprError();
637 // C++ [conv.lval]p1:
638 // A glvalue of a non-function, non-array type T can be
639 // converted to a prvalue.
640 if (!E->isGLValue()) return E;
642 QualType T = E->getType();
643 assert(!T.isNull() && "r-value conversion on typeless expression?");
645 // We don't want to throw lvalue-to-rvalue casts on top of
646 // expressions of certain types in C++.
647 if (getLangOpts().CPlusPlus &&
648 (E->getType() == Context.OverloadTy ||
649 T->isDependentType() ||
653 // The C standard is actually really unclear on this point, and
654 // DR106 tells us what the result should be but not why. It's
655 // generally best to say that void types just doesn't undergo
656 // lvalue-to-rvalue at all. Note that expressions of unqualified
657 // 'void' type are never l-values, but qualified void can be.
661 // OpenCL usually rejects direct accesses to values of 'half' type.
662 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
664 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
669 CheckForNullPointerDereference(*this, E);
670 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
671 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
672 &Context.Idents.get("object_getClass"),
673 SourceLocation(), LookupOrdinaryName);
675 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
676 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
677 FixItHint::CreateReplacement(
678 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
680 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
682 else if (const ObjCIvarRefExpr *OIRE =
683 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
684 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
686 // C++ [conv.lval]p1:
687 // [...] If T is a non-class type, the type of the prvalue is the
688 // cv-unqualified version of T. Otherwise, the type of the
692 // If the lvalue has qualified type, the value has the unqualified
693 // version of the type of the lvalue; otherwise, the value has the
694 // type of the lvalue.
695 if (T.hasQualifiers())
696 T = T.getUnqualifiedType();
698 // Under the MS ABI, lock down the inheritance model now.
699 if (T->isMemberPointerType() &&
700 Context.getTargetInfo().getCXXABI().isMicrosoft())
701 (void)isCompleteType(E->getExprLoc(), T);
703 UpdateMarkingForLValueToRValue(E);
705 // Loading a __weak object implicitly retains the value, so we need a cleanup to
707 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
708 Cleanup.setExprNeedsCleanups(true);
710 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
714 // ... if the lvalue has atomic type, the value has the non-atomic version
715 // of the type of the lvalue ...
716 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
717 T = Atomic->getValueType().getUnqualifiedType();
718 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
725 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
726 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
729 Res = DefaultLvalueConversion(Res.get());
735 /// CallExprUnaryConversions - a special case of an unary conversion
736 /// performed on a function designator of a call expression.
737 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
738 QualType Ty = E->getType();
740 // Only do implicit cast for a function type, but not for a pointer
742 if (Ty->isFunctionType()) {
743 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
744 CK_FunctionToPointerDecay).get();
748 Res = DefaultLvalueConversion(Res.get());
754 /// UsualUnaryConversions - Performs various conversions that are common to most
755 /// operators (C99 6.3). The conversions of array and function types are
756 /// sometimes suppressed. For example, the array->pointer conversion doesn't
757 /// apply if the array is an argument to the sizeof or address (&) operators.
758 /// In these instances, this routine should *not* be called.
759 ExprResult Sema::UsualUnaryConversions(Expr *E) {
760 // First, convert to an r-value.
761 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
766 QualType Ty = E->getType();
767 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
769 // Half FP have to be promoted to float unless it is natively supported
770 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
771 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
773 // Try to perform integral promotions if the object has a theoretically
775 if (Ty->isIntegralOrUnscopedEnumerationType()) {
778 // The following may be used in an expression wherever an int or
779 // unsigned int may be used:
780 // - an object or expression with an integer type whose integer
781 // conversion rank is less than or equal to the rank of int
783 // - A bit-field of type _Bool, int, signed int, or unsigned int.
785 // If an int can represent all values of the original type, the
786 // value is converted to an int; otherwise, it is converted to an
787 // unsigned int. These are called the integer promotions. All
788 // other types are unchanged by the integer promotions.
790 QualType PTy = Context.isPromotableBitField(E);
792 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
795 if (Ty->isPromotableIntegerType()) {
796 QualType PT = Context.getPromotedIntegerType(Ty);
797 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
804 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
805 /// do not have a prototype. Arguments that have type float or __fp16
806 /// are promoted to double. All other argument types are converted by
807 /// UsualUnaryConversions().
808 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
809 QualType Ty = E->getType();
810 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
812 ExprResult Res = UsualUnaryConversions(E);
817 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
819 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
820 if (BTy && (BTy->getKind() == BuiltinType::Half ||
821 BTy->getKind() == BuiltinType::Float)) {
822 if (getLangOpts().OpenCL &&
823 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
824 if (BTy->getKind() == BuiltinType::Half) {
825 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
828 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
832 // C++ performs lvalue-to-rvalue conversion as a default argument
833 // promotion, even on class types, but note:
834 // C++11 [conv.lval]p2:
835 // When an lvalue-to-rvalue conversion occurs in an unevaluated
836 // operand or a subexpression thereof the value contained in the
837 // referenced object is not accessed. Otherwise, if the glvalue
838 // has a class type, the conversion copy-initializes a temporary
839 // of type T from the glvalue and the result of the conversion
840 // is a prvalue for the temporary.
841 // FIXME: add some way to gate this entire thing for correctness in
842 // potentially potentially evaluated contexts.
843 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
844 ExprResult Temp = PerformCopyInitialization(
845 InitializedEntity::InitializeTemporary(E->getType()),
847 if (Temp.isInvalid())
855 /// Determine the degree of POD-ness for an expression.
856 /// Incomplete types are considered POD, since this check can be performed
857 /// when we're in an unevaluated context.
858 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
859 if (Ty->isIncompleteType()) {
860 // C++11 [expr.call]p7:
861 // After these conversions, if the argument does not have arithmetic,
862 // enumeration, pointer, pointer to member, or class type, the program
865 // Since we've already performed array-to-pointer and function-to-pointer
866 // decay, the only such type in C++ is cv void. This also handles
867 // initializer lists as variadic arguments.
868 if (Ty->isVoidType())
871 if (Ty->isObjCObjectType())
876 if (Ty.isCXX98PODType(Context))
879 // C++11 [expr.call]p7:
880 // Passing a potentially-evaluated argument of class type (Clause 9)
881 // having a non-trivial copy constructor, a non-trivial move constructor,
882 // or a non-trivial destructor, with no corresponding parameter,
883 // is conditionally-supported with implementation-defined semantics.
884 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
885 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
886 if (!Record->hasNonTrivialCopyConstructor() &&
887 !Record->hasNonTrivialMoveConstructor() &&
888 !Record->hasNonTrivialDestructor())
889 return VAK_ValidInCXX11;
891 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
894 if (Ty->isObjCObjectType())
897 if (getLangOpts().MSVCCompat)
898 return VAK_MSVCUndefined;
900 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
901 // permitted to reject them. We should consider doing so.
902 return VAK_Undefined;
905 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
906 // Don't allow one to pass an Objective-C interface to a vararg.
907 const QualType &Ty = E->getType();
908 VarArgKind VAK = isValidVarArgType(Ty);
910 // Complain about passing non-POD types through varargs.
912 case VAK_ValidInCXX11:
914 E->getLocStart(), nullptr,
915 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
919 if (Ty->isRecordType()) {
920 // This is unlikely to be what the user intended. If the class has a
921 // 'c_str' member function, the user probably meant to call that.
922 DiagRuntimeBehavior(E->getLocStart(), nullptr,
923 PDiag(diag::warn_pass_class_arg_to_vararg)
924 << Ty << CT << hasCStrMethod(E) << ".c_str()");
929 case VAK_MSVCUndefined:
931 E->getLocStart(), nullptr,
932 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
933 << getLangOpts().CPlusPlus11 << Ty << CT);
937 if (Ty->isObjCObjectType())
939 E->getLocStart(), nullptr,
940 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
943 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
944 << isa<InitListExpr>(E) << Ty << CT;
949 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
950 /// will create a trap if the resulting type is not a POD type.
951 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
952 FunctionDecl *FDecl) {
953 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
954 // Strip the unbridged-cast placeholder expression off, if applicable.
955 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
956 (CT == VariadicMethod ||
957 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
958 E = stripARCUnbridgedCast(E);
960 // Otherwise, do normal placeholder checking.
962 ExprResult ExprRes = CheckPlaceholderExpr(E);
963 if (ExprRes.isInvalid())
969 ExprResult ExprRes = DefaultArgumentPromotion(E);
970 if (ExprRes.isInvalid())
974 // Diagnostics regarding non-POD argument types are
975 // emitted along with format string checking in Sema::CheckFunctionCall().
976 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
977 // Turn this into a trap.
979 SourceLocation TemplateKWLoc;
981 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
983 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
985 if (TrapFn.isInvalid())
988 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
989 E->getLocStart(), None,
991 if (Call.isInvalid())
994 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
996 if (Comma.isInvalid())
1001 if (!getLangOpts().CPlusPlus &&
1002 RequireCompleteType(E->getExprLoc(), E->getType(),
1003 diag::err_call_incomplete_argument))
1009 /// \brief Converts an integer to complex float type. Helper function of
1010 /// UsualArithmeticConversions()
1012 /// \return false if the integer expression is an integer type and is
1013 /// successfully converted to the complex type.
1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1015 ExprResult &ComplexExpr,
1019 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1020 if (SkipCast) return false;
1021 if (IntTy->isIntegerType()) {
1022 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1025 CK_FloatingRealToComplex);
1027 assert(IntTy->isComplexIntegerType());
1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1029 CK_IntegralComplexToFloatingComplex);
1034 /// \brief Handle arithmetic conversion with complex types. Helper function of
1035 /// UsualArithmeticConversions()
1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1037 ExprResult &RHS, QualType LHSType,
1039 bool IsCompAssign) {
1040 // if we have an integer operand, the result is the complex type.
1041 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1044 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1045 /*skipCast*/IsCompAssign))
1048 // This handles complex/complex, complex/float, or float/complex.
1049 // When both operands are complex, the shorter operand is converted to the
1050 // type of the longer, and that is the type of the result. This corresponds
1051 // to what is done when combining two real floating-point operands.
1052 // The fun begins when size promotion occur across type domains.
1053 // From H&S 6.3.4: When one operand is complex and the other is a real
1054 // floating-point type, the less precise type is converted, within it's
1055 // real or complex domain, to the precision of the other type. For example,
1056 // when combining a "long double" with a "double _Complex", the
1057 // "double _Complex" is promoted to "long double _Complex".
1059 // Compute the rank of the two types, regardless of whether they are complex.
1060 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1062 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1063 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1064 QualType LHSElementType =
1065 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1066 QualType RHSElementType =
1067 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1069 QualType ResultType = S.Context.getComplexType(LHSElementType);
1071 // Promote the precision of the LHS if not an assignment.
1072 ResultType = S.Context.getComplexType(RHSElementType);
1073 if (!IsCompAssign) {
1076 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1078 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1080 } else if (Order > 0) {
1081 // Promote the precision of the RHS.
1083 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1085 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1090 /// \brief Hande arithmetic conversion from integer to float. Helper function
1091 /// of UsualArithmeticConversions()
1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1093 ExprResult &IntExpr,
1094 QualType FloatTy, QualType IntTy,
1095 bool ConvertFloat, bool ConvertInt) {
1096 if (IntTy->isIntegerType()) {
1098 // Convert intExpr to the lhs floating point type.
1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1100 CK_IntegralToFloating);
1104 // Convert both sides to the appropriate complex float.
1105 assert(IntTy->isComplexIntegerType());
1106 QualType result = S.Context.getComplexType(FloatTy);
1108 // _Complex int -> _Complex float
1110 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1111 CK_IntegralComplexToFloatingComplex);
1113 // float -> _Complex float
1115 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1116 CK_FloatingRealToComplex);
1121 /// \brief Handle arithmethic conversion with floating point types. Helper
1122 /// function of UsualArithmeticConversions()
1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1124 ExprResult &RHS, QualType LHSType,
1125 QualType RHSType, bool IsCompAssign) {
1126 bool LHSFloat = LHSType->isRealFloatingType();
1127 bool RHSFloat = RHSType->isRealFloatingType();
1129 // If we have two real floating types, convert the smaller operand
1130 // to the bigger result.
1131 if (LHSFloat && RHSFloat) {
1132 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1134 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1138 assert(order < 0 && "illegal float comparison");
1140 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1145 // Half FP has to be promoted to float unless it is natively supported
1146 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1147 LHSType = S.Context.FloatTy;
1149 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1150 /*convertFloat=*/!IsCompAssign,
1151 /*convertInt=*/ true);
1154 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1155 /*convertInt=*/ true,
1156 /*convertFloat=*/!IsCompAssign);
1159 /// \brief Diagnose attempts to convert between __float128 and long double if
1160 /// there is no support for such conversion. Helper function of
1161 /// UsualArithmeticConversions().
1162 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1164 /* No issue converting if at least one of the types is not a floating point
1165 type or the two types have the same rank.
1167 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1168 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1171 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1172 "The remaining types must be floating point types.");
1174 auto *LHSComplex = LHSType->getAs<ComplexType>();
1175 auto *RHSComplex = RHSType->getAs<ComplexType>();
1177 QualType LHSElemType = LHSComplex ?
1178 LHSComplex->getElementType() : LHSType;
1179 QualType RHSElemType = RHSComplex ?
1180 RHSComplex->getElementType() : RHSType;
1182 // No issue if the two types have the same representation
1183 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1184 &S.Context.getFloatTypeSemantics(RHSElemType))
1187 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1188 RHSElemType == S.Context.LongDoubleTy);
1189 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1190 RHSElemType == S.Context.Float128Ty);
1192 /* We've handled the situation where __float128 and long double have the same
1193 representation. The only other allowable conversion is if long double is
1196 return Float128AndLongDouble &&
1197 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1198 &llvm::APFloat::IEEEdouble());
1201 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1204 /// These helper callbacks are placed in an anonymous namespace to
1205 /// permit their use as function template parameters.
1206 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1207 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1210 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1211 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1212 CK_IntegralComplexCast);
1216 /// \brief Handle integer arithmetic conversions. Helper function of
1217 /// UsualArithmeticConversions()
1218 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1219 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1220 ExprResult &RHS, QualType LHSType,
1221 QualType RHSType, bool IsCompAssign) {
1222 // The rules for this case are in C99 6.3.1.8
1223 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1224 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1225 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1226 if (LHSSigned == RHSSigned) {
1227 // Same signedness; use the higher-ranked type
1229 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1231 } else if (!IsCompAssign)
1232 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1234 } else if (order != (LHSSigned ? 1 : -1)) {
1235 // The unsigned type has greater than or equal rank to the
1236 // signed type, so use the unsigned type
1238 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1240 } else if (!IsCompAssign)
1241 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1243 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1244 // The two types are different widths; if we are here, that
1245 // means the signed type is larger than the unsigned type, so
1246 // use the signed type.
1248 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1250 } else if (!IsCompAssign)
1251 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1254 // The signed type is higher-ranked than the unsigned type,
1255 // but isn't actually any bigger (like unsigned int and long
1256 // on most 32-bit systems). Use the unsigned type corresponding
1257 // to the signed type.
1259 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1260 RHS = (*doRHSCast)(S, RHS.get(), result);
1262 LHS = (*doLHSCast)(S, LHS.get(), result);
1267 /// \brief Handle conversions with GCC complex int extension. Helper function
1268 /// of UsualArithmeticConversions()
1269 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1270 ExprResult &RHS, QualType LHSType,
1272 bool IsCompAssign) {
1273 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1274 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1276 if (LHSComplexInt && RHSComplexInt) {
1277 QualType LHSEltType = LHSComplexInt->getElementType();
1278 QualType RHSEltType = RHSComplexInt->getElementType();
1279 QualType ScalarType =
1280 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1281 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1283 return S.Context.getComplexType(ScalarType);
1286 if (LHSComplexInt) {
1287 QualType LHSEltType = LHSComplexInt->getElementType();
1288 QualType ScalarType =
1289 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1290 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1291 QualType ComplexType = S.Context.getComplexType(ScalarType);
1292 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1293 CK_IntegralRealToComplex);
1298 assert(RHSComplexInt);
1300 QualType RHSEltType = RHSComplexInt->getElementType();
1301 QualType ScalarType =
1302 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1303 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1304 QualType ComplexType = S.Context.getComplexType(ScalarType);
1307 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1308 CK_IntegralRealToComplex);
1312 /// UsualArithmeticConversions - Performs various conversions that are common to
1313 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1314 /// routine returns the first non-arithmetic type found. The client is
1315 /// responsible for emitting appropriate error diagnostics.
1316 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1317 bool IsCompAssign) {
1318 if (!IsCompAssign) {
1319 LHS = UsualUnaryConversions(LHS.get());
1320 if (LHS.isInvalid())
1324 RHS = UsualUnaryConversions(RHS.get());
1325 if (RHS.isInvalid())
1328 // For conversion purposes, we ignore any qualifiers.
1329 // For example, "const float" and "float" are equivalent.
1331 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1333 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1335 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1336 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1337 LHSType = AtomicLHS->getValueType();
1339 // If both types are identical, no conversion is needed.
1340 if (LHSType == RHSType)
1343 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1344 // The caller can deal with this (e.g. pointer + int).
1345 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1348 // Apply unary and bitfield promotions to the LHS's type.
1349 QualType LHSUnpromotedType = LHSType;
1350 if (LHSType->isPromotableIntegerType())
1351 LHSType = Context.getPromotedIntegerType(LHSType);
1352 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1353 if (!LHSBitfieldPromoteTy.isNull())
1354 LHSType = LHSBitfieldPromoteTy;
1355 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1356 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1358 // If both types are identical, no conversion is needed.
1359 if (LHSType == RHSType)
1362 // At this point, we have two different arithmetic types.
1364 // Diagnose attempts to convert between __float128 and long double where
1365 // such conversions currently can't be handled.
1366 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1369 // Handle complex types first (C99 6.3.1.8p1).
1370 if (LHSType->isComplexType() || RHSType->isComplexType())
1371 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1374 // Now handle "real" floating types (i.e. float, double, long double).
1375 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1376 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1379 // Handle GCC complex int extension.
1380 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1381 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1384 // Finally, we have two differing integer types.
1385 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1386 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1390 //===----------------------------------------------------------------------===//
1391 // Semantic Analysis for various Expression Types
1392 //===----------------------------------------------------------------------===//
1396 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1397 SourceLocation DefaultLoc,
1398 SourceLocation RParenLoc,
1399 Expr *ControllingExpr,
1400 ArrayRef<ParsedType> ArgTypes,
1401 ArrayRef<Expr *> ArgExprs) {
1402 unsigned NumAssocs = ArgTypes.size();
1403 assert(NumAssocs == ArgExprs.size());
1405 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1406 for (unsigned i = 0; i < NumAssocs; ++i) {
1408 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1413 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1415 llvm::makeArrayRef(Types, NumAssocs),
1422 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1423 SourceLocation DefaultLoc,
1424 SourceLocation RParenLoc,
1425 Expr *ControllingExpr,
1426 ArrayRef<TypeSourceInfo *> Types,
1427 ArrayRef<Expr *> Exprs) {
1428 unsigned NumAssocs = Types.size();
1429 assert(NumAssocs == Exprs.size());
1431 // Decay and strip qualifiers for the controlling expression type, and handle
1432 // placeholder type replacement. See committee discussion from WG14 DR423.
1434 EnterExpressionEvaluationContext Unevaluated(
1435 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1436 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1439 ControllingExpr = R.get();
1442 // The controlling expression is an unevaluated operand, so side effects are
1443 // likely unintended.
1444 if (!inTemplateInstantiation() &&
1445 ControllingExpr->HasSideEffects(Context, false))
1446 Diag(ControllingExpr->getExprLoc(),
1447 diag::warn_side_effects_unevaluated_context);
1449 bool TypeErrorFound = false,
1450 IsResultDependent = ControllingExpr->isTypeDependent(),
1451 ContainsUnexpandedParameterPack
1452 = ControllingExpr->containsUnexpandedParameterPack();
1454 for (unsigned i = 0; i < NumAssocs; ++i) {
1455 if (Exprs[i]->containsUnexpandedParameterPack())
1456 ContainsUnexpandedParameterPack = true;
1459 if (Types[i]->getType()->containsUnexpandedParameterPack())
1460 ContainsUnexpandedParameterPack = true;
1462 if (Types[i]->getType()->isDependentType()) {
1463 IsResultDependent = true;
1465 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1466 // complete object type other than a variably modified type."
1468 if (Types[i]->getType()->isIncompleteType())
1469 D = diag::err_assoc_type_incomplete;
1470 else if (!Types[i]->getType()->isObjectType())
1471 D = diag::err_assoc_type_nonobject;
1472 else if (Types[i]->getType()->isVariablyModifiedType())
1473 D = diag::err_assoc_type_variably_modified;
1476 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1477 << Types[i]->getTypeLoc().getSourceRange()
1478 << Types[i]->getType();
1479 TypeErrorFound = true;
1482 // C11 6.5.1.1p2 "No two generic associations in the same generic
1483 // selection shall specify compatible types."
1484 for (unsigned j = i+1; j < NumAssocs; ++j)
1485 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1486 Context.typesAreCompatible(Types[i]->getType(),
1487 Types[j]->getType())) {
1488 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1489 diag::err_assoc_compatible_types)
1490 << Types[j]->getTypeLoc().getSourceRange()
1491 << Types[j]->getType()
1492 << Types[i]->getType();
1493 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1494 diag::note_compat_assoc)
1495 << Types[i]->getTypeLoc().getSourceRange()
1496 << Types[i]->getType();
1497 TypeErrorFound = true;
1505 // If we determined that the generic selection is result-dependent, don't
1506 // try to compute the result expression.
1507 if (IsResultDependent)
1508 return new (Context) GenericSelectionExpr(
1509 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1510 ContainsUnexpandedParameterPack);
1512 SmallVector<unsigned, 1> CompatIndices;
1513 unsigned DefaultIndex = -1U;
1514 for (unsigned i = 0; i < NumAssocs; ++i) {
1517 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1518 Types[i]->getType()))
1519 CompatIndices.push_back(i);
1522 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1523 // type compatible with at most one of the types named in its generic
1524 // association list."
1525 if (CompatIndices.size() > 1) {
1526 // We strip parens here because the controlling expression is typically
1527 // parenthesized in macro definitions.
1528 ControllingExpr = ControllingExpr->IgnoreParens();
1529 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1530 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1531 << (unsigned) CompatIndices.size();
1532 for (unsigned I : CompatIndices) {
1533 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1534 diag::note_compat_assoc)
1535 << Types[I]->getTypeLoc().getSourceRange()
1536 << Types[I]->getType();
1541 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1542 // its controlling expression shall have type compatible with exactly one of
1543 // the types named in its generic association list."
1544 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1545 // We strip parens here because the controlling expression is typically
1546 // parenthesized in macro definitions.
1547 ControllingExpr = ControllingExpr->IgnoreParens();
1548 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1549 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1553 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1554 // type name that is compatible with the type of the controlling expression,
1555 // then the result expression of the generic selection is the expression
1556 // in that generic association. Otherwise, the result expression of the
1557 // generic selection is the expression in the default generic association."
1558 unsigned ResultIndex =
1559 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1561 return new (Context) GenericSelectionExpr(
1562 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1563 ContainsUnexpandedParameterPack, ResultIndex);
1566 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1567 /// location of the token and the offset of the ud-suffix within it.
1568 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1570 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1574 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1575 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1576 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1577 IdentifierInfo *UDSuffix,
1578 SourceLocation UDSuffixLoc,
1579 ArrayRef<Expr*> Args,
1580 SourceLocation LitEndLoc) {
1581 assert(Args.size() <= 2 && "too many arguments for literal operator");
1584 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1585 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1586 if (ArgTy[ArgIdx]->isArrayType())
1587 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1590 DeclarationName OpName =
1591 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1592 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1593 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1595 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1596 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1597 /*AllowRaw*/false, /*AllowTemplate*/false,
1598 /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1601 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1604 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1605 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1606 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1607 /// multiple tokens. However, the common case is that StringToks points to one
1611 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1612 assert(!StringToks.empty() && "Must have at least one string!");
1614 StringLiteralParser Literal(StringToks, PP);
1615 if (Literal.hadError)
1618 SmallVector<SourceLocation, 4> StringTokLocs;
1619 for (const Token &Tok : StringToks)
1620 StringTokLocs.push_back(Tok.getLocation());
1622 QualType CharTy = Context.CharTy;
1623 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1624 if (Literal.isWide()) {
1625 CharTy = Context.getWideCharType();
1626 Kind = StringLiteral::Wide;
1627 } else if (Literal.isUTF8()) {
1628 Kind = StringLiteral::UTF8;
1629 } else if (Literal.isUTF16()) {
1630 CharTy = Context.Char16Ty;
1631 Kind = StringLiteral::UTF16;
1632 } else if (Literal.isUTF32()) {
1633 CharTy = Context.Char32Ty;
1634 Kind = StringLiteral::UTF32;
1635 } else if (Literal.isPascal()) {
1636 CharTy = Context.UnsignedCharTy;
1639 QualType CharTyConst = CharTy;
1640 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1641 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1642 CharTyConst.addConst();
1644 // Get an array type for the string, according to C99 6.4.5. This includes
1645 // the nul terminator character as well as the string length for pascal
1647 QualType StrTy = Context.getConstantArrayType(CharTyConst,
1648 llvm::APInt(32, Literal.GetNumStringChars()+1),
1649 ArrayType::Normal, 0);
1651 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1652 if (getLangOpts().OpenCL) {
1653 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1656 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1657 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1658 Kind, Literal.Pascal, StrTy,
1660 StringTokLocs.size());
1661 if (Literal.getUDSuffix().empty())
1664 // We're building a user-defined literal.
1665 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1666 SourceLocation UDSuffixLoc =
1667 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1668 Literal.getUDSuffixOffset());
1670 // Make sure we're allowed user-defined literals here.
1672 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1674 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1675 // operator "" X (str, len)
1676 QualType SizeType = Context.getSizeType();
1678 DeclarationName OpName =
1679 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1680 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1681 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1683 QualType ArgTy[] = {
1684 Context.getArrayDecayedType(StrTy), SizeType
1687 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1688 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1689 /*AllowRaw*/false, /*AllowTemplate*/false,
1690 /*AllowStringTemplate*/true)) {
1693 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1694 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1696 Expr *Args[] = { Lit, LenArg };
1698 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1701 case LOLR_StringTemplate: {
1702 TemplateArgumentListInfo ExplicitArgs;
1704 unsigned CharBits = Context.getIntWidth(CharTy);
1705 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1706 llvm::APSInt Value(CharBits, CharIsUnsigned);
1708 TemplateArgument TypeArg(CharTy);
1709 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1710 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1712 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1713 Value = Lit->getCodeUnit(I);
1714 TemplateArgument Arg(Context, Value, CharTy);
1715 TemplateArgumentLocInfo ArgInfo;
1716 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1718 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1723 llvm_unreachable("unexpected literal operator lookup result");
1727 llvm_unreachable("unexpected literal operator lookup result");
1731 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1733 const CXXScopeSpec *SS) {
1734 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1735 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1738 /// BuildDeclRefExpr - Build an expression that references a
1739 /// declaration that does not require a closure capture.
1741 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1742 const DeclarationNameInfo &NameInfo,
1743 const CXXScopeSpec *SS, NamedDecl *FoundD,
1744 const TemplateArgumentListInfo *TemplateArgs) {
1745 bool RefersToCapturedVariable =
1747 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1750 if (isa<VarTemplateSpecializationDecl>(D)) {
1751 VarTemplateSpecializationDecl *VarSpec =
1752 cast<VarTemplateSpecializationDecl>(D);
1754 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1755 : NestedNameSpecifierLoc(),
1756 VarSpec->getTemplateKeywordLoc(), D,
1757 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1758 FoundD, TemplateArgs);
1760 assert(!TemplateArgs && "No template arguments for non-variable"
1761 " template specialization references");
1762 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1763 : NestedNameSpecifierLoc(),
1764 SourceLocation(), D, RefersToCapturedVariable,
1765 NameInfo, Ty, VK, FoundD);
1768 MarkDeclRefReferenced(E);
1770 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1771 Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1772 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1773 recordUseOfEvaluatedWeak(E);
1775 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1776 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1777 FD = IFD->getAnonField();
1779 UnusedPrivateFields.remove(FD);
1780 // Just in case we're building an illegal pointer-to-member.
1781 if (FD->isBitField())
1782 E->setObjectKind(OK_BitField);
1785 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1786 // designates a bit-field.
1787 if (auto *BD = dyn_cast<BindingDecl>(D))
1788 if (auto *BE = BD->getBinding())
1789 E->setObjectKind(BE->getObjectKind());
1794 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1795 /// possibly a list of template arguments.
1797 /// If this produces template arguments, it is permitted to call
1798 /// DecomposeTemplateName.
1800 /// This actually loses a lot of source location information for
1801 /// non-standard name kinds; we should consider preserving that in
1804 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1805 TemplateArgumentListInfo &Buffer,
1806 DeclarationNameInfo &NameInfo,
1807 const TemplateArgumentListInfo *&TemplateArgs) {
1808 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1809 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1810 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1812 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1813 Id.TemplateId->NumArgs);
1814 translateTemplateArguments(TemplateArgsPtr, Buffer);
1816 TemplateName TName = Id.TemplateId->Template.get();
1817 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1818 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1819 TemplateArgs = &Buffer;
1821 NameInfo = GetNameFromUnqualifiedId(Id);
1822 TemplateArgs = nullptr;
1826 static void emitEmptyLookupTypoDiagnostic(
1827 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1828 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1829 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1831 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1833 // Emit a special diagnostic for failed member lookups.
1834 // FIXME: computing the declaration context might fail here (?)
1836 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1839 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1843 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1844 bool DroppedSpecifier =
1845 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1846 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1847 ? diag::note_implicit_param_decl
1848 : diag::note_previous_decl;
1850 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1851 SemaRef.PDiag(NoteID));
1853 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1854 << Typo << Ctx << DroppedSpecifier
1856 SemaRef.PDiag(NoteID));
1859 /// Diagnose an empty lookup.
1861 /// \return false if new lookup candidates were found
1863 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1864 std::unique_ptr<CorrectionCandidateCallback> CCC,
1865 TemplateArgumentListInfo *ExplicitTemplateArgs,
1866 ArrayRef<Expr *> Args, TypoExpr **Out) {
1867 DeclarationName Name = R.getLookupName();
1869 unsigned diagnostic = diag::err_undeclared_var_use;
1870 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1871 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1872 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1873 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1874 diagnostic = diag::err_undeclared_use;
1875 diagnostic_suggest = diag::err_undeclared_use_suggest;
1878 // If the original lookup was an unqualified lookup, fake an
1879 // unqualified lookup. This is useful when (for example) the
1880 // original lookup would not have found something because it was a
1882 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1884 if (isa<CXXRecordDecl>(DC)) {
1885 LookupQualifiedName(R, DC);
1888 // Don't give errors about ambiguities in this lookup.
1889 R.suppressDiagnostics();
1891 // During a default argument instantiation the CurContext points
1892 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1893 // function parameter list, hence add an explicit check.
1894 bool isDefaultArgument =
1895 !CodeSynthesisContexts.empty() &&
1896 CodeSynthesisContexts.back().Kind ==
1897 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1898 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1899 bool isInstance = CurMethod &&
1900 CurMethod->isInstance() &&
1901 DC == CurMethod->getParent() && !isDefaultArgument;
1903 // Give a code modification hint to insert 'this->'.
1904 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1905 // Actually quite difficult!
1906 if (getLangOpts().MSVCCompat)
1907 diagnostic = diag::ext_found_via_dependent_bases_lookup;
1909 Diag(R.getNameLoc(), diagnostic) << Name
1910 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1911 CheckCXXThisCapture(R.getNameLoc());
1913 Diag(R.getNameLoc(), diagnostic) << Name;
1916 // Do we really want to note all of these?
1917 for (NamedDecl *D : R)
1918 Diag(D->getLocation(), diag::note_dependent_var_use);
1920 // Return true if we are inside a default argument instantiation
1921 // and the found name refers to an instance member function, otherwise
1922 // the function calling DiagnoseEmptyLookup will try to create an
1923 // implicit member call and this is wrong for default argument.
1924 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1925 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1929 // Tell the callee to try to recover.
1936 // In Microsoft mode, if we are performing lookup from within a friend
1937 // function definition declared at class scope then we must set
1938 // DC to the lexical parent to be able to search into the parent
1940 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1941 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1942 DC->getLexicalParent()->isRecord())
1943 DC = DC->getLexicalParent();
1945 DC = DC->getParent();
1948 // We didn't find anything, so try to correct for a typo.
1949 TypoCorrection Corrected;
1951 SourceLocation TypoLoc = R.getNameLoc();
1952 assert(!ExplicitTemplateArgs &&
1953 "Diagnosing an empty lookup with explicit template args!");
1954 *Out = CorrectTypoDelayed(
1955 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1956 [=](const TypoCorrection &TC) {
1957 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1958 diagnostic, diagnostic_suggest);
1960 nullptr, CTK_ErrorRecovery);
1963 } else if (S && (Corrected =
1964 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1965 &SS, std::move(CCC), CTK_ErrorRecovery))) {
1966 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1967 bool DroppedSpecifier =
1968 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1969 R.setLookupName(Corrected.getCorrection());
1971 bool AcceptableWithRecovery = false;
1972 bool AcceptableWithoutRecovery = false;
1973 NamedDecl *ND = Corrected.getFoundDecl();
1975 if (Corrected.isOverloaded()) {
1976 OverloadCandidateSet OCS(R.getNameLoc(),
1977 OverloadCandidateSet::CSK_Normal);
1978 OverloadCandidateSet::iterator Best;
1979 for (NamedDecl *CD : Corrected) {
1980 if (FunctionTemplateDecl *FTD =
1981 dyn_cast<FunctionTemplateDecl>(CD))
1982 AddTemplateOverloadCandidate(
1983 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1985 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1986 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1987 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1990 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1992 ND = Best->FoundDecl;
1993 Corrected.setCorrectionDecl(ND);
1996 // FIXME: Arbitrarily pick the first declaration for the note.
1997 Corrected.setCorrectionDecl(ND);
2002 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2003 CXXRecordDecl *Record = nullptr;
2004 if (Corrected.getCorrectionSpecifier()) {
2005 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2006 Record = Ty->getAsCXXRecordDecl();
2009 Record = cast<CXXRecordDecl>(
2010 ND->getDeclContext()->getRedeclContext());
2011 R.setNamingClass(Record);
2014 auto *UnderlyingND = ND->getUnderlyingDecl();
2015 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2016 isa<FunctionTemplateDecl>(UnderlyingND);
2017 // FIXME: If we ended up with a typo for a type name or
2018 // Objective-C class name, we're in trouble because the parser
2019 // is in the wrong place to recover. Suggest the typo
2020 // correction, but don't make it a fix-it since we're not going
2021 // to recover well anyway.
2022 AcceptableWithoutRecovery =
2023 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2025 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2026 // because we aren't able to recover.
2027 AcceptableWithoutRecovery = true;
2030 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2031 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2032 ? diag::note_implicit_param_decl
2033 : diag::note_previous_decl;
2035 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2036 PDiag(NoteID), AcceptableWithRecovery);
2038 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2039 << Name << computeDeclContext(SS, false)
2040 << DroppedSpecifier << SS.getRange(),
2041 PDiag(NoteID), AcceptableWithRecovery);
2043 // Tell the callee whether to try to recover.
2044 return !AcceptableWithRecovery;
2049 // Emit a special diagnostic for failed member lookups.
2050 // FIXME: computing the declaration context might fail here (?)
2051 if (!SS.isEmpty()) {
2052 Diag(R.getNameLoc(), diag::err_no_member)
2053 << Name << computeDeclContext(SS, false)
2058 // Give up, we can't recover.
2059 Diag(R.getNameLoc(), diagnostic) << Name;
2063 /// In Microsoft mode, if we are inside a template class whose parent class has
2064 /// dependent base classes, and we can't resolve an unqualified identifier, then
2065 /// assume the identifier is a member of a dependent base class. We can only
2066 /// recover successfully in static methods, instance methods, and other contexts
2067 /// where 'this' is available. This doesn't precisely match MSVC's
2068 /// instantiation model, but it's close enough.
2070 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2071 DeclarationNameInfo &NameInfo,
2072 SourceLocation TemplateKWLoc,
2073 const TemplateArgumentListInfo *TemplateArgs) {
2074 // Only try to recover from lookup into dependent bases in static methods or
2075 // contexts where 'this' is available.
2076 QualType ThisType = S.getCurrentThisType();
2077 const CXXRecordDecl *RD = nullptr;
2078 if (!ThisType.isNull())
2079 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2080 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2081 RD = MD->getParent();
2082 if (!RD || !RD->hasAnyDependentBases())
2085 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2086 // is available, suggest inserting 'this->' as a fixit.
2087 SourceLocation Loc = NameInfo.getLoc();
2088 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2089 DB << NameInfo.getName() << RD;
2091 if (!ThisType.isNull()) {
2092 DB << FixItHint::CreateInsertion(Loc, "this->");
2093 return CXXDependentScopeMemberExpr::Create(
2094 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2095 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2096 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2099 // Synthesize a fake NNS that points to the derived class. This will
2100 // perform name lookup during template instantiation.
2103 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2104 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2105 return DependentScopeDeclRefExpr::Create(
2106 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2111 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2112 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2113 bool HasTrailingLParen, bool IsAddressOfOperand,
2114 std::unique_ptr<CorrectionCandidateCallback> CCC,
2115 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2116 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2117 "cannot be direct & operand and have a trailing lparen");
2121 TemplateArgumentListInfo TemplateArgsBuffer;
2123 // Decompose the UnqualifiedId into the following data.
2124 DeclarationNameInfo NameInfo;
2125 const TemplateArgumentListInfo *TemplateArgs;
2126 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2128 DeclarationName Name = NameInfo.getName();
2129 IdentifierInfo *II = Name.getAsIdentifierInfo();
2130 SourceLocation NameLoc = NameInfo.getLoc();
2132 // C++ [temp.dep.expr]p3:
2133 // An id-expression is type-dependent if it contains:
2134 // -- an identifier that was declared with a dependent type,
2135 // (note: handled after lookup)
2136 // -- a template-id that is dependent,
2137 // (note: handled in BuildTemplateIdExpr)
2138 // -- a conversion-function-id that specifies a dependent type,
2139 // -- a nested-name-specifier that contains a class-name that
2140 // names a dependent type.
2141 // Determine whether this is a member of an unknown specialization;
2142 // we need to handle these differently.
2143 bool DependentID = false;
2144 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2145 Name.getCXXNameType()->isDependentType()) {
2147 } else if (SS.isSet()) {
2148 if (DeclContext *DC = computeDeclContext(SS, false)) {
2149 if (RequireCompleteDeclContext(SS, DC))
2157 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2158 IsAddressOfOperand, TemplateArgs);
2160 // Perform the required lookup.
2161 LookupResult R(*this, NameInfo,
2162 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2163 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2165 // Lookup the template name again to correctly establish the context in
2166 // which it was found. This is really unfortunate as we already did the
2167 // lookup to determine that it was a template name in the first place. If
2168 // this becomes a performance hit, we can work harder to preserve those
2169 // results until we get here but it's likely not worth it.
2170 bool MemberOfUnknownSpecialization;
2171 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2172 MemberOfUnknownSpecialization);
2174 if (MemberOfUnknownSpecialization ||
2175 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2176 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2177 IsAddressOfOperand, TemplateArgs);
2179 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2180 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2182 // If the result might be in a dependent base class, this is a dependent
2184 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2185 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2186 IsAddressOfOperand, TemplateArgs);
2188 // If this reference is in an Objective-C method, then we need to do
2189 // some special Objective-C lookup, too.
2190 if (IvarLookupFollowUp) {
2191 ExprResult E(LookupInObjCMethod(R, S, II, true));
2195 if (Expr *Ex = E.getAs<Expr>())
2200 if (R.isAmbiguous())
2203 // This could be an implicitly declared function reference (legal in C90,
2204 // extension in C99, forbidden in C++).
2205 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2206 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2207 if (D) R.addDecl(D);
2210 // Determine whether this name might be a candidate for
2211 // argument-dependent lookup.
2212 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2214 if (R.empty() && !ADL) {
2215 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2216 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2217 TemplateKWLoc, TemplateArgs))
2221 // Don't diagnose an empty lookup for inline assembly.
2222 if (IsInlineAsmIdentifier)
2225 // If this name wasn't predeclared and if this is not a function
2226 // call, diagnose the problem.
2227 TypoExpr *TE = nullptr;
2228 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2229 II, SS.isValid() ? SS.getScopeRep() : nullptr);
2230 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2231 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2232 "Typo correction callback misconfigured");
2234 // Make sure the callback knows what the typo being diagnosed is.
2235 CCC->setTypoName(II);
2237 CCC->setTypoNNS(SS.getScopeRep());
2239 if (DiagnoseEmptyLookup(S, SS, R,
2240 CCC ? std::move(CCC) : std::move(DefaultValidator),
2241 nullptr, None, &TE)) {
2242 if (TE && KeywordReplacement) {
2243 auto &State = getTypoExprState(TE);
2244 auto BestTC = State.Consumer->getNextCorrection();
2245 if (BestTC.isKeyword()) {
2246 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2247 if (State.DiagHandler)
2248 State.DiagHandler(BestTC);
2249 KeywordReplacement->startToken();
2250 KeywordReplacement->setKind(II->getTokenID());
2251 KeywordReplacement->setIdentifierInfo(II);
2252 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2253 // Clean up the state associated with the TypoExpr, since it has
2254 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2255 clearDelayedTypo(TE);
2256 // Signal that a correction to a keyword was performed by returning a
2257 // valid-but-null ExprResult.
2258 return (Expr*)nullptr;
2260 State.Consumer->resetCorrectionStream();
2262 return TE ? TE : ExprError();
2265 assert(!R.empty() &&
2266 "DiagnoseEmptyLookup returned false but added no results");
2268 // If we found an Objective-C instance variable, let
2269 // LookupInObjCMethod build the appropriate expression to
2270 // reference the ivar.
2271 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2273 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2274 // In a hopelessly buggy code, Objective-C instance variable
2275 // lookup fails and no expression will be built to reference it.
2276 if (!E.isInvalid() && !E.get())
2282 // This is guaranteed from this point on.
2283 assert(!R.empty() || ADL);
2285 // Check whether this might be a C++ implicit instance member access.
2286 // C++ [class.mfct.non-static]p3:
2287 // When an id-expression that is not part of a class member access
2288 // syntax and not used to form a pointer to member is used in the
2289 // body of a non-static member function of class X, if name lookup
2290 // resolves the name in the id-expression to a non-static non-type
2291 // member of some class C, the id-expression is transformed into a
2292 // class member access expression using (*this) as the
2293 // postfix-expression to the left of the . operator.
2295 // But we don't actually need to do this for '&' operands if R
2296 // resolved to a function or overloaded function set, because the
2297 // expression is ill-formed if it actually works out to be a
2298 // non-static member function:
2300 // C++ [expr.ref]p4:
2301 // Otherwise, if E1.E2 refers to a non-static member function. . .
2302 // [t]he expression can be used only as the left-hand operand of a
2303 // member function call.
2305 // There are other safeguards against such uses, but it's important
2306 // to get this right here so that we don't end up making a
2307 // spuriously dependent expression if we're inside a dependent
2309 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2310 bool MightBeImplicitMember;
2311 if (!IsAddressOfOperand)
2312 MightBeImplicitMember = true;
2313 else if (!SS.isEmpty())
2314 MightBeImplicitMember = false;
2315 else if (R.isOverloadedResult())
2316 MightBeImplicitMember = false;
2317 else if (R.isUnresolvableResult())
2318 MightBeImplicitMember = true;
2320 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2321 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2322 isa<MSPropertyDecl>(R.getFoundDecl());
2324 if (MightBeImplicitMember)
2325 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2326 R, TemplateArgs, S);
2329 if (TemplateArgs || TemplateKWLoc.isValid()) {
2331 // In C++1y, if this is a variable template id, then check it
2332 // in BuildTemplateIdExpr().
2333 // The single lookup result must be a variable template declaration.
2334 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2335 Id.TemplateId->Kind == TNK_Var_template) {
2336 assert(R.getAsSingle<VarTemplateDecl>() &&
2337 "There should only be one declaration found.");
2340 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2343 return BuildDeclarationNameExpr(SS, R, ADL);
2346 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2347 /// declaration name, generally during template instantiation.
2348 /// There's a large number of things which don't need to be done along
2350 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2351 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2352 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2353 DeclContext *DC = computeDeclContext(SS, false);
2355 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2356 NameInfo, /*TemplateArgs=*/nullptr);
2358 if (RequireCompleteDeclContext(SS, DC))
2361 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2362 LookupQualifiedName(R, DC);
2364 if (R.isAmbiguous())
2367 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2368 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2369 NameInfo, /*TemplateArgs=*/nullptr);
2372 Diag(NameInfo.getLoc(), diag::err_no_member)
2373 << NameInfo.getName() << DC << SS.getRange();
2377 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2378 // Diagnose a missing typename if this resolved unambiguously to a type in
2379 // a dependent context. If we can recover with a type, downgrade this to
2380 // a warning in Microsoft compatibility mode.
2381 unsigned DiagID = diag::err_typename_missing;
2382 if (RecoveryTSI && getLangOpts().MSVCCompat)
2383 DiagID = diag::ext_typename_missing;
2384 SourceLocation Loc = SS.getBeginLoc();
2385 auto D = Diag(Loc, DiagID);
2386 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2387 << SourceRange(Loc, NameInfo.getEndLoc());
2389 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2394 // Only issue the fixit if we're prepared to recover.
2395 D << FixItHint::CreateInsertion(Loc, "typename ");
2397 // Recover by pretending this was an elaborated type.
2398 QualType Ty = Context.getTypeDeclType(TD);
2400 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2402 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2403 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2404 QTL.setElaboratedKeywordLoc(SourceLocation());
2405 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2407 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2412 // Defend against this resolving to an implicit member access. We usually
2413 // won't get here if this might be a legitimate a class member (we end up in
2414 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2415 // a pointer-to-member or in an unevaluated context in C++11.
2416 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2417 return BuildPossibleImplicitMemberExpr(SS,
2418 /*TemplateKWLoc=*/SourceLocation(),
2419 R, /*TemplateArgs=*/nullptr, S);
2421 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2424 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2425 /// detected that we're currently inside an ObjC method. Perform some
2426 /// additional lookup.
2428 /// Ideally, most of this would be done by lookup, but there's
2429 /// actually quite a lot of extra work involved.
2431 /// Returns a null sentinel to indicate trivial success.
2433 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2434 IdentifierInfo *II, bool AllowBuiltinCreation) {
2435 SourceLocation Loc = Lookup.getNameLoc();
2436 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2438 // Check for error condition which is already reported.
2442 // There are two cases to handle here. 1) scoped lookup could have failed,
2443 // in which case we should look for an ivar. 2) scoped lookup could have
2444 // found a decl, but that decl is outside the current instance method (i.e.
2445 // a global variable). In these two cases, we do a lookup for an ivar with
2446 // this name, if the lookup sucedes, we replace it our current decl.
2448 // If we're in a class method, we don't normally want to look for
2449 // ivars. But if we don't find anything else, and there's an
2450 // ivar, that's an error.
2451 bool IsClassMethod = CurMethod->isClassMethod();
2455 LookForIvars = true;
2456 else if (IsClassMethod)
2457 LookForIvars = false;
2459 LookForIvars = (Lookup.isSingleResult() &&
2460 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2461 ObjCInterfaceDecl *IFace = nullptr;
2463 IFace = CurMethod->getClassInterface();
2464 ObjCInterfaceDecl *ClassDeclared;
2465 ObjCIvarDecl *IV = nullptr;
2466 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2467 // Diagnose using an ivar in a class method.
2469 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2470 << IV->getDeclName());
2472 // If we're referencing an invalid decl, just return this as a silent
2473 // error node. The error diagnostic was already emitted on the decl.
2474 if (IV->isInvalidDecl())
2477 // Check if referencing a field with __attribute__((deprecated)).
2478 if (DiagnoseUseOfDecl(IV, Loc))
2481 // Diagnose the use of an ivar outside of the declaring class.
2482 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2483 !declaresSameEntity(ClassDeclared, IFace) &&
2484 !getLangOpts().DebuggerSupport)
2485 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2487 // FIXME: This should use a new expr for a direct reference, don't
2488 // turn this into Self->ivar, just return a BareIVarExpr or something.
2489 IdentifierInfo &II = Context.Idents.get("self");
2490 UnqualifiedId SelfName;
2491 SelfName.setIdentifier(&II, SourceLocation());
2492 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2493 CXXScopeSpec SelfScopeSpec;
2494 SourceLocation TemplateKWLoc;
2495 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2496 SelfName, false, false);
2497 if (SelfExpr.isInvalid())
2500 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2501 if (SelfExpr.isInvalid())
2504 MarkAnyDeclReferenced(Loc, IV, true);
2506 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2507 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2508 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2509 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2511 ObjCIvarRefExpr *Result = new (Context)
2512 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2513 IV->getLocation(), SelfExpr.get(), true, true);
2515 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2516 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2517 recordUseOfEvaluatedWeak(Result);
2519 if (getLangOpts().ObjCAutoRefCount) {
2520 if (CurContext->isClosure())
2521 Diag(Loc, diag::warn_implicitly_retains_self)
2522 << FixItHint::CreateInsertion(Loc, "self->");
2527 } else if (CurMethod->isInstanceMethod()) {
2528 // We should warn if a local variable hides an ivar.
2529 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2530 ObjCInterfaceDecl *ClassDeclared;
2531 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2532 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2533 declaresSameEntity(IFace, ClassDeclared))
2534 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2537 } else if (Lookup.isSingleResult() &&
2538 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2539 // If accessing a stand-alone ivar in a class method, this is an error.
2540 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2541 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2542 << IV->getDeclName());
2545 if (Lookup.empty() && II && AllowBuiltinCreation) {
2546 // FIXME. Consolidate this with similar code in LookupName.
2547 if (unsigned BuiltinID = II->getBuiltinID()) {
2548 if (!(getLangOpts().CPlusPlus &&
2549 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2550 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2551 S, Lookup.isForRedeclaration(),
2552 Lookup.getNameLoc());
2553 if (D) Lookup.addDecl(D);
2557 // Sentinel value saying that we didn't do anything special.
2558 return ExprResult((Expr *)nullptr);
2561 /// \brief Cast a base object to a member's actual type.
2563 /// Logically this happens in three phases:
2565 /// * First we cast from the base type to the naming class.
2566 /// The naming class is the class into which we were looking
2567 /// when we found the member; it's the qualifier type if a
2568 /// qualifier was provided, and otherwise it's the base type.
2570 /// * Next we cast from the naming class to the declaring class.
2571 /// If the member we found was brought into a class's scope by
2572 /// a using declaration, this is that class; otherwise it's
2573 /// the class declaring the member.
2575 /// * Finally we cast from the declaring class to the "true"
2576 /// declaring class of the member. This conversion does not
2577 /// obey access control.
2579 Sema::PerformObjectMemberConversion(Expr *From,
2580 NestedNameSpecifier *Qualifier,
2581 NamedDecl *FoundDecl,
2582 NamedDecl *Member) {
2583 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2587 QualType DestRecordType;
2589 QualType FromRecordType;
2590 QualType FromType = From->getType();
2591 bool PointerConversions = false;
2592 if (isa<FieldDecl>(Member)) {
2593 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2595 if (FromType->getAs<PointerType>()) {
2596 DestType = Context.getPointerType(DestRecordType);
2597 FromRecordType = FromType->getPointeeType();
2598 PointerConversions = true;
2600 DestType = DestRecordType;
2601 FromRecordType = FromType;
2603 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2604 if (Method->isStatic())
2607 DestType = Method->getThisType(Context);
2608 DestRecordType = DestType->getPointeeType();
2610 if (FromType->getAs<PointerType>()) {
2611 FromRecordType = FromType->getPointeeType();
2612 PointerConversions = true;
2614 FromRecordType = FromType;
2615 DestType = DestRecordType;
2618 // No conversion necessary.
2622 if (DestType->isDependentType() || FromType->isDependentType())
2625 // If the unqualified types are the same, no conversion is necessary.
2626 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2629 SourceRange FromRange = From->getSourceRange();
2630 SourceLocation FromLoc = FromRange.getBegin();
2632 ExprValueKind VK = From->getValueKind();
2634 // C++ [class.member.lookup]p8:
2635 // [...] Ambiguities can often be resolved by qualifying a name with its
2638 // If the member was a qualified name and the qualified referred to a
2639 // specific base subobject type, we'll cast to that intermediate type
2640 // first and then to the object in which the member is declared. That allows
2641 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2643 // class Base { public: int x; };
2644 // class Derived1 : public Base { };
2645 // class Derived2 : public Base { };
2646 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2648 // void VeryDerived::f() {
2649 // x = 17; // error: ambiguous base subobjects
2650 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2652 if (Qualifier && Qualifier->getAsType()) {
2653 QualType QType = QualType(Qualifier->getAsType(), 0);
2654 assert(QType->isRecordType() && "lookup done with non-record type");
2656 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2658 // In C++98, the qualifier type doesn't actually have to be a base
2659 // type of the object type, in which case we just ignore it.
2660 // Otherwise build the appropriate casts.
2661 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2662 CXXCastPath BasePath;
2663 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2664 FromLoc, FromRange, &BasePath))
2667 if (PointerConversions)
2668 QType = Context.getPointerType(QType);
2669 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2670 VK, &BasePath).get();
2673 FromRecordType = QRecordType;
2675 // If the qualifier type was the same as the destination type,
2677 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2682 bool IgnoreAccess = false;
2684 // If we actually found the member through a using declaration, cast
2685 // down to the using declaration's type.
2687 // Pointer equality is fine here because only one declaration of a
2688 // class ever has member declarations.
2689 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2690 assert(isa<UsingShadowDecl>(FoundDecl));
2691 QualType URecordType = Context.getTypeDeclType(
2692 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2694 // We only need to do this if the naming-class to declaring-class
2695 // conversion is non-trivial.
2696 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2697 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2698 CXXCastPath BasePath;
2699 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2700 FromLoc, FromRange, &BasePath))
2703 QualType UType = URecordType;
2704 if (PointerConversions)
2705 UType = Context.getPointerType(UType);
2706 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2707 VK, &BasePath).get();
2709 FromRecordType = URecordType;
2712 // We don't do access control for the conversion from the
2713 // declaring class to the true declaring class.
2714 IgnoreAccess = true;
2717 CXXCastPath BasePath;
2718 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2719 FromLoc, FromRange, &BasePath,
2723 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2727 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2728 const LookupResult &R,
2729 bool HasTrailingLParen) {
2730 // Only when used directly as the postfix-expression of a call.
2731 if (!HasTrailingLParen)
2734 // Never if a scope specifier was provided.
2738 // Only in C++ or ObjC++.
2739 if (!getLangOpts().CPlusPlus)
2742 // Turn off ADL when we find certain kinds of declarations during
2744 for (NamedDecl *D : R) {
2745 // C++0x [basic.lookup.argdep]p3:
2746 // -- a declaration of a class member
2747 // Since using decls preserve this property, we check this on the
2749 if (D->isCXXClassMember())
2752 // C++0x [basic.lookup.argdep]p3:
2753 // -- a block-scope function declaration that is not a
2754 // using-declaration
2755 // NOTE: we also trigger this for function templates (in fact, we
2756 // don't check the decl type at all, since all other decl types
2757 // turn off ADL anyway).
2758 if (isa<UsingShadowDecl>(D))
2759 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2760 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2763 // C++0x [basic.lookup.argdep]p3:
2764 // -- a declaration that is neither a function or a function
2766 // And also for builtin functions.
2767 if (isa<FunctionDecl>(D)) {
2768 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2770 // But also builtin functions.
2771 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2773 } else if (!isa<FunctionTemplateDecl>(D))
2781 /// Diagnoses obvious problems with the use of the given declaration
2782 /// as an expression. This is only actually called for lookups that
2783 /// were not overloaded, and it doesn't promise that the declaration
2784 /// will in fact be used.
2785 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2786 if (D->isInvalidDecl())
2789 if (isa<TypedefNameDecl>(D)) {
2790 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2794 if (isa<ObjCInterfaceDecl>(D)) {
2795 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2799 if (isa<NamespaceDecl>(D)) {
2800 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2807 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2808 LookupResult &R, bool NeedsADL,
2809 bool AcceptInvalidDecl) {
2810 // If this is a single, fully-resolved result and we don't need ADL,
2811 // just build an ordinary singleton decl ref.
2812 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2813 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2814 R.getRepresentativeDecl(), nullptr,
2817 // We only need to check the declaration if there's exactly one
2818 // result, because in the overloaded case the results can only be
2819 // functions and function templates.
2820 if (R.isSingleResult() &&
2821 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2824 // Otherwise, just build an unresolved lookup expression. Suppress
2825 // any lookup-related diagnostics; we'll hash these out later, when
2826 // we've picked a target.
2827 R.suppressDiagnostics();
2829 UnresolvedLookupExpr *ULE
2830 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2831 SS.getWithLocInContext(Context),
2832 R.getLookupNameInfo(),
2833 NeedsADL, R.isOverloadedResult(),
2834 R.begin(), R.end());
2840 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2841 ValueDecl *var, DeclContext *DC);
2843 /// \brief Complete semantic analysis for a reference to the given declaration.
2844 ExprResult Sema::BuildDeclarationNameExpr(
2845 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2846 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2847 bool AcceptInvalidDecl) {
2848 assert(D && "Cannot refer to a NULL declaration");
2849 assert(!isa<FunctionTemplateDecl>(D) &&
2850 "Cannot refer unambiguously to a function template");
2852 SourceLocation Loc = NameInfo.getLoc();
2853 if (CheckDeclInExpr(*this, Loc, D))
2856 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2857 // Specifically diagnose references to class templates that are missing
2858 // a template argument list.
2859 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2860 << Template << SS.getRange();
2861 Diag(Template->getLocation(), diag::note_template_decl_here);
2865 // Make sure that we're referring to a value.
2866 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2868 Diag(Loc, diag::err_ref_non_value)
2869 << D << SS.getRange();
2870 Diag(D->getLocation(), diag::note_declared_at);
2874 // Check whether this declaration can be used. Note that we suppress
2875 // this check when we're going to perform argument-dependent lookup
2876 // on this function name, because this might not be the function
2877 // that overload resolution actually selects.
2878 if (DiagnoseUseOfDecl(VD, Loc))
2881 // Only create DeclRefExpr's for valid Decl's.
2882 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2885 // Handle members of anonymous structs and unions. If we got here,
2886 // and the reference is to a class member indirect field, then this
2887 // must be the subject of a pointer-to-member expression.
2888 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2889 if (!indirectField->isCXXClassMember())
2890 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2894 QualType type = VD->getType();
2895 if (auto *FPT = type->getAs<FunctionProtoType>()) {
2896 // C++ [except.spec]p17:
2897 // An exception-specification is considered to be needed when:
2898 // - in an expression, the function is the unique lookup result or
2899 // the selected member of a set of overloaded functions.
2900 ResolveExceptionSpec(Loc, FPT);
2901 type = VD->getType();
2903 ExprValueKind valueKind = VK_RValue;
2905 switch (D->getKind()) {
2906 // Ignore all the non-ValueDecl kinds.
2907 #define ABSTRACT_DECL(kind)
2908 #define VALUE(type, base)
2909 #define DECL(type, base) \
2911 #include "clang/AST/DeclNodes.inc"
2912 llvm_unreachable("invalid value decl kind");
2914 // These shouldn't make it here.
2915 case Decl::ObjCAtDefsField:
2916 case Decl::ObjCIvar:
2917 llvm_unreachable("forming non-member reference to ivar?");
2919 // Enum constants are always r-values and never references.
2920 // Unresolved using declarations are dependent.
2921 case Decl::EnumConstant:
2922 case Decl::UnresolvedUsingValue:
2923 case Decl::OMPDeclareReduction:
2924 valueKind = VK_RValue;
2927 // Fields and indirect fields that got here must be for
2928 // pointer-to-member expressions; we just call them l-values for
2929 // internal consistency, because this subexpression doesn't really
2930 // exist in the high-level semantics.
2932 case Decl::IndirectField:
2933 assert(getLangOpts().CPlusPlus &&
2934 "building reference to field in C?");
2936 // These can't have reference type in well-formed programs, but
2937 // for internal consistency we do this anyway.
2938 type = type.getNonReferenceType();
2939 valueKind = VK_LValue;
2942 // Non-type template parameters are either l-values or r-values
2943 // depending on the type.
2944 case Decl::NonTypeTemplateParm: {
2945 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2946 type = reftype->getPointeeType();
2947 valueKind = VK_LValue; // even if the parameter is an r-value reference
2951 // For non-references, we need to strip qualifiers just in case
2952 // the template parameter was declared as 'const int' or whatever.
2953 valueKind = VK_RValue;
2954 type = type.getUnqualifiedType();
2959 case Decl::VarTemplateSpecialization:
2960 case Decl::VarTemplatePartialSpecialization:
2961 case Decl::Decomposition:
2962 case Decl::OMPCapturedExpr:
2963 // In C, "extern void blah;" is valid and is an r-value.
2964 if (!getLangOpts().CPlusPlus &&
2965 !type.hasQualifiers() &&
2966 type->isVoidType()) {
2967 valueKind = VK_RValue;
2972 case Decl::ImplicitParam:
2973 case Decl::ParmVar: {
2974 // These are always l-values.
2975 valueKind = VK_LValue;
2976 type = type.getNonReferenceType();
2978 // FIXME: Does the addition of const really only apply in
2979 // potentially-evaluated contexts? Since the variable isn't actually
2980 // captured in an unevaluated context, it seems that the answer is no.
2981 if (!isUnevaluatedContext()) {
2982 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2983 if (!CapturedType.isNull())
2984 type = CapturedType;
2990 case Decl::Binding: {
2991 // These are always lvalues.
2992 valueKind = VK_LValue;
2993 type = type.getNonReferenceType();
2994 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2995 // decides how that's supposed to work.
2996 auto *BD = cast<BindingDecl>(VD);
2997 if (BD->getDeclContext()->isFunctionOrMethod() &&
2998 BD->getDeclContext() != CurContext)
2999 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3003 case Decl::Function: {
3004 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3005 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3006 type = Context.BuiltinFnTy;
3007 valueKind = VK_RValue;
3012 const FunctionType *fty = type->castAs<FunctionType>();
3014 // If we're referring to a function with an __unknown_anytype
3015 // result type, make the entire expression __unknown_anytype.
3016 if (fty->getReturnType() == Context.UnknownAnyTy) {
3017 type = Context.UnknownAnyTy;
3018 valueKind = VK_RValue;
3022 // Functions are l-values in C++.
3023 if (getLangOpts().CPlusPlus) {
3024 valueKind = VK_LValue;
3028 // C99 DR 316 says that, if a function type comes from a
3029 // function definition (without a prototype), that type is only
3030 // used for checking compatibility. Therefore, when referencing
3031 // the function, we pretend that we don't have the full function
3033 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3034 isa<FunctionProtoType>(fty))
3035 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3038 // Functions are r-values in C.
3039 valueKind = VK_RValue;
3043 case Decl::CXXDeductionGuide:
3044 llvm_unreachable("building reference to deduction guide");
3046 case Decl::MSProperty:
3047 valueKind = VK_LValue;
3050 case Decl::CXXMethod:
3051 // If we're referring to a method with an __unknown_anytype
3052 // result type, make the entire expression __unknown_anytype.
3053 // This should only be possible with a type written directly.
3054 if (const FunctionProtoType *proto
3055 = dyn_cast<FunctionProtoType>(VD->getType()))
3056 if (proto->getReturnType() == Context.UnknownAnyTy) {
3057 type = Context.UnknownAnyTy;
3058 valueKind = VK_RValue;
3062 // C++ methods are l-values if static, r-values if non-static.
3063 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3064 valueKind = VK_LValue;
3069 case Decl::CXXConversion:
3070 case Decl::CXXDestructor:
3071 case Decl::CXXConstructor:
3072 valueKind = VK_RValue;
3076 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3081 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3082 SmallString<32> &Target) {
3083 Target.resize(CharByteWidth * (Source.size() + 1));
3084 char *ResultPtr = &Target[0];
3085 const llvm::UTF8 *ErrorPtr;
3087 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3090 Target.resize(ResultPtr - &Target[0]);
3093 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3094 PredefinedExpr::IdentType IT) {
3095 // Pick the current block, lambda, captured statement or function.
3096 Decl *currentDecl = nullptr;
3097 if (const BlockScopeInfo *BSI = getCurBlock())
3098 currentDecl = BSI->TheDecl;
3099 else if (const LambdaScopeInfo *LSI = getCurLambda())
3100 currentDecl = LSI->CallOperator;
3101 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3102 currentDecl = CSI->TheCapturedDecl;
3104 currentDecl = getCurFunctionOrMethodDecl();
3107 Diag(Loc, diag::ext_predef_outside_function);
3108 currentDecl = Context.getTranslationUnitDecl();
3112 StringLiteral *SL = nullptr;
3113 if (cast<DeclContext>(currentDecl)->isDependentContext())
3114 ResTy = Context.DependentTy;
3116 // Pre-defined identifiers are of type char[x], where x is the length of
3118 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3119 unsigned Length = Str.length();
3121 llvm::APInt LengthI(32, Length + 1);
3122 if (IT == PredefinedExpr::LFunction) {
3123 ResTy = Context.WideCharTy.withConst();
3124 SmallString<32> RawChars;
3125 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3127 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3128 /*IndexTypeQuals*/ 0);
3129 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3130 /*Pascal*/ false, ResTy, Loc);
3132 ResTy = Context.CharTy.withConst();
3133 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3134 /*IndexTypeQuals*/ 0);
3135 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3136 /*Pascal*/ false, ResTy, Loc);
3140 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3143 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3144 PredefinedExpr::IdentType IT;
3147 default: llvm_unreachable("Unknown simple primary expr!");
3148 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3149 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3150 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3151 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3152 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3153 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3156 return BuildPredefinedExpr(Loc, IT);
3159 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3160 SmallString<16> CharBuffer;
3161 bool Invalid = false;
3162 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3166 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3168 if (Literal.hadError())
3172 if (Literal.isWide())
3173 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3174 else if (Literal.isUTF16())
3175 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3176 else if (Literal.isUTF32())
3177 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3178 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3179 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3181 Ty = Context.CharTy; // 'x' -> char in C++
3183 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3184 if (Literal.isWide())
3185 Kind = CharacterLiteral::Wide;
3186 else if (Literal.isUTF16())
3187 Kind = CharacterLiteral::UTF16;
3188 else if (Literal.isUTF32())
3189 Kind = CharacterLiteral::UTF32;
3190 else if (Literal.isUTF8())
3191 Kind = CharacterLiteral::UTF8;
3193 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3196 if (Literal.getUDSuffix().empty())
3199 // We're building a user-defined literal.
3200 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3201 SourceLocation UDSuffixLoc =
3202 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3204 // Make sure we're allowed user-defined literals here.
3206 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3208 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3209 // operator "" X (ch)
3210 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3211 Lit, Tok.getLocation());
3214 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3215 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3216 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3217 Context.IntTy, Loc);
3220 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3221 QualType Ty, SourceLocation Loc) {
3222 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3224 using llvm::APFloat;
3225 APFloat Val(Format);
3227 APFloat::opStatus result = Literal.GetFloatValue(Val);
3229 // Overflow is always an error, but underflow is only an error if
3230 // we underflowed to zero (APFloat reports denormals as underflow).
3231 if ((result & APFloat::opOverflow) ||
3232 ((result & APFloat::opUnderflow) && Val.isZero())) {
3233 unsigned diagnostic;
3234 SmallString<20> buffer;
3235 if (result & APFloat::opOverflow) {
3236 diagnostic = diag::warn_float_overflow;
3237 APFloat::getLargest(Format).toString(buffer);
3239 diagnostic = diag::warn_float_underflow;
3240 APFloat::getSmallest(Format).toString(buffer);
3243 S.Diag(Loc, diagnostic)
3245 << StringRef(buffer.data(), buffer.size());
3248 bool isExact = (result == APFloat::opOK);
3249 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3252 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3253 assert(E && "Invalid expression");
3255 if (E->isValueDependent())
3258 QualType QT = E->getType();
3259 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3260 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3264 llvm::APSInt ValueAPS;
3265 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3270 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3271 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3272 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3273 << ValueAPS.toString(10) << ValueIsPositive;
3280 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3281 // Fast path for a single digit (which is quite common). A single digit
3282 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3283 if (Tok.getLength() == 1) {
3284 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3285 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3288 SmallString<128> SpellingBuffer;
3289 // NumericLiteralParser wants to overread by one character. Add padding to
3290 // the buffer in case the token is copied to the buffer. If getSpelling()
3291 // returns a StringRef to the memory buffer, it should have a null char at
3292 // the EOF, so it is also safe.
3293 SpellingBuffer.resize(Tok.getLength() + 1);
3295 // Get the spelling of the token, which eliminates trigraphs, etc.
3296 bool Invalid = false;
3297 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3301 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3302 if (Literal.hadError)
3305 if (Literal.hasUDSuffix()) {
3306 // We're building a user-defined literal.
3307 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3308 SourceLocation UDSuffixLoc =
3309 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3311 // Make sure we're allowed user-defined literals here.
3313 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3316 if (Literal.isFloatingLiteral()) {
3317 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3318 // long double, the literal is treated as a call of the form
3319 // operator "" X (f L)
3320 CookedTy = Context.LongDoubleTy;
3322 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3323 // unsigned long long, the literal is treated as a call of the form
3324 // operator "" X (n ULL)
3325 CookedTy = Context.UnsignedLongLongTy;
3328 DeclarationName OpName =
3329 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3330 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3331 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3333 SourceLocation TokLoc = Tok.getLocation();
3335 // Perform literal operator lookup to determine if we're building a raw
3336 // literal or a cooked one.
3337 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3338 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3339 /*AllowRaw*/true, /*AllowTemplate*/true,
3340 /*AllowStringTemplate*/false)) {
3346 if (Literal.isFloatingLiteral()) {
3347 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3349 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3350 if (Literal.GetIntegerValue(ResultVal))
3351 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3352 << /* Unsigned */ 1;
3353 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3356 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3360 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3361 // literal is treated as a call of the form
3362 // operator "" X ("n")
3363 unsigned Length = Literal.getUDSuffixOffset();
3364 QualType StrTy = Context.getConstantArrayType(
3365 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3366 ArrayType::Normal, 0);
3367 Expr *Lit = StringLiteral::Create(
3368 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3369 /*Pascal*/false, StrTy, &TokLoc, 1);
3370 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3373 case LOLR_Template: {
3374 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3375 // template), L is treated as a call fo the form
3376 // operator "" X <'c1', 'c2', ... 'ck'>()
3377 // where n is the source character sequence c1 c2 ... ck.
3378 TemplateArgumentListInfo ExplicitArgs;
3379 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3380 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3381 llvm::APSInt Value(CharBits, CharIsUnsigned);
3382 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3383 Value = TokSpelling[I];
3384 TemplateArgument Arg(Context, Value, Context.CharTy);
3385 TemplateArgumentLocInfo ArgInfo;
3386 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3388 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3391 case LOLR_StringTemplate:
3392 llvm_unreachable("unexpected literal operator lookup result");
3398 if (Literal.isFloatingLiteral()) {
3400 if (Literal.isHalf){
3401 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3402 Ty = Context.HalfTy;
3404 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3407 } else if (Literal.isFloat)
3408 Ty = Context.FloatTy;
3409 else if (Literal.isLong)
3410 Ty = Context.LongDoubleTy;
3411 else if (Literal.isFloat128)
3412 Ty = Context.Float128Ty;
3414 Ty = Context.DoubleTy;
3416 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3418 if (Ty == Context.DoubleTy) {
3419 if (getLangOpts().SinglePrecisionConstants) {
3420 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3421 if (BTy->getKind() != BuiltinType::Float) {
3422 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3424 } else if (getLangOpts().OpenCL &&
3425 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3426 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3427 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3428 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3431 } else if (!Literal.isIntegerLiteral()) {
3436 // 'long long' is a C99 or C++11 feature.
3437 if (!getLangOpts().C99 && Literal.isLongLong) {
3438 if (getLangOpts().CPlusPlus)
3439 Diag(Tok.getLocation(),
3440 getLangOpts().CPlusPlus11 ?
3441 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3443 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3446 // Get the value in the widest-possible width.
3447 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3448 llvm::APInt ResultVal(MaxWidth, 0);
3450 if (Literal.GetIntegerValue(ResultVal)) {
3451 // If this value didn't fit into uintmax_t, error and force to ull.
3452 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3453 << /* Unsigned */ 1;
3454 Ty = Context.UnsignedLongLongTy;
3455 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3456 "long long is not intmax_t?");
3458 // If this value fits into a ULL, try to figure out what else it fits into
3459 // according to the rules of C99 6.4.4.1p5.
3461 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3462 // be an unsigned int.
3463 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3465 // Check from smallest to largest, picking the smallest type we can.
3468 // Microsoft specific integer suffixes are explicitly sized.
3469 if (Literal.MicrosoftInteger) {
3470 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3472 Ty = Context.CharTy;
3474 Width = Literal.MicrosoftInteger;
3475 Ty = Context.getIntTypeForBitwidth(Width,
3476 /*Signed=*/!Literal.isUnsigned);
3480 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3481 // Are int/unsigned possibilities?
3482 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3484 // Does it fit in a unsigned int?
3485 if (ResultVal.isIntN(IntSize)) {
3486 // Does it fit in a signed int?
3487 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3489 else if (AllowUnsigned)
3490 Ty = Context.UnsignedIntTy;
3495 // Are long/unsigned long possibilities?
3496 if (Ty.isNull() && !Literal.isLongLong) {
3497 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3499 // Does it fit in a unsigned long?
3500 if (ResultVal.isIntN(LongSize)) {
3501 // Does it fit in a signed long?
3502 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3503 Ty = Context.LongTy;
3504 else if (AllowUnsigned)
3505 Ty = Context.UnsignedLongTy;
3506 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3508 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3509 const unsigned LongLongSize =
3510 Context.getTargetInfo().getLongLongWidth();
3511 Diag(Tok.getLocation(),
3512 getLangOpts().CPlusPlus
3514 ? diag::warn_old_implicitly_unsigned_long_cxx
3515 : /*C++98 UB*/ diag::
3516 ext_old_implicitly_unsigned_long_cxx
3517 : diag::warn_old_implicitly_unsigned_long)
3518 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3519 : /*will be ill-formed*/ 1);
3520 Ty = Context.UnsignedLongTy;
3526 // Check long long if needed.
3528 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3530 // Does it fit in a unsigned long long?
3531 if (ResultVal.isIntN(LongLongSize)) {
3532 // Does it fit in a signed long long?
3533 // To be compatible with MSVC, hex integer literals ending with the
3534 // LL or i64 suffix are always signed in Microsoft mode.
3535 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3536 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3537 Ty = Context.LongLongTy;
3538 else if (AllowUnsigned)
3539 Ty = Context.UnsignedLongLongTy;
3540 Width = LongLongSize;
3544 // If we still couldn't decide a type, we probably have something that
3545 // does not fit in a signed long long, but has no U suffix.
3547 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3548 Ty = Context.UnsignedLongLongTy;
3549 Width = Context.getTargetInfo().getLongLongWidth();
3552 if (ResultVal.getBitWidth() != Width)
3553 ResultVal = ResultVal.trunc(Width);
3555 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3558 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3559 if (Literal.isImaginary)
3560 Res = new (Context) ImaginaryLiteral(Res,
3561 Context.getComplexType(Res->getType()));
3566 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3567 assert(E && "ActOnParenExpr() missing expr");
3568 return new (Context) ParenExpr(L, R, E);
3571 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3573 SourceRange ArgRange) {
3574 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3575 // scalar or vector data type argument..."
3576 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3577 // type (C99 6.2.5p18) or void.
3578 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3579 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3584 assert((T->isVoidType() || !T->isIncompleteType()) &&
3585 "Scalar types should always be complete");
3589 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3591 SourceRange ArgRange,
3592 UnaryExprOrTypeTrait TraitKind) {
3593 // Invalid types must be hard errors for SFINAE in C++.
3594 if (S.LangOpts.CPlusPlus)
3598 if (T->isFunctionType() &&
3599 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3600 // sizeof(function)/alignof(function) is allowed as an extension.
3601 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3602 << TraitKind << ArgRange;
3606 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3607 // this is an error (OpenCL v1.1 s6.3.k)
3608 if (T->isVoidType()) {
3609 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3610 : diag::ext_sizeof_alignof_void_type;
3611 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3618 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3620 SourceRange ArgRange,
3621 UnaryExprOrTypeTrait TraitKind) {
3622 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3623 // runtime doesn't allow it.
3624 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3625 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3626 << T << (TraitKind == UETT_SizeOf)
3634 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3635 /// pointer type is equal to T) and emit a warning if it is.
3636 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3638 // Don't warn if the operation changed the type.
3639 if (T != E->getType())
3642 // Now look for array decays.
3643 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3644 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3647 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3649 << ICE->getSubExpr()->getType();
3652 /// \brief Check the constraints on expression operands to unary type expression
3653 /// and type traits.
3655 /// Completes any types necessary and validates the constraints on the operand
3656 /// expression. The logic mostly mirrors the type-based overload, but may modify
3657 /// the expression as it completes the type for that expression through template
3658 /// instantiation, etc.
3659 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3660 UnaryExprOrTypeTrait ExprKind) {
3661 QualType ExprTy = E->getType();
3662 assert(!ExprTy->isReferenceType());
3664 if (ExprKind == UETT_VecStep)
3665 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3666 E->getSourceRange());
3668 // Whitelist some types as extensions
3669 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3670 E->getSourceRange(), ExprKind))
3673 // 'alignof' applied to an expression only requires the base element type of
3674 // the expression to be complete. 'sizeof' requires the expression's type to
3675 // be complete (and will attempt to complete it if it's an array of unknown
3677 if (ExprKind == UETT_AlignOf) {
3678 if (RequireCompleteType(E->getExprLoc(),
3679 Context.getBaseElementType(E->getType()),
3680 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3681 E->getSourceRange()))
3684 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3685 ExprKind, E->getSourceRange()))
3689 // Completing the expression's type may have changed it.
3690 ExprTy = E->getType();
3691 assert(!ExprTy->isReferenceType());
3693 if (ExprTy->isFunctionType()) {
3694 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3695 << ExprKind << E->getSourceRange();
3699 // The operand for sizeof and alignof is in an unevaluated expression context,
3700 // so side effects could result in unintended consequences.
3701 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3702 !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3703 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3705 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3706 E->getSourceRange(), ExprKind))
3709 if (ExprKind == UETT_SizeOf) {
3710 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3711 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3712 QualType OType = PVD->getOriginalType();
3713 QualType Type = PVD->getType();
3714 if (Type->isPointerType() && OType->isArrayType()) {
3715 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3717 Diag(PVD->getLocation(), diag::note_declared_at);
3722 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3723 // decays into a pointer and returns an unintended result. This is most
3724 // likely a typo for "sizeof(array) op x".
3725 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3726 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3728 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3736 /// \brief Check the constraints on operands to unary expression and type
3739 /// This will complete any types necessary, and validate the various constraints
3740 /// on those operands.
3742 /// The UsualUnaryConversions() function is *not* called by this routine.
3743 /// C99 6.3.2.1p[2-4] all state:
3744 /// Except when it is the operand of the sizeof operator ...
3746 /// C++ [expr.sizeof]p4
3747 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3748 /// standard conversions are not applied to the operand of sizeof.
3750 /// This policy is followed for all of the unary trait expressions.
3751 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3752 SourceLocation OpLoc,
3753 SourceRange ExprRange,
3754 UnaryExprOrTypeTrait ExprKind) {
3755 if (ExprType->isDependentType())
3758 // C++ [expr.sizeof]p2:
3759 // When applied to a reference or a reference type, the result
3760 // is the size of the referenced type.
3761 // C++11 [expr.alignof]p3:
3762 // When alignof is applied to a reference type, the result
3763 // shall be the alignment of the referenced type.
3764 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3765 ExprType = Ref->getPointeeType();
3767 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3768 // When alignof or _Alignof is applied to an array type, the result
3769 // is the alignment of the element type.
3770 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3771 ExprType = Context.getBaseElementType(ExprType);
3773 if (ExprKind == UETT_VecStep)
3774 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3776 // Whitelist some types as extensions
3777 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3781 if (RequireCompleteType(OpLoc, ExprType,
3782 diag::err_sizeof_alignof_incomplete_type,
3783 ExprKind, ExprRange))
3786 if (ExprType->isFunctionType()) {
3787 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3788 << ExprKind << ExprRange;
3792 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3799 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3800 E = E->IgnoreParens();
3802 // Cannot know anything else if the expression is dependent.
3803 if (E->isTypeDependent())
3806 if (E->getObjectKind() == OK_BitField) {
3807 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3808 << 1 << E->getSourceRange();
3812 ValueDecl *D = nullptr;
3813 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3815 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3816 D = ME->getMemberDecl();
3819 // If it's a field, require the containing struct to have a
3820 // complete definition so that we can compute the layout.
3822 // This can happen in C++11 onwards, either by naming the member
3823 // in a way that is not transformed into a member access expression
3824 // (in an unevaluated operand, for instance), or by naming the member
3825 // in a trailing-return-type.
3827 // For the record, since __alignof__ on expressions is a GCC
3828 // extension, GCC seems to permit this but always gives the
3829 // nonsensical answer 0.
3831 // We don't really need the layout here --- we could instead just
3832 // directly check for all the appropriate alignment-lowing
3833 // attributes --- but that would require duplicating a lot of
3834 // logic that just isn't worth duplicating for such a marginal
3836 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3837 // Fast path this check, since we at least know the record has a
3838 // definition if we can find a member of it.
3839 if (!FD->getParent()->isCompleteDefinition()) {
3840 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3841 << E->getSourceRange();
3845 // Otherwise, if it's a field, and the field doesn't have
3846 // reference type, then it must have a complete type (or be a
3847 // flexible array member, which we explicitly want to
3848 // white-list anyway), which makes the following checks trivial.
3849 if (!FD->getType()->isReferenceType())
3853 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3856 bool Sema::CheckVecStepExpr(Expr *E) {
3857 E = E->IgnoreParens();
3859 // Cannot know anything else if the expression is dependent.
3860 if (E->isTypeDependent())
3863 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3866 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3867 CapturingScopeInfo *CSI) {
3868 assert(T->isVariablyModifiedType());
3869 assert(CSI != nullptr);
3871 // We're going to walk down into the type and look for VLA expressions.
3873 const Type *Ty = T.getTypePtr();
3874 switch (Ty->getTypeClass()) {
3875 #define TYPE(Class, Base)
3876 #define ABSTRACT_TYPE(Class, Base)
3877 #define NON_CANONICAL_TYPE(Class, Base)
3878 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3879 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3880 #include "clang/AST/TypeNodes.def"
3883 // These types are never variably-modified.
3887 case Type::ExtVector:
3890 case Type::Elaborated:
3891 case Type::TemplateSpecialization:
3892 case Type::ObjCObject:
3893 case Type::ObjCInterface:
3894 case Type::ObjCObjectPointer:
3895 case Type::ObjCTypeParam:
3897 llvm_unreachable("type class is never variably-modified!");
3898 case Type::Adjusted:
3899 T = cast<AdjustedType>(Ty)->getOriginalType();
3902 T = cast<DecayedType>(Ty)->getPointeeType();
3905 T = cast<PointerType>(Ty)->getPointeeType();
3907 case Type::BlockPointer:
3908 T = cast<BlockPointerType>(Ty)->getPointeeType();
3910 case Type::LValueReference:
3911 case Type::RValueReference:
3912 T = cast<ReferenceType>(Ty)->getPointeeType();
3914 case Type::MemberPointer:
3915 T = cast<MemberPointerType>(Ty)->getPointeeType();
3917 case Type::ConstantArray:
3918 case Type::IncompleteArray:
3919 // Losing element qualification here is fine.
3920 T = cast<ArrayType>(Ty)->getElementType();
3922 case Type::VariableArray: {
3923 // Losing element qualification here is fine.
3924 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3926 // Unknown size indication requires no size computation.
3927 // Otherwise, evaluate and record it.
3928 if (auto Size = VAT->getSizeExpr()) {
3929 if (!CSI->isVLATypeCaptured(VAT)) {
3930 RecordDecl *CapRecord = nullptr;
3931 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3932 CapRecord = LSI->Lambda;
3933 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3934 CapRecord = CRSI->TheRecordDecl;
3937 auto ExprLoc = Size->getExprLoc();
3938 auto SizeType = Context.getSizeType();
3939 // Build the non-static data member.
3941 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3942 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3943 /*BW*/ nullptr, /*Mutable*/ false,
3944 /*InitStyle*/ ICIS_NoInit);
3945 Field->setImplicit(true);
3946 Field->setAccess(AS_private);
3947 Field->setCapturedVLAType(VAT);
3948 CapRecord->addDecl(Field);
3950 CSI->addVLATypeCapture(ExprLoc, SizeType);
3954 T = VAT->getElementType();
3957 case Type::FunctionProto:
3958 case Type::FunctionNoProto:
3959 T = cast<FunctionType>(Ty)->getReturnType();
3963 case Type::UnaryTransform:
3964 case Type::Attributed:
3965 case Type::SubstTemplateTypeParm:
3966 case Type::PackExpansion:
3967 // Keep walking after single level desugaring.
3968 T = T.getSingleStepDesugaredType(Context);
3971 T = cast<TypedefType>(Ty)->desugar();
3973 case Type::Decltype:
3974 T = cast<DecltypeType>(Ty)->desugar();
3977 case Type::DeducedTemplateSpecialization:
3978 T = cast<DeducedType>(Ty)->getDeducedType();
3980 case Type::TypeOfExpr:
3981 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3984 T = cast<AtomicType>(Ty)->getValueType();
3987 } while (!T.isNull() && T->isVariablyModifiedType());
3990 /// \brief Build a sizeof or alignof expression given a type operand.
3992 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3993 SourceLocation OpLoc,
3994 UnaryExprOrTypeTrait ExprKind,
3999 QualType T = TInfo->getType();
4001 if (!T->isDependentType() &&
4002 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4005 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4006 if (auto *TT = T->getAs<TypedefType>()) {
4007 for (auto I = FunctionScopes.rbegin(),
4008 E = std::prev(FunctionScopes.rend());
4010 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4013 DeclContext *DC = nullptr;
4014 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4015 DC = LSI->CallOperator;
4016 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4017 DC = CRSI->TheCapturedDecl;
4018 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4021 if (DC->containsDecl(TT->getDecl()))
4023 captureVariablyModifiedType(Context, T, CSI);
4029 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4030 return new (Context) UnaryExprOrTypeTraitExpr(
4031 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4034 /// \brief Build a sizeof or alignof expression given an expression
4037 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4038 UnaryExprOrTypeTrait ExprKind) {
4039 ExprResult PE = CheckPlaceholderExpr(E);
4045 // Verify that the operand is valid.
4046 bool isInvalid = false;
4047 if (E->isTypeDependent()) {
4048 // Delay type-checking for type-dependent expressions.
4049 } else if (ExprKind == UETT_AlignOf) {
4050 isInvalid = CheckAlignOfExpr(*this, E);
4051 } else if (ExprKind == UETT_VecStep) {
4052 isInvalid = CheckVecStepExpr(E);
4053 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4054 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4056 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4057 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4060 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4066 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4067 PE = TransformToPotentiallyEvaluated(E);
4068 if (PE.isInvalid()) return ExprError();
4072 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4073 return new (Context) UnaryExprOrTypeTraitExpr(
4074 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4077 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4078 /// expr and the same for @c alignof and @c __alignof
4079 /// Note that the ArgRange is invalid if isType is false.
4081 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4082 UnaryExprOrTypeTrait ExprKind, bool IsType,
4083 void *TyOrEx, SourceRange ArgRange) {
4084 // If error parsing type, ignore.
4085 if (!TyOrEx) return ExprError();
4088 TypeSourceInfo *TInfo;
4089 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4090 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4093 Expr *ArgEx = (Expr *)TyOrEx;
4094 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4098 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4100 if (V.get()->isTypeDependent())
4101 return S.Context.DependentTy;
4103 // _Real and _Imag are only l-values for normal l-values.
4104 if (V.get()->getObjectKind() != OK_Ordinary) {
4105 V = S.DefaultLvalueConversion(V.get());
4110 // These operators return the element type of a complex type.
4111 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4112 return CT->getElementType();
4114 // Otherwise they pass through real integer and floating point types here.
4115 if (V.get()->getType()->isArithmeticType())
4116 return V.get()->getType();
4118 // Test for placeholders.
4119 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4120 if (PR.isInvalid()) return QualType();
4121 if (PR.get() != V.get()) {
4123 return CheckRealImagOperand(S, V, Loc, IsReal);
4126 // Reject anything else.
4127 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4128 << (IsReal ? "__real" : "__imag");
4135 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4136 tok::TokenKind Kind, Expr *Input) {
4137 UnaryOperatorKind Opc;
4139 default: llvm_unreachable("Unknown unary op!");
4140 case tok::plusplus: Opc = UO_PostInc; break;
4141 case tok::minusminus: Opc = UO_PostDec; break;
4144 // Since this might is a postfix expression, get rid of ParenListExprs.
4145 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4146 if (Result.isInvalid()) return ExprError();
4147 Input = Result.get();
4149 return BuildUnaryOp(S, OpLoc, Opc, Input);
4152 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4154 /// \return true on error
4155 static bool checkArithmeticOnObjCPointer(Sema &S,
4156 SourceLocation opLoc,
4158 assert(op->getType()->isObjCObjectPointerType());
4159 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4160 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4163 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4164 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4165 << op->getSourceRange();
4169 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4170 auto *BaseNoParens = Base->IgnoreParens();
4171 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4172 return MSProp->getPropertyDecl()->getType()->isArrayType();
4173 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4177 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4178 Expr *idx, SourceLocation rbLoc) {
4179 if (base && !base->getType().isNull() &&
4180 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4181 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4182 /*Length=*/nullptr, rbLoc);
4184 // Since this might be a postfix expression, get rid of ParenListExprs.
4185 if (isa<ParenListExpr>(base)) {
4186 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4187 if (result.isInvalid()) return ExprError();
4188 base = result.get();
4191 // Handle any non-overload placeholder types in the base and index
4192 // expressions. We can't handle overloads here because the other
4193 // operand might be an overloadable type, in which case the overload
4194 // resolution for the operator overload should get the first crack
4196 bool IsMSPropertySubscript = false;
4197 if (base->getType()->isNonOverloadPlaceholderType()) {
4198 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4199 if (!IsMSPropertySubscript) {
4200 ExprResult result = CheckPlaceholderExpr(base);
4201 if (result.isInvalid())
4203 base = result.get();
4206 if (idx->getType()->isNonOverloadPlaceholderType()) {
4207 ExprResult result = CheckPlaceholderExpr(idx);
4208 if (result.isInvalid()) return ExprError();
4212 // Build an unanalyzed expression if either operand is type-dependent.
4213 if (getLangOpts().CPlusPlus &&
4214 (base->isTypeDependent() || idx->isTypeDependent())) {
4215 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4216 VK_LValue, OK_Ordinary, rbLoc);
4219 // MSDN, property (C++)
4220 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4221 // This attribute can also be used in the declaration of an empty array in a
4222 // class or structure definition. For example:
4223 // __declspec(property(get=GetX, put=PutX)) int x[];
4224 // The above statement indicates that x[] can be used with one or more array
4225 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4226 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4227 if (IsMSPropertySubscript) {
4228 // Build MS property subscript expression if base is MS property reference
4229 // or MS property subscript.
4230 return new (Context) MSPropertySubscriptExpr(
4231 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4234 // Use C++ overloaded-operator rules if either operand has record
4235 // type. The spec says to do this if either type is *overloadable*,
4236 // but enum types can't declare subscript operators or conversion
4237 // operators, so there's nothing interesting for overload resolution
4238 // to do if there aren't any record types involved.
4240 // ObjC pointers have their own subscripting logic that is not tied
4241 // to overload resolution and so should not take this path.
4242 if (getLangOpts().CPlusPlus &&
4243 (base->getType()->isRecordType() ||
4244 (!base->getType()->isObjCObjectPointerType() &&
4245 idx->getType()->isRecordType()))) {
4246 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4249 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4252 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4254 SourceLocation ColonLoc, Expr *Length,
4255 SourceLocation RBLoc) {
4256 if (Base->getType()->isPlaceholderType() &&
4257 !Base->getType()->isSpecificPlaceholderType(
4258 BuiltinType::OMPArraySection)) {
4259 ExprResult Result = CheckPlaceholderExpr(Base);
4260 if (Result.isInvalid())
4262 Base = Result.get();
4264 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4265 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4266 if (Result.isInvalid())
4268 Result = DefaultLvalueConversion(Result.get());
4269 if (Result.isInvalid())
4271 LowerBound = Result.get();
4273 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4274 ExprResult Result = CheckPlaceholderExpr(Length);
4275 if (Result.isInvalid())
4277 Result = DefaultLvalueConversion(Result.get());
4278 if (Result.isInvalid())
4280 Length = Result.get();
4283 // Build an unanalyzed expression if either operand is type-dependent.
4284 if (Base->isTypeDependent() ||
4286 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4287 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4288 return new (Context)
4289 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4290 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4293 // Perform default conversions.
4294 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4296 if (OriginalTy->isAnyPointerType()) {
4297 ResultTy = OriginalTy->getPointeeType();
4298 } else if (OriginalTy->isArrayType()) {
4299 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4302 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4303 << Base->getSourceRange());
4307 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4309 if (Res.isInvalid())
4310 return ExprError(Diag(LowerBound->getExprLoc(),
4311 diag::err_omp_typecheck_section_not_integer)
4312 << 0 << LowerBound->getSourceRange());
4313 LowerBound = Res.get();
4315 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4316 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4317 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4318 << 0 << LowerBound->getSourceRange();
4322 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4323 if (Res.isInvalid())
4324 return ExprError(Diag(Length->getExprLoc(),
4325 diag::err_omp_typecheck_section_not_integer)
4326 << 1 << Length->getSourceRange());
4329 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4330 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4331 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4332 << 1 << Length->getSourceRange();
4335 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4336 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4337 // type. Note that functions are not objects, and that (in C99 parlance)
4338 // incomplete types are not object types.
4339 if (ResultTy->isFunctionType()) {
4340 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4341 << ResultTy << Base->getSourceRange();
4345 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4346 diag::err_omp_section_incomplete_type, Base))
4349 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4350 llvm::APSInt LowerBoundValue;
4351 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4352 // OpenMP 4.5, [2.4 Array Sections]
4353 // The array section must be a subset of the original array.
4354 if (LowerBoundValue.isNegative()) {
4355 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4356 << LowerBound->getSourceRange();
4363 llvm::APSInt LengthValue;
4364 if (Length->EvaluateAsInt(LengthValue, Context)) {
4365 // OpenMP 4.5, [2.4 Array Sections]
4366 // The length must evaluate to non-negative integers.
4367 if (LengthValue.isNegative()) {
4368 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4369 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4370 << Length->getSourceRange();
4374 } else if (ColonLoc.isValid() &&
4375 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4376 !OriginalTy->isVariableArrayType()))) {
4377 // OpenMP 4.5, [2.4 Array Sections]
4378 // When the size of the array dimension is not known, the length must be
4379 // specified explicitly.
4380 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4381 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4385 if (!Base->getType()->isSpecificPlaceholderType(
4386 BuiltinType::OMPArraySection)) {
4387 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4388 if (Result.isInvalid())
4390 Base = Result.get();
4392 return new (Context)
4393 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4394 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4398 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4399 Expr *Idx, SourceLocation RLoc) {
4400 Expr *LHSExp = Base;
4403 ExprValueKind VK = VK_LValue;
4404 ExprObjectKind OK = OK_Ordinary;
4406 // Per C++ core issue 1213, the result is an xvalue if either operand is
4407 // a non-lvalue array, and an lvalue otherwise.
4408 if (getLangOpts().CPlusPlus11 &&
4409 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4410 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4413 // Perform default conversions.
4414 if (!LHSExp->getType()->getAs<VectorType>()) {
4415 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4416 if (Result.isInvalid())
4418 LHSExp = Result.get();
4420 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4421 if (Result.isInvalid())
4423 RHSExp = Result.get();
4425 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4427 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4428 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4429 // in the subscript position. As a result, we need to derive the array base
4430 // and index from the expression types.
4431 Expr *BaseExpr, *IndexExpr;
4432 QualType ResultType;
4433 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4436 ResultType = Context.DependentTy;
4437 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4440 ResultType = PTy->getPointeeType();
4441 } else if (const ObjCObjectPointerType *PTy =
4442 LHSTy->getAs<ObjCObjectPointerType>()) {
4446 // Use custom logic if this should be the pseudo-object subscript
4448 if (!LangOpts.isSubscriptPointerArithmetic())
4449 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4452 ResultType = PTy->getPointeeType();
4453 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4454 // Handle the uncommon case of "123[Ptr]".
4457 ResultType = PTy->getPointeeType();
4458 } else if (const ObjCObjectPointerType *PTy =
4459 RHSTy->getAs<ObjCObjectPointerType>()) {
4460 // Handle the uncommon case of "123[Ptr]".
4463 ResultType = PTy->getPointeeType();
4464 if (!LangOpts.isSubscriptPointerArithmetic()) {
4465 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4466 << ResultType << BaseExpr->getSourceRange();
4469 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4470 BaseExpr = LHSExp; // vectors: V[123]
4472 VK = LHSExp->getValueKind();
4473 if (VK != VK_RValue)
4474 OK = OK_VectorComponent;
4476 // FIXME: need to deal with const...
4477 ResultType = VTy->getElementType();
4478 } else if (LHSTy->isArrayType()) {
4479 // If we see an array that wasn't promoted by
4480 // DefaultFunctionArrayLvalueConversion, it must be an array that
4481 // wasn't promoted because of the C90 rule that doesn't
4482 // allow promoting non-lvalue arrays. Warn, then
4483 // force the promotion here.
4484 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4485 LHSExp->getSourceRange();
4486 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4487 CK_ArrayToPointerDecay).get();
4488 LHSTy = LHSExp->getType();
4492 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4493 } else if (RHSTy->isArrayType()) {
4494 // Same as previous, except for 123[f().a] case
4495 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4496 RHSExp->getSourceRange();
4497 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4498 CK_ArrayToPointerDecay).get();
4499 RHSTy = RHSExp->getType();
4503 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4505 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4506 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4509 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4510 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4511 << IndexExpr->getSourceRange());
4513 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4514 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4515 && !IndexExpr->isTypeDependent())
4516 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4518 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4519 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4520 // type. Note that Functions are not objects, and that (in C99 parlance)
4521 // incomplete types are not object types.
4522 if (ResultType->isFunctionType()) {
4523 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4524 << ResultType << BaseExpr->getSourceRange();
4528 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4529 // GNU extension: subscripting on pointer to void
4530 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4531 << BaseExpr->getSourceRange();
4533 // C forbids expressions of unqualified void type from being l-values.
4534 // See IsCForbiddenLValueType.
4535 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4536 } else if (!ResultType->isDependentType() &&
4537 RequireCompleteType(LLoc, ResultType,
4538 diag::err_subscript_incomplete_type, BaseExpr))
4541 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4542 !ResultType.isCForbiddenLValueType());
4544 return new (Context)
4545 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4548 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4549 ParmVarDecl *Param) {
4550 if (Param->hasUnparsedDefaultArg()) {
4552 diag::err_use_of_default_argument_to_function_declared_later) <<
4553 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4554 Diag(UnparsedDefaultArgLocs[Param],
4555 diag::note_default_argument_declared_here);
4559 if (Param->hasUninstantiatedDefaultArg()) {
4560 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4562 EnterExpressionEvaluationContext EvalContext(
4563 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4565 // Instantiate the expression.
4566 MultiLevelTemplateArgumentList MutiLevelArgList
4567 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4569 InstantiatingTemplate Inst(*this, CallLoc, Param,
4570 MutiLevelArgList.getInnermost());
4571 if (Inst.isInvalid())
4573 if (Inst.isAlreadyInstantiating()) {
4574 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4575 Param->setInvalidDecl();
4581 // C++ [dcl.fct.default]p5:
4582 // The names in the [default argument] expression are bound, and
4583 // the semantic constraints are checked, at the point where the
4584 // default argument expression appears.
4585 ContextRAII SavedContext(*this, FD);
4586 LocalInstantiationScope Local(*this);
4587 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4588 /*DirectInit*/false);
4590 if (Result.isInvalid())
4593 // Check the expression as an initializer for the parameter.
4594 InitializedEntity Entity
4595 = InitializedEntity::InitializeParameter(Context, Param);
4596 InitializationKind Kind
4597 = InitializationKind::CreateCopy(Param->getLocation(),
4598 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4599 Expr *ResultE = Result.getAs<Expr>();
4601 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4602 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4603 if (Result.isInvalid())
4606 Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4607 Param->getOuterLocStart());
4608 if (Result.isInvalid())
4611 // Remember the instantiated default argument.
4612 Param->setDefaultArg(Result.getAs<Expr>());
4613 if (ASTMutationListener *L = getASTMutationListener()) {
4614 L->DefaultArgumentInstantiated(Param);
4618 // If the default argument expression is not set yet, we are building it now.
4619 if (!Param->hasInit()) {
4620 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4621 Param->setInvalidDecl();
4625 // If the default expression creates temporaries, we need to
4626 // push them to the current stack of expression temporaries so they'll
4627 // be properly destroyed.
4628 // FIXME: We should really be rebuilding the default argument with new
4629 // bound temporaries; see the comment in PR5810.
4630 // We don't need to do that with block decls, though, because
4631 // blocks in default argument expression can never capture anything.
4632 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4633 // Set the "needs cleanups" bit regardless of whether there are
4634 // any explicit objects.
4635 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4637 // Append all the objects to the cleanup list. Right now, this
4638 // should always be a no-op, because blocks in default argument
4639 // expressions should never be able to capture anything.
4640 assert(!Init->getNumObjects() &&
4641 "default argument expression has capturing blocks?");
4644 // We already type-checked the argument, so we know it works.
4645 // Just mark all of the declarations in this potentially-evaluated expression
4646 // as being "referenced".
4647 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4648 /*SkipLocalVariables=*/true);
4652 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4653 FunctionDecl *FD, ParmVarDecl *Param) {
4654 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4656 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4659 Sema::VariadicCallType
4660 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4662 if (Proto && Proto->isVariadic()) {
4663 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4664 return VariadicConstructor;
4665 else if (Fn && Fn->getType()->isBlockPointerType())
4666 return VariadicBlock;
4668 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4669 if (Method->isInstance())
4670 return VariadicMethod;
4671 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4672 return VariadicMethod;
4673 return VariadicFunction;
4675 return VariadicDoesNotApply;
4679 class FunctionCallCCC : public FunctionCallFilterCCC {
4681 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4682 unsigned NumArgs, MemberExpr *ME)
4683 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4684 FunctionName(FuncName) {}
4686 bool ValidateCandidate(const TypoCorrection &candidate) override {
4687 if (!candidate.getCorrectionSpecifier() ||
4688 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4692 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4696 const IdentifierInfo *const FunctionName;
4700 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4701 FunctionDecl *FDecl,
4702 ArrayRef<Expr *> Args) {
4703 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4704 DeclarationName FuncName = FDecl->getDeclName();
4705 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4707 if (TypoCorrection Corrected = S.CorrectTypo(
4708 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4709 S.getScopeForContext(S.CurContext), nullptr,
4710 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4712 Sema::CTK_ErrorRecovery)) {
4713 if (NamedDecl *ND = Corrected.getFoundDecl()) {
4714 if (Corrected.isOverloaded()) {
4715 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4716 OverloadCandidateSet::iterator Best;
4717 for (NamedDecl *CD : Corrected) {
4718 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4719 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4722 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4724 ND = Best->FoundDecl;
4725 Corrected.setCorrectionDecl(ND);
4731 ND = ND->getUnderlyingDecl();
4732 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4736 return TypoCorrection();
4739 /// ConvertArgumentsForCall - Converts the arguments specified in
4740 /// Args/NumArgs to the parameter types of the function FDecl with
4741 /// function prototype Proto. Call is the call expression itself, and
4742 /// Fn is the function expression. For a C++ member function, this
4743 /// routine does not attempt to convert the object argument. Returns
4744 /// true if the call is ill-formed.
4746 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4747 FunctionDecl *FDecl,
4748 const FunctionProtoType *Proto,
4749 ArrayRef<Expr *> Args,
4750 SourceLocation RParenLoc,
4751 bool IsExecConfig) {
4752 // Bail out early if calling a builtin with custom typechecking.
4754 if (unsigned ID = FDecl->getBuiltinID())
4755 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4758 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4759 // assignment, to the types of the corresponding parameter, ...
4760 unsigned NumParams = Proto->getNumParams();
4761 bool Invalid = false;
4762 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4763 unsigned FnKind = Fn->getType()->isBlockPointerType()
4765 : (IsExecConfig ? 3 /* kernel function (exec config) */
4766 : 0 /* function */);
4768 // If too few arguments are available (and we don't have default
4769 // arguments for the remaining parameters), don't make the call.
4770 if (Args.size() < NumParams) {
4771 if (Args.size() < MinArgs) {
4773 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4775 MinArgs == NumParams && !Proto->isVariadic()
4776 ? diag::err_typecheck_call_too_few_args_suggest
4777 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4778 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4779 << static_cast<unsigned>(Args.size())
4780 << TC.getCorrectionRange());
4781 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4783 MinArgs == NumParams && !Proto->isVariadic()
4784 ? diag::err_typecheck_call_too_few_args_one
4785 : diag::err_typecheck_call_too_few_args_at_least_one)
4786 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4788 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4789 ? diag::err_typecheck_call_too_few_args
4790 : diag::err_typecheck_call_too_few_args_at_least)
4791 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4792 << Fn->getSourceRange();
4794 // Emit the location of the prototype.
4795 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4796 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4801 Call->setNumArgs(Context, NumParams);
4804 // If too many are passed and not variadic, error on the extras and drop
4806 if (Args.size() > NumParams) {
4807 if (!Proto->isVariadic()) {
4809 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4811 MinArgs == NumParams && !Proto->isVariadic()
4812 ? diag::err_typecheck_call_too_many_args_suggest
4813 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4814 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4815 << static_cast<unsigned>(Args.size())
4816 << TC.getCorrectionRange());
4817 } else if (NumParams == 1 && FDecl &&
4818 FDecl->getParamDecl(0)->getDeclName())
4819 Diag(Args[NumParams]->getLocStart(),
4820 MinArgs == NumParams
4821 ? diag::err_typecheck_call_too_many_args_one
4822 : diag::err_typecheck_call_too_many_args_at_most_one)
4823 << FnKind << FDecl->getParamDecl(0)
4824 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4825 << SourceRange(Args[NumParams]->getLocStart(),
4826 Args.back()->getLocEnd());
4828 Diag(Args[NumParams]->getLocStart(),
4829 MinArgs == NumParams
4830 ? diag::err_typecheck_call_too_many_args
4831 : diag::err_typecheck_call_too_many_args_at_most)
4832 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4833 << Fn->getSourceRange()
4834 << SourceRange(Args[NumParams]->getLocStart(),
4835 Args.back()->getLocEnd());
4837 // Emit the location of the prototype.
4838 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4839 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4842 // This deletes the extra arguments.
4843 Call->setNumArgs(Context, NumParams);
4847 SmallVector<Expr *, 8> AllArgs;
4848 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4850 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4851 Proto, 0, Args, AllArgs, CallType);
4854 unsigned TotalNumArgs = AllArgs.size();
4855 for (unsigned i = 0; i < TotalNumArgs; ++i)
4856 Call->setArg(i, AllArgs[i]);
4861 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4862 const FunctionProtoType *Proto,
4863 unsigned FirstParam, ArrayRef<Expr *> Args,
4864 SmallVectorImpl<Expr *> &AllArgs,
4865 VariadicCallType CallType, bool AllowExplicit,
4866 bool IsListInitialization) {
4867 unsigned NumParams = Proto->getNumParams();
4868 bool Invalid = false;
4870 // Continue to check argument types (even if we have too few/many args).
4871 for (unsigned i = FirstParam; i < NumParams; i++) {
4872 QualType ProtoArgType = Proto->getParamType(i);
4875 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4876 if (ArgIx < Args.size()) {
4877 Arg = Args[ArgIx++];
4879 if (RequireCompleteType(Arg->getLocStart(),
4881 diag::err_call_incomplete_argument, Arg))
4884 // Strip the unbridged-cast placeholder expression off, if applicable.
4885 bool CFAudited = false;
4886 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4887 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4888 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4889 Arg = stripARCUnbridgedCast(Arg);
4890 else if (getLangOpts().ObjCAutoRefCount &&
4891 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4892 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4895 InitializedEntity Entity =
4896 Param ? InitializedEntity::InitializeParameter(Context, Param,
4898 : InitializedEntity::InitializeParameter(
4899 Context, ProtoArgType, Proto->isParamConsumed(i));
4901 // Remember that parameter belongs to a CF audited API.
4903 Entity.setParameterCFAudited();
4905 ExprResult ArgE = PerformCopyInitialization(
4906 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4907 if (ArgE.isInvalid())
4910 Arg = ArgE.getAs<Expr>();
4912 assert(Param && "can't use default arguments without a known callee");
4914 ExprResult ArgExpr =
4915 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4916 if (ArgExpr.isInvalid())
4919 Arg = ArgExpr.getAs<Expr>();
4922 // Check for array bounds violations for each argument to the call. This
4923 // check only triggers warnings when the argument isn't a more complex Expr
4924 // with its own checking, such as a BinaryOperator.
4925 CheckArrayAccess(Arg);
4927 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4928 CheckStaticArrayArgument(CallLoc, Param, Arg);
4930 AllArgs.push_back(Arg);
4933 // If this is a variadic call, handle args passed through "...".
4934 if (CallType != VariadicDoesNotApply) {
4935 // Assume that extern "C" functions with variadic arguments that
4936 // return __unknown_anytype aren't *really* variadic.
4937 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4938 FDecl->isExternC()) {
4939 for (Expr *A : Args.slice(ArgIx)) {
4940 QualType paramType; // ignored
4941 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4942 Invalid |= arg.isInvalid();
4943 AllArgs.push_back(arg.get());
4946 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4948 for (Expr *A : Args.slice(ArgIx)) {
4949 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4950 Invalid |= Arg.isInvalid();
4951 AllArgs.push_back(Arg.get());
4955 // Check for array bounds violations.
4956 for (Expr *A : Args.slice(ArgIx))
4957 CheckArrayAccess(A);
4962 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4963 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4964 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4965 TL = DTL.getOriginalLoc();
4966 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4967 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4968 << ATL.getLocalSourceRange();
4971 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4972 /// array parameter, check that it is non-null, and that if it is formed by
4973 /// array-to-pointer decay, the underlying array is sufficiently large.
4975 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4976 /// array type derivation, then for each call to the function, the value of the
4977 /// corresponding actual argument shall provide access to the first element of
4978 /// an array with at least as many elements as specified by the size expression.
4980 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4982 const Expr *ArgExpr) {
4983 // Static array parameters are not supported in C++.
4984 if (!Param || getLangOpts().CPlusPlus)
4987 QualType OrigTy = Param->getOriginalType();
4989 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4990 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4993 if (ArgExpr->isNullPointerConstant(Context,
4994 Expr::NPC_NeverValueDependent)) {
4995 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4996 DiagnoseCalleeStaticArrayParam(*this, Param);
5000 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5004 const ConstantArrayType *ArgCAT =
5005 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5009 if (ArgCAT->getSize().ult(CAT->getSize())) {
5010 Diag(CallLoc, diag::warn_static_array_too_small)
5011 << ArgExpr->getSourceRange()
5012 << (unsigned) ArgCAT->getSize().getZExtValue()
5013 << (unsigned) CAT->getSize().getZExtValue();
5014 DiagnoseCalleeStaticArrayParam(*this, Param);
5018 /// Given a function expression of unknown-any type, try to rebuild it
5019 /// to have a function type.
5020 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5022 /// Is the given type a placeholder that we need to lower out
5023 /// immediately during argument processing?
5024 static bool isPlaceholderToRemoveAsArg(QualType type) {
5025 // Placeholders are never sugared.
5026 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5027 if (!placeholder) return false;
5029 switch (placeholder->getKind()) {
5030 // Ignore all the non-placeholder types.
5031 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5032 case BuiltinType::Id:
5033 #include "clang/Basic/OpenCLImageTypes.def"
5034 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5035 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5036 #include "clang/AST/BuiltinTypes.def"
5039 // We cannot lower out overload sets; they might validly be resolved
5040 // by the call machinery.
5041 case BuiltinType::Overload:
5044 // Unbridged casts in ARC can be handled in some call positions and
5045 // should be left in place.
5046 case BuiltinType::ARCUnbridgedCast:
5049 // Pseudo-objects should be converted as soon as possible.
5050 case BuiltinType::PseudoObject:
5053 // The debugger mode could theoretically but currently does not try
5054 // to resolve unknown-typed arguments based on known parameter types.
5055 case BuiltinType::UnknownAny:
5058 // These are always invalid as call arguments and should be reported.
5059 case BuiltinType::BoundMember:
5060 case BuiltinType::BuiltinFn:
5061 case BuiltinType::OMPArraySection:
5065 llvm_unreachable("bad builtin type kind");
5068 /// Check an argument list for placeholders that we won't try to
5070 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5071 // Apply this processing to all the arguments at once instead of
5072 // dying at the first failure.
5073 bool hasInvalid = false;
5074 for (size_t i = 0, e = args.size(); i != e; i++) {
5075 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5076 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5077 if (result.isInvalid()) hasInvalid = true;
5078 else args[i] = result.get();
5079 } else if (hasInvalid) {
5080 (void)S.CorrectDelayedTyposInExpr(args[i]);
5086 /// If a builtin function has a pointer argument with no explicit address
5087 /// space, then it should be able to accept a pointer to any address
5088 /// space as input. In order to do this, we need to replace the
5089 /// standard builtin declaration with one that uses the same address space
5092 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5093 /// it does not contain any pointer arguments without
5094 /// an address space qualifer. Otherwise the rewritten
5095 /// FunctionDecl is returned.
5096 /// TODO: Handle pointer return types.
5097 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5098 const FunctionDecl *FDecl,
5099 MultiExprArg ArgExprs) {
5101 QualType DeclType = FDecl->getType();
5102 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5104 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5105 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5108 bool NeedsNewDecl = false;
5110 SmallVector<QualType, 8> OverloadParams;
5112 for (QualType ParamType : FT->param_types()) {
5114 // Convert array arguments to pointer to simplify type lookup.
5116 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5117 if (ArgRes.isInvalid())
5119 Expr *Arg = ArgRes.get();
5120 QualType ArgType = Arg->getType();
5121 if (!ParamType->isPointerType() ||
5122 ParamType.getQualifiers().hasAddressSpace() ||
5123 !ArgType->isPointerType() ||
5124 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5125 OverloadParams.push_back(ParamType);
5129 NeedsNewDecl = true;
5130 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5132 QualType PointeeType = ParamType->getPointeeType();
5133 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5134 OverloadParams.push_back(Context.getPointerType(PointeeType));
5140 FunctionProtoType::ExtProtoInfo EPI;
5141 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5142 OverloadParams, EPI);
5143 DeclContext *Parent = Context.getTranslationUnitDecl();
5144 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5145 FDecl->getLocation(),
5146 FDecl->getLocation(),
5147 FDecl->getIdentifier(),
5151 /*hasPrototype=*/true);
5152 SmallVector<ParmVarDecl*, 16> Params;
5153 FT = cast<FunctionProtoType>(OverloadTy);
5154 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5155 QualType ParamType = FT->getParamType(i);
5157 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5158 SourceLocation(), nullptr, ParamType,
5159 /*TInfo=*/nullptr, SC_None, nullptr);
5160 Parm->setScopeInfo(0, i);
5161 Params.push_back(Parm);
5163 OverloadDecl->setParams(Params);
5164 return OverloadDecl;
5167 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5168 FunctionDecl *Callee,
5169 MultiExprArg ArgExprs) {
5170 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5171 // similar attributes) really don't like it when functions are called with an
5172 // invalid number of args.
5173 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5174 /*PartialOverloading=*/false) &&
5175 !Callee->isVariadic())
5177 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5180 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5181 S.Diag(Fn->getLocStart(),
5182 isa<CXXMethodDecl>(Callee)
5183 ? diag::err_ovl_no_viable_member_function_in_call
5184 : diag::err_ovl_no_viable_function_in_call)
5185 << Callee << Callee->getSourceRange();
5186 S.Diag(Callee->getLocation(),
5187 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5188 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5193 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5194 /// This provides the location of the left/right parens and a list of comma
5196 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5197 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5198 Expr *ExecConfig, bool IsExecConfig) {
5199 // Since this might be a postfix expression, get rid of ParenListExprs.
5200 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5201 if (Result.isInvalid()) return ExprError();
5204 if (checkArgsForPlaceholders(*this, ArgExprs))
5207 if (getLangOpts().CPlusPlus) {
5208 // If this is a pseudo-destructor expression, build the call immediately.
5209 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5210 if (!ArgExprs.empty()) {
5211 // Pseudo-destructor calls should not have any arguments.
5212 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5213 << FixItHint::CreateRemoval(
5214 SourceRange(ArgExprs.front()->getLocStart(),
5215 ArgExprs.back()->getLocEnd()));
5218 return new (Context)
5219 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5221 if (Fn->getType() == Context.PseudoObjectTy) {
5222 ExprResult result = CheckPlaceholderExpr(Fn);
5223 if (result.isInvalid()) return ExprError();
5227 // Determine whether this is a dependent call inside a C++ template,
5228 // in which case we won't do any semantic analysis now.
5229 bool Dependent = false;
5230 if (Fn->isTypeDependent())
5232 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5237 return new (Context) CUDAKernelCallExpr(
5238 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5239 Context.DependentTy, VK_RValue, RParenLoc);
5241 return new (Context) CallExpr(
5242 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5246 // Determine whether this is a call to an object (C++ [over.call.object]).
5247 if (Fn->getType()->isRecordType())
5248 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5251 if (Fn->getType() == Context.UnknownAnyTy) {
5252 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5253 if (result.isInvalid()) return ExprError();
5257 if (Fn->getType() == Context.BoundMemberTy) {
5258 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5263 // Check for overloaded calls. This can happen even in C due to extensions.
5264 if (Fn->getType() == Context.OverloadTy) {
5265 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5267 // We aren't supposed to apply this logic for if there'Scope an '&'
5269 if (!find.HasFormOfMemberPointer) {
5270 OverloadExpr *ovl = find.Expression;
5271 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5272 return BuildOverloadedCallExpr(
5273 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5274 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5275 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5280 // If we're directly calling a function, get the appropriate declaration.
5281 if (Fn->getType() == Context.UnknownAnyTy) {
5282 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5283 if (result.isInvalid()) return ExprError();
5287 Expr *NakedFn = Fn->IgnoreParens();
5289 bool CallingNDeclIndirectly = false;
5290 NamedDecl *NDecl = nullptr;
5291 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5292 if (UnOp->getOpcode() == UO_AddrOf) {
5293 CallingNDeclIndirectly = true;
5294 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5298 if (isa<DeclRefExpr>(NakedFn)) {
5299 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5301 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5302 if (FDecl && FDecl->getBuiltinID()) {
5303 // Rewrite the function decl for this builtin by replacing parameters
5304 // with no explicit address space with the address space of the arguments
5307 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5309 Fn = DeclRefExpr::Create(
5310 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5311 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5314 } else if (isa<MemberExpr>(NakedFn))
5315 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5317 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5318 if (CallingNDeclIndirectly &&
5319 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5323 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5326 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5329 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5330 ExecConfig, IsExecConfig);
5333 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5335 /// __builtin_astype( value, dst type )
5337 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5338 SourceLocation BuiltinLoc,
5339 SourceLocation RParenLoc) {
5340 ExprValueKind VK = VK_RValue;
5341 ExprObjectKind OK = OK_Ordinary;
5342 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5343 QualType SrcTy = E->getType();
5344 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5345 return ExprError(Diag(BuiltinLoc,
5346 diag::err_invalid_astype_of_different_size)
5349 << E->getSourceRange());
5350 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5353 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5354 /// provided arguments.
5356 /// __builtin_convertvector( value, dst type )
5358 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5359 SourceLocation BuiltinLoc,
5360 SourceLocation RParenLoc) {
5361 TypeSourceInfo *TInfo;
5362 GetTypeFromParser(ParsedDestTy, &TInfo);
5363 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5366 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5367 /// i.e. an expression not of \p OverloadTy. The expression should
5368 /// unary-convert to an expression of function-pointer or
5369 /// block-pointer type.
5371 /// \param NDecl the declaration being called, if available
5373 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5374 SourceLocation LParenLoc,
5375 ArrayRef<Expr *> Args,
5376 SourceLocation RParenLoc,
5377 Expr *Config, bool IsExecConfig) {
5378 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5379 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5381 // Functions with 'interrupt' attribute cannot be called directly.
5382 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5383 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5387 // Interrupt handlers don't save off the VFP regs automatically on ARM,
5388 // so there's some risk when calling out to non-interrupt handler functions
5389 // that the callee might not preserve them. This is easy to diagnose here,
5390 // but can be very challenging to debug.
5391 if (auto *Caller = getCurFunctionDecl())
5392 if (Caller->hasAttr<ARMInterruptAttr>())
5393 if (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())
5394 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5396 // Promote the function operand.
5397 // We special-case function promotion here because we only allow promoting
5398 // builtin functions to function pointers in the callee of a call.
5401 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5402 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5403 CK_BuiltinFnToFnPtr).get();
5405 Result = CallExprUnaryConversions(Fn);
5407 if (Result.isInvalid())
5411 // Make the call expr early, before semantic checks. This guarantees cleanup
5412 // of arguments and function on error.
5415 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5416 cast<CallExpr>(Config), Args,
5417 Context.BoolTy, VK_RValue,
5420 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5421 VK_RValue, RParenLoc);
5423 if (!getLangOpts().CPlusPlus) {
5424 // C cannot always handle TypoExpr nodes in builtin calls and direct
5425 // function calls as their argument checking don't necessarily handle
5426 // dependent types properly, so make sure any TypoExprs have been
5428 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5429 if (!Result.isUsable()) return ExprError();
5430 TheCall = dyn_cast<CallExpr>(Result.get());
5431 if (!TheCall) return Result;
5432 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5435 // Bail out early if calling a builtin with custom typechecking.
5436 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5437 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5440 const FunctionType *FuncT;
5441 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5442 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5443 // have type pointer to function".
5444 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5446 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5447 << Fn->getType() << Fn->getSourceRange());
5448 } else if (const BlockPointerType *BPT =
5449 Fn->getType()->getAs<BlockPointerType>()) {
5450 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5452 // Handle calls to expressions of unknown-any type.
5453 if (Fn->getType() == Context.UnknownAnyTy) {
5454 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5455 if (rewrite.isInvalid()) return ExprError();
5457 TheCall->setCallee(Fn);
5461 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5462 << Fn->getType() << Fn->getSourceRange());
5465 if (getLangOpts().CUDA) {
5467 // CUDA: Kernel calls must be to global functions
5468 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5469 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5470 << FDecl->getName() << Fn->getSourceRange());
5472 // CUDA: Kernel function must have 'void' return type
5473 if (!FuncT->getReturnType()->isVoidType())
5474 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5475 << Fn->getType() << Fn->getSourceRange());
5477 // CUDA: Calls to global functions must be configured
5478 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5479 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5480 << FDecl->getName() << Fn->getSourceRange());
5484 // Check for a valid return type
5485 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5489 // We know the result type of the call, set it.
5490 TheCall->setType(FuncT->getCallResultType(Context));
5491 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5493 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5495 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5499 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5502 // Check if we have too few/too many template arguments, based
5503 // on our knowledge of the function definition.
5504 const FunctionDecl *Def = nullptr;
5505 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5506 Proto = Def->getType()->getAs<FunctionProtoType>();
5507 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5508 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5509 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5512 // If the function we're calling isn't a function prototype, but we have
5513 // a function prototype from a prior declaratiom, use that prototype.
5514 if (!FDecl->hasPrototype())
5515 Proto = FDecl->getType()->getAs<FunctionProtoType>();
5518 // Promote the arguments (C99 6.5.2.2p6).
5519 for (unsigned i = 0, e = Args.size(); i != e; i++) {
5520 Expr *Arg = Args[i];
5522 if (Proto && i < Proto->getNumParams()) {
5523 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5524 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5526 PerformCopyInitialization(Entity, SourceLocation(), Arg);
5527 if (ArgE.isInvalid())
5530 Arg = ArgE.getAs<Expr>();
5533 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5535 if (ArgE.isInvalid())
5538 Arg = ArgE.getAs<Expr>();
5541 if (RequireCompleteType(Arg->getLocStart(),
5543 diag::err_call_incomplete_argument, Arg))
5546 TheCall->setArg(i, Arg);
5550 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5551 if (!Method->isStatic())
5552 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5553 << Fn->getSourceRange());
5555 // Check for sentinels
5557 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5559 // Do special checking on direct calls to functions.
5561 if (CheckFunctionCall(FDecl, TheCall, Proto))
5565 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5567 if (CheckPointerCall(NDecl, TheCall, Proto))
5570 if (CheckOtherCall(TheCall, Proto))
5574 return MaybeBindToTemporary(TheCall);
5578 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5579 SourceLocation RParenLoc, Expr *InitExpr) {
5580 assert(Ty && "ActOnCompoundLiteral(): missing type");
5581 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5583 TypeSourceInfo *TInfo;
5584 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5586 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5588 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5592 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5593 SourceLocation RParenLoc, Expr *LiteralExpr) {
5594 QualType literalType = TInfo->getType();
5596 if (literalType->isArrayType()) {
5597 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5598 diag::err_illegal_decl_array_incomplete_type,
5599 SourceRange(LParenLoc,
5600 LiteralExpr->getSourceRange().getEnd())))
5602 if (literalType->isVariableArrayType())
5603 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5604 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5605 } else if (!literalType->isDependentType() &&
5606 RequireCompleteType(LParenLoc, literalType,
5607 diag::err_typecheck_decl_incomplete_type,
5608 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5611 InitializedEntity Entity
5612 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5613 InitializationKind Kind
5614 = InitializationKind::CreateCStyleCast(LParenLoc,
5615 SourceRange(LParenLoc, RParenLoc),
5617 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5618 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5620 if (Result.isInvalid())
5622 LiteralExpr = Result.get();
5624 bool isFileScope = !CurContext->isFunctionOrMethod();
5626 !LiteralExpr->isTypeDependent() &&
5627 !LiteralExpr->isValueDependent() &&
5628 !literalType->isDependentType()) { // 6.5.2.5p3
5629 if (CheckForConstantInitializer(LiteralExpr, literalType))
5633 // In C, compound literals are l-values for some reason.
5634 // For GCC compatibility, in C++, file-scope array compound literals with
5635 // constant initializers are also l-values, and compound literals are
5636 // otherwise prvalues.
5638 // (GCC also treats C++ list-initialized file-scope array prvalues with
5639 // constant initializers as l-values, but that's non-conforming, so we don't
5640 // follow it there.)
5642 // FIXME: It would be better to handle the lvalue cases as materializing and
5643 // lifetime-extending a temporary object, but our materialized temporaries
5644 // representation only supports lifetime extension from a variable, not "out
5646 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5647 // is bound to the result of applying array-to-pointer decay to the compound
5649 // FIXME: GCC supports compound literals of reference type, which should
5650 // obviously have a value kind derived from the kind of reference involved.
5652 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5656 return MaybeBindToTemporary(
5657 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5658 VK, LiteralExpr, isFileScope));
5662 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5663 SourceLocation RBraceLoc) {
5664 // Immediately handle non-overload placeholders. Overloads can be
5665 // resolved contextually, but everything else here can't.
5666 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5667 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5668 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5670 // Ignore failures; dropping the entire initializer list because
5671 // of one failure would be terrible for indexing/etc.
5672 if (result.isInvalid()) continue;
5674 InitArgList[I] = result.get();
5678 // Semantic analysis for initializers is done by ActOnDeclarator() and
5679 // CheckInitializer() - it requires knowledge of the object being intialized.
5681 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5683 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5687 /// Do an explicit extend of the given block pointer if we're in ARC.
5688 void Sema::maybeExtendBlockObject(ExprResult &E) {
5689 assert(E.get()->getType()->isBlockPointerType());
5690 assert(E.get()->isRValue());
5692 // Only do this in an r-value context.
5693 if (!getLangOpts().ObjCAutoRefCount) return;
5695 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5696 CK_ARCExtendBlockObject, E.get(),
5697 /*base path*/ nullptr, VK_RValue);
5698 Cleanup.setExprNeedsCleanups(true);
5701 /// Prepare a conversion of the given expression to an ObjC object
5703 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5704 QualType type = E.get()->getType();
5705 if (type->isObjCObjectPointerType()) {
5707 } else if (type->isBlockPointerType()) {
5708 maybeExtendBlockObject(E);
5709 return CK_BlockPointerToObjCPointerCast;
5711 assert(type->isPointerType());
5712 return CK_CPointerToObjCPointerCast;
5716 /// Prepares for a scalar cast, performing all the necessary stages
5717 /// except the final cast and returning the kind required.
5718 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5719 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5720 // Also, callers should have filtered out the invalid cases with
5721 // pointers. Everything else should be possible.
5723 QualType SrcTy = Src.get()->getType();
5724 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5727 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5728 case Type::STK_MemberPointer:
5729 llvm_unreachable("member pointer type in C");
5731 case Type::STK_CPointer:
5732 case Type::STK_BlockPointer:
5733 case Type::STK_ObjCObjectPointer:
5734 switch (DestTy->getScalarTypeKind()) {
5735 case Type::STK_CPointer: {
5736 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5737 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5738 if (SrcAS != DestAS)
5739 return CK_AddressSpaceConversion;
5742 case Type::STK_BlockPointer:
5743 return (SrcKind == Type::STK_BlockPointer
5744 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5745 case Type::STK_ObjCObjectPointer:
5746 if (SrcKind == Type::STK_ObjCObjectPointer)
5748 if (SrcKind == Type::STK_CPointer)
5749 return CK_CPointerToObjCPointerCast;
5750 maybeExtendBlockObject(Src);
5751 return CK_BlockPointerToObjCPointerCast;
5752 case Type::STK_Bool:
5753 return CK_PointerToBoolean;
5754 case Type::STK_Integral:
5755 return CK_PointerToIntegral;
5756 case Type::STK_Floating:
5757 case Type::STK_FloatingComplex:
5758 case Type::STK_IntegralComplex:
5759 case Type::STK_MemberPointer:
5760 llvm_unreachable("illegal cast from pointer");
5762 llvm_unreachable("Should have returned before this");
5764 case Type::STK_Bool: // casting from bool is like casting from an integer
5765 case Type::STK_Integral:
5766 switch (DestTy->getScalarTypeKind()) {
5767 case Type::STK_CPointer:
5768 case Type::STK_ObjCObjectPointer:
5769 case Type::STK_BlockPointer:
5770 if (Src.get()->isNullPointerConstant(Context,
5771 Expr::NPC_ValueDependentIsNull))
5772 return CK_NullToPointer;
5773 return CK_IntegralToPointer;
5774 case Type::STK_Bool:
5775 return CK_IntegralToBoolean;
5776 case Type::STK_Integral:
5777 return CK_IntegralCast;
5778 case Type::STK_Floating:
5779 return CK_IntegralToFloating;
5780 case Type::STK_IntegralComplex:
5781 Src = ImpCastExprToType(Src.get(),
5782 DestTy->castAs<ComplexType>()->getElementType(),
5784 return CK_IntegralRealToComplex;
5785 case Type::STK_FloatingComplex:
5786 Src = ImpCastExprToType(Src.get(),
5787 DestTy->castAs<ComplexType>()->getElementType(),
5788 CK_IntegralToFloating);
5789 return CK_FloatingRealToComplex;
5790 case Type::STK_MemberPointer:
5791 llvm_unreachable("member pointer type in C");
5793 llvm_unreachable("Should have returned before this");
5795 case Type::STK_Floating:
5796 switch (DestTy->getScalarTypeKind()) {
5797 case Type::STK_Floating:
5798 return CK_FloatingCast;
5799 case Type::STK_Bool:
5800 return CK_FloatingToBoolean;
5801 case Type::STK_Integral:
5802 return CK_FloatingToIntegral;
5803 case Type::STK_FloatingComplex:
5804 Src = ImpCastExprToType(Src.get(),
5805 DestTy->castAs<ComplexType>()->getElementType(),
5807 return CK_FloatingRealToComplex;
5808 case Type::STK_IntegralComplex:
5809 Src = ImpCastExprToType(Src.get(),
5810 DestTy->castAs<ComplexType>()->getElementType(),
5811 CK_FloatingToIntegral);
5812 return CK_IntegralRealToComplex;
5813 case Type::STK_CPointer:
5814 case Type::STK_ObjCObjectPointer:
5815 case Type::STK_BlockPointer:
5816 llvm_unreachable("valid float->pointer cast?");
5817 case Type::STK_MemberPointer:
5818 llvm_unreachable("member pointer type in C");
5820 llvm_unreachable("Should have returned before this");
5822 case Type::STK_FloatingComplex:
5823 switch (DestTy->getScalarTypeKind()) {
5824 case Type::STK_FloatingComplex:
5825 return CK_FloatingComplexCast;
5826 case Type::STK_IntegralComplex:
5827 return CK_FloatingComplexToIntegralComplex;
5828 case Type::STK_Floating: {
5829 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5830 if (Context.hasSameType(ET, DestTy))
5831 return CK_FloatingComplexToReal;
5832 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5833 return CK_FloatingCast;
5835 case Type::STK_Bool:
5836 return CK_FloatingComplexToBoolean;
5837 case Type::STK_Integral:
5838 Src = ImpCastExprToType(Src.get(),
5839 SrcTy->castAs<ComplexType>()->getElementType(),
5840 CK_FloatingComplexToReal);
5841 return CK_FloatingToIntegral;
5842 case Type::STK_CPointer:
5843 case Type::STK_ObjCObjectPointer:
5844 case Type::STK_BlockPointer:
5845 llvm_unreachable("valid complex float->pointer cast?");
5846 case Type::STK_MemberPointer:
5847 llvm_unreachable("member pointer type in C");
5849 llvm_unreachable("Should have returned before this");
5851 case Type::STK_IntegralComplex:
5852 switch (DestTy->getScalarTypeKind()) {
5853 case Type::STK_FloatingComplex:
5854 return CK_IntegralComplexToFloatingComplex;
5855 case Type::STK_IntegralComplex:
5856 return CK_IntegralComplexCast;
5857 case Type::STK_Integral: {
5858 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5859 if (Context.hasSameType(ET, DestTy))
5860 return CK_IntegralComplexToReal;
5861 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5862 return CK_IntegralCast;
5864 case Type::STK_Bool:
5865 return CK_IntegralComplexToBoolean;
5866 case Type::STK_Floating:
5867 Src = ImpCastExprToType(Src.get(),
5868 SrcTy->castAs<ComplexType>()->getElementType(),
5869 CK_IntegralComplexToReal);
5870 return CK_IntegralToFloating;
5871 case Type::STK_CPointer:
5872 case Type::STK_ObjCObjectPointer:
5873 case Type::STK_BlockPointer:
5874 llvm_unreachable("valid complex int->pointer cast?");
5875 case Type::STK_MemberPointer:
5876 llvm_unreachable("member pointer type in C");
5878 llvm_unreachable("Should have returned before this");
5881 llvm_unreachable("Unhandled scalar cast");
5884 static bool breakDownVectorType(QualType type, uint64_t &len,
5885 QualType &eltType) {
5886 // Vectors are simple.
5887 if (const VectorType *vecType = type->getAs<VectorType>()) {
5888 len = vecType->getNumElements();
5889 eltType = vecType->getElementType();
5890 assert(eltType->isScalarType());
5894 // We allow lax conversion to and from non-vector types, but only if
5895 // they're real types (i.e. non-complex, non-pointer scalar types).
5896 if (!type->isRealType()) return false;
5903 /// Are the two types lax-compatible vector types? That is, given
5904 /// that one of them is a vector, do they have equal storage sizes,
5905 /// where the storage size is the number of elements times the element
5908 /// This will also return false if either of the types is neither a
5909 /// vector nor a real type.
5910 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5911 assert(destTy->isVectorType() || srcTy->isVectorType());
5913 // Disallow lax conversions between scalars and ExtVectors (these
5914 // conversions are allowed for other vector types because common headers
5915 // depend on them). Most scalar OP ExtVector cases are handled by the
5916 // splat path anyway, which does what we want (convert, not bitcast).
5917 // What this rules out for ExtVectors is crazy things like char4*float.
5918 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5919 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5921 uint64_t srcLen, destLen;
5922 QualType srcEltTy, destEltTy;
5923 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5924 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5926 // ASTContext::getTypeSize will return the size rounded up to a
5927 // power of 2, so instead of using that, we need to use the raw
5928 // element size multiplied by the element count.
5929 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5930 uint64_t destEltSize = Context.getTypeSize(destEltTy);
5932 return (srcLen * srcEltSize == destLen * destEltSize);
5935 /// Is this a legal conversion between two types, one of which is
5936 /// known to be a vector type?
5937 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5938 assert(destTy->isVectorType() || srcTy->isVectorType());
5940 if (!Context.getLangOpts().LaxVectorConversions)
5942 return areLaxCompatibleVectorTypes(srcTy, destTy);
5945 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5947 assert(VectorTy->isVectorType() && "Not a vector type!");
5949 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5950 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5951 return Diag(R.getBegin(),
5952 Ty->isVectorType() ?
5953 diag::err_invalid_conversion_between_vectors :
5954 diag::err_invalid_conversion_between_vector_and_integer)
5955 << VectorTy << Ty << R;
5957 return Diag(R.getBegin(),
5958 diag::err_invalid_conversion_between_vector_and_scalar)
5959 << VectorTy << Ty << R;
5965 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5966 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5968 if (DestElemTy == SplattedExpr->getType())
5969 return SplattedExpr;
5971 assert(DestElemTy->isFloatingType() ||
5972 DestElemTy->isIntegralOrEnumerationType());
5975 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5976 // OpenCL requires that we convert `true` boolean expressions to -1, but
5977 // only when splatting vectors.
5978 if (DestElemTy->isFloatingType()) {
5979 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5980 // in two steps: boolean to signed integral, then to floating.
5981 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5982 CK_BooleanToSignedIntegral);
5983 SplattedExpr = CastExprRes.get();
5984 CK = CK_IntegralToFloating;
5986 CK = CK_BooleanToSignedIntegral;
5989 ExprResult CastExprRes = SplattedExpr;
5990 CK = PrepareScalarCast(CastExprRes, DestElemTy);
5991 if (CastExprRes.isInvalid())
5993 SplattedExpr = CastExprRes.get();
5995 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5998 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5999 Expr *CastExpr, CastKind &Kind) {
6000 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6002 QualType SrcTy = CastExpr->getType();
6004 // If SrcTy is a VectorType, the total size must match to explicitly cast to
6005 // an ExtVectorType.
6006 // In OpenCL, casts between vectors of different types are not allowed.
6007 // (See OpenCL 6.2).
6008 if (SrcTy->isVectorType()) {
6009 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6010 || (getLangOpts().OpenCL &&
6011 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6012 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6013 << DestTy << SrcTy << R;
6020 // All non-pointer scalars can be cast to ExtVector type. The appropriate
6021 // conversion will take place first from scalar to elt type, and then
6022 // splat from elt type to vector.
6023 if (SrcTy->isPointerType())
6024 return Diag(R.getBegin(),
6025 diag::err_invalid_conversion_between_vector_and_scalar)
6026 << DestTy << SrcTy << R;
6028 Kind = CK_VectorSplat;
6029 return prepareVectorSplat(DestTy, CastExpr);
6033 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6034 Declarator &D, ParsedType &Ty,
6035 SourceLocation RParenLoc, Expr *CastExpr) {
6036 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6037 "ActOnCastExpr(): missing type or expr");
6039 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6040 if (D.isInvalidType())
6043 if (getLangOpts().CPlusPlus) {
6044 // Check that there are no default arguments (C++ only).
6045 CheckExtraCXXDefaultArguments(D);
6047 // Make sure any TypoExprs have been dealt with.
6048 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6049 if (!Res.isUsable())
6051 CastExpr = Res.get();
6054 checkUnusedDeclAttributes(D);
6056 QualType castType = castTInfo->getType();
6057 Ty = CreateParsedType(castType, castTInfo);
6059 bool isVectorLiteral = false;
6061 // Check for an altivec or OpenCL literal,
6062 // i.e. all the elements are integer constants.
6063 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6064 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6065 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6066 && castType->isVectorType() && (PE || PLE)) {
6067 if (PLE && PLE->getNumExprs() == 0) {
6068 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6071 if (PE || PLE->getNumExprs() == 1) {
6072 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6073 if (!E->getType()->isVectorType())
6074 isVectorLiteral = true;
6077 isVectorLiteral = true;
6080 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6081 // then handle it as such.
6082 if (isVectorLiteral)
6083 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6085 // If the Expr being casted is a ParenListExpr, handle it specially.
6086 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6087 // sequence of BinOp comma operators.
6088 if (isa<ParenListExpr>(CastExpr)) {
6089 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6090 if (Result.isInvalid()) return ExprError();
6091 CastExpr = Result.get();
6094 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6095 !getSourceManager().isInSystemMacro(LParenLoc))
6096 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6098 CheckTollFreeBridgeCast(castType, CastExpr);
6100 CheckObjCBridgeRelatedCast(castType, CastExpr);
6102 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6104 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6107 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6108 SourceLocation RParenLoc, Expr *E,
6109 TypeSourceInfo *TInfo) {
6110 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6111 "Expected paren or paren list expression");
6116 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6117 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6118 LiteralLParenLoc = PE->getLParenLoc();
6119 LiteralRParenLoc = PE->getRParenLoc();
6120 exprs = PE->getExprs();
6121 numExprs = PE->getNumExprs();
6122 } else { // isa<ParenExpr> by assertion at function entrance
6123 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6124 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6125 subExpr = cast<ParenExpr>(E)->getSubExpr();
6130 QualType Ty = TInfo->getType();
6131 assert(Ty->isVectorType() && "Expected vector type");
6133 SmallVector<Expr *, 8> initExprs;
6134 const VectorType *VTy = Ty->getAs<VectorType>();
6135 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6137 // '(...)' form of vector initialization in AltiVec: the number of
6138 // initializers must be one or must match the size of the vector.
6139 // If a single value is specified in the initializer then it will be
6140 // replicated to all the components of the vector
6141 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6142 // The number of initializers must be one or must match the size of the
6143 // vector. If a single value is specified in the initializer then it will
6144 // be replicated to all the components of the vector
6145 if (numExprs == 1) {
6146 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6147 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6148 if (Literal.isInvalid())
6150 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6151 PrepareScalarCast(Literal, ElemTy));
6152 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6154 else if (numExprs < numElems) {
6155 Diag(E->getExprLoc(),
6156 diag::err_incorrect_number_of_vector_initializers);
6160 initExprs.append(exprs, exprs + numExprs);
6163 // For OpenCL, when the number of initializers is a single value,
6164 // it will be replicated to all components of the vector.
6165 if (getLangOpts().OpenCL &&
6166 VTy->getVectorKind() == VectorType::GenericVector &&
6168 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6169 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6170 if (Literal.isInvalid())
6172 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6173 PrepareScalarCast(Literal, ElemTy));
6174 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6177 initExprs.append(exprs, exprs + numExprs);
6179 // FIXME: This means that pretty-printing the final AST will produce curly
6180 // braces instead of the original commas.
6181 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6182 initExprs, LiteralRParenLoc);
6184 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6187 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6188 /// the ParenListExpr into a sequence of comma binary operators.
6190 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6191 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6195 ExprResult Result(E->getExpr(0));
6197 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6198 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6201 if (Result.isInvalid()) return ExprError();
6203 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6206 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6209 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6213 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6214 /// constant and the other is not a pointer. Returns true if a diagnostic is
6216 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6217 SourceLocation QuestionLoc) {
6218 Expr *NullExpr = LHSExpr;
6219 Expr *NonPointerExpr = RHSExpr;
6220 Expr::NullPointerConstantKind NullKind =
6221 NullExpr->isNullPointerConstant(Context,
6222 Expr::NPC_ValueDependentIsNotNull);
6224 if (NullKind == Expr::NPCK_NotNull) {
6226 NonPointerExpr = LHSExpr;
6228 NullExpr->isNullPointerConstant(Context,
6229 Expr::NPC_ValueDependentIsNotNull);
6232 if (NullKind == Expr::NPCK_NotNull)
6235 if (NullKind == Expr::NPCK_ZeroExpression)
6238 if (NullKind == Expr::NPCK_ZeroLiteral) {
6239 // In this case, check to make sure that we got here from a "NULL"
6240 // string in the source code.
6241 NullExpr = NullExpr->IgnoreParenImpCasts();
6242 SourceLocation loc = NullExpr->getExprLoc();
6243 if (!findMacroSpelling(loc, "NULL"))
6247 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6248 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6249 << NonPointerExpr->getType() << DiagType
6250 << NonPointerExpr->getSourceRange();
6254 /// \brief Return false if the condition expression is valid, true otherwise.
6255 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6256 QualType CondTy = Cond->getType();
6258 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6259 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6260 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6261 << CondTy << Cond->getSourceRange();
6266 if (CondTy->isScalarType()) return false;
6268 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6269 << CondTy << Cond->getSourceRange();
6273 /// \brief Handle when one or both operands are void type.
6274 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6276 Expr *LHSExpr = LHS.get();
6277 Expr *RHSExpr = RHS.get();
6279 if (!LHSExpr->getType()->isVoidType())
6280 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6281 << RHSExpr->getSourceRange();
6282 if (!RHSExpr->getType()->isVoidType())
6283 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6284 << LHSExpr->getSourceRange();
6285 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6286 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6287 return S.Context.VoidTy;
6290 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6292 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6293 QualType PointerTy) {
6294 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6295 !NullExpr.get()->isNullPointerConstant(S.Context,
6296 Expr::NPC_ValueDependentIsNull))
6299 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6303 /// \brief Checks compatibility between two pointers and return the resulting
6305 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6307 SourceLocation Loc) {
6308 QualType LHSTy = LHS.get()->getType();
6309 QualType RHSTy = RHS.get()->getType();
6311 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6312 // Two identical pointers types are always compatible.
6316 QualType lhptee, rhptee;
6318 // Get the pointee types.
6319 bool IsBlockPointer = false;
6320 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6321 lhptee = LHSBTy->getPointeeType();
6322 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6323 IsBlockPointer = true;
6325 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6326 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6329 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6330 // differently qualified versions of compatible types, the result type is
6331 // a pointer to an appropriately qualified version of the composite
6334 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6335 // clause doesn't make sense for our extensions. E.g. address space 2 should
6336 // be incompatible with address space 3: they may live on different devices or
6338 Qualifiers lhQual = lhptee.getQualifiers();
6339 Qualifiers rhQual = rhptee.getQualifiers();
6341 unsigned ResultAddrSpace = 0;
6342 unsigned LAddrSpace = lhQual.getAddressSpace();
6343 unsigned RAddrSpace = rhQual.getAddressSpace();
6344 if (S.getLangOpts().OpenCL) {
6345 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6346 // spaces is disallowed.
6347 if (lhQual.isAddressSpaceSupersetOf(rhQual))
6348 ResultAddrSpace = LAddrSpace;
6349 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6350 ResultAddrSpace = RAddrSpace;
6353 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6354 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6355 << RHS.get()->getSourceRange();
6360 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6361 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6362 lhQual.removeCVRQualifiers();
6363 rhQual.removeCVRQualifiers();
6365 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6366 // (C99 6.7.3) for address spaces. We assume that the check should behave in
6367 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6368 // qual types are compatible iff
6369 // * corresponded types are compatible
6370 // * CVR qualifiers are equal
6371 // * address spaces are equal
6372 // Thus for conditional operator we merge CVR and address space unqualified
6373 // pointees and if there is a composite type we return a pointer to it with
6374 // merged qualifiers.
6375 if (S.getLangOpts().OpenCL) {
6376 LHSCastKind = LAddrSpace == ResultAddrSpace
6378 : CK_AddressSpaceConversion;
6379 RHSCastKind = RAddrSpace == ResultAddrSpace
6381 : CK_AddressSpaceConversion;
6382 lhQual.removeAddressSpace();
6383 rhQual.removeAddressSpace();
6386 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6387 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6389 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6391 if (CompositeTy.isNull()) {
6392 // In this situation, we assume void* type. No especially good
6393 // reason, but this is what gcc does, and we do have to pick
6394 // to get a consistent AST.
6395 QualType incompatTy;
6396 incompatTy = S.Context.getPointerType(
6397 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6398 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6399 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6400 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6401 // for casts between types with incompatible address space qualifiers.
6402 // For the following code the compiler produces casts between global and
6403 // local address spaces of the corresponded innermost pointees:
6404 // local int *global *a;
6405 // global int *global *b;
6406 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6407 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6408 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6409 << RHS.get()->getSourceRange();
6413 // The pointer types are compatible.
6414 // In case of OpenCL ResultTy should have the address space qualifier
6415 // which is a superset of address spaces of both the 2nd and the 3rd
6416 // operands of the conditional operator.
6417 QualType ResultTy = [&, ResultAddrSpace]() {
6418 if (S.getLangOpts().OpenCL) {
6419 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6420 CompositeQuals.setAddressSpace(ResultAddrSpace);
6422 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6423 .withCVRQualifiers(MergedCVRQual);
6425 return CompositeTy.withCVRQualifiers(MergedCVRQual);
6428 ResultTy = S.Context.getBlockPointerType(ResultTy);
6430 ResultTy = S.Context.getPointerType(ResultTy);
6433 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6434 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6438 /// \brief Return the resulting type when the operands are both block pointers.
6439 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6442 SourceLocation Loc) {
6443 QualType LHSTy = LHS.get()->getType();
6444 QualType RHSTy = RHS.get()->getType();
6446 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6447 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6448 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6449 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6450 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6453 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6454 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6455 << RHS.get()->getSourceRange();
6459 // We have 2 block pointer types.
6460 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6463 /// \brief Return the resulting type when the operands are both pointers.
6465 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6467 SourceLocation Loc) {
6468 // get the pointer types
6469 QualType LHSTy = LHS.get()->getType();
6470 QualType RHSTy = RHS.get()->getType();
6472 // get the "pointed to" types
6473 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6474 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6476 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6477 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6478 // Figure out necessary qualifiers (C99 6.5.15p6)
6479 QualType destPointee
6480 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6481 QualType destType = S.Context.getPointerType(destPointee);
6482 // Add qualifiers if necessary.
6483 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6484 // Promote to void*.
6485 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6488 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6489 QualType destPointee
6490 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6491 QualType destType = S.Context.getPointerType(destPointee);
6492 // Add qualifiers if necessary.
6493 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6494 // Promote to void*.
6495 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6499 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6502 /// \brief Return false if the first expression is not an integer and the second
6503 /// expression is not a pointer, true otherwise.
6504 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6505 Expr* PointerExpr, SourceLocation Loc,
6506 bool IsIntFirstExpr) {
6507 if (!PointerExpr->getType()->isPointerType() ||
6508 !Int.get()->getType()->isIntegerType())
6511 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6512 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6514 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6515 << Expr1->getType() << Expr2->getType()
6516 << Expr1->getSourceRange() << Expr2->getSourceRange();
6517 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6518 CK_IntegralToPointer);
6522 /// \brief Simple conversion between integer and floating point types.
6524 /// Used when handling the OpenCL conditional operator where the
6525 /// condition is a vector while the other operands are scalar.
6527 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6528 /// types are either integer or floating type. Between the two
6529 /// operands, the type with the higher rank is defined as the "result
6530 /// type". The other operand needs to be promoted to the same type. No
6531 /// other type promotion is allowed. We cannot use
6532 /// UsualArithmeticConversions() for this purpose, since it always
6533 /// promotes promotable types.
6534 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6536 SourceLocation QuestionLoc) {
6537 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6538 if (LHS.isInvalid())
6540 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6541 if (RHS.isInvalid())
6544 // For conversion purposes, we ignore any qualifiers.
6545 // For example, "const float" and "float" are equivalent.
6547 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6549 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6551 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6552 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6553 << LHSType << LHS.get()->getSourceRange();
6557 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6558 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6559 << RHSType << RHS.get()->getSourceRange();
6563 // If both types are identical, no conversion is needed.
6564 if (LHSType == RHSType)
6567 // Now handle "real" floating types (i.e. float, double, long double).
6568 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6569 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6570 /*IsCompAssign = */ false);
6572 // Finally, we have two differing integer types.
6573 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6574 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6577 /// \brief Convert scalar operands to a vector that matches the
6578 /// condition in length.
6580 /// Used when handling the OpenCL conditional operator where the
6581 /// condition is a vector while the other operands are scalar.
6583 /// We first compute the "result type" for the scalar operands
6584 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6585 /// into a vector of that type where the length matches the condition
6586 /// vector type. s6.11.6 requires that the element types of the result
6587 /// and the condition must have the same number of bits.
6589 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6590 QualType CondTy, SourceLocation QuestionLoc) {
6591 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6592 if (ResTy.isNull()) return QualType();
6594 const VectorType *CV = CondTy->getAs<VectorType>();
6597 // Determine the vector result type
6598 unsigned NumElements = CV->getNumElements();
6599 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6601 // Ensure that all types have the same number of bits
6602 if (S.Context.getTypeSize(CV->getElementType())
6603 != S.Context.getTypeSize(ResTy)) {
6604 // Since VectorTy is created internally, it does not pretty print
6605 // with an OpenCL name. Instead, we just print a description.
6606 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6607 SmallString<64> Str;
6608 llvm::raw_svector_ostream OS(Str);
6609 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6610 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6611 << CondTy << OS.str();
6615 // Convert operands to the vector result type
6616 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6617 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6622 /// \brief Return false if this is a valid OpenCL condition vector
6623 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6624 SourceLocation QuestionLoc) {
6625 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6627 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6629 QualType EleTy = CondTy->getElementType();
6630 if (EleTy->isIntegerType()) return false;
6632 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6633 << Cond->getType() << Cond->getSourceRange();
6637 /// \brief Return false if the vector condition type and the vector
6638 /// result type are compatible.
6640 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6641 /// number of elements, and their element types have the same number
6643 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6644 SourceLocation QuestionLoc) {
6645 const VectorType *CV = CondTy->getAs<VectorType>();
6646 const VectorType *RV = VecResTy->getAs<VectorType>();
6649 if (CV->getNumElements() != RV->getNumElements()) {
6650 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6651 << CondTy << VecResTy;
6655 QualType CVE = CV->getElementType();
6656 QualType RVE = RV->getElementType();
6658 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6659 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6660 << CondTy << VecResTy;
6667 /// \brief Return the resulting type for the conditional operator in
6668 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6669 /// s6.3.i) when the condition is a vector type.
6671 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6672 ExprResult &LHS, ExprResult &RHS,
6673 SourceLocation QuestionLoc) {
6674 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6675 if (Cond.isInvalid())
6677 QualType CondTy = Cond.get()->getType();
6679 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6682 // If either operand is a vector then find the vector type of the
6683 // result as specified in OpenCL v1.1 s6.3.i.
6684 if (LHS.get()->getType()->isVectorType() ||
6685 RHS.get()->getType()->isVectorType()) {
6686 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6687 /*isCompAssign*/false,
6688 /*AllowBothBool*/true,
6689 /*AllowBoolConversions*/false);
6690 if (VecResTy.isNull()) return QualType();
6691 // The result type must match the condition type as specified in
6692 // OpenCL v1.1 s6.11.6.
6693 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6698 // Both operands are scalar.
6699 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6702 /// \brief Return true if the Expr is block type
6703 static bool checkBlockType(Sema &S, const Expr *E) {
6704 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6705 QualType Ty = CE->getCallee()->getType();
6706 if (Ty->isBlockPointerType()) {
6707 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6714 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6715 /// In that case, LHS = cond.
6717 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6718 ExprResult &RHS, ExprValueKind &VK,
6720 SourceLocation QuestionLoc) {
6722 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6723 if (!LHSResult.isUsable()) return QualType();
6726 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6727 if (!RHSResult.isUsable()) return QualType();
6730 // C++ is sufficiently different to merit its own checker.
6731 if (getLangOpts().CPlusPlus)
6732 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6737 // The OpenCL operator with a vector condition is sufficiently
6738 // different to merit its own checker.
6739 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6740 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6742 // First, check the condition.
6743 Cond = UsualUnaryConversions(Cond.get());
6744 if (Cond.isInvalid())
6746 if (checkCondition(*this, Cond.get(), QuestionLoc))
6749 // Now check the two expressions.
6750 if (LHS.get()->getType()->isVectorType() ||
6751 RHS.get()->getType()->isVectorType())
6752 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6753 /*AllowBothBool*/true,
6754 /*AllowBoolConversions*/false);
6756 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6757 if (LHS.isInvalid() || RHS.isInvalid())
6760 QualType LHSTy = LHS.get()->getType();
6761 QualType RHSTy = RHS.get()->getType();
6763 // Diagnose attempts to convert between __float128 and long double where
6764 // such conversions currently can't be handled.
6765 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6767 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6768 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6772 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6773 // selection operator (?:).
6774 if (getLangOpts().OpenCL &&
6775 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6779 // If both operands have arithmetic type, do the usual arithmetic conversions
6780 // to find a common type: C99 6.5.15p3,5.
6781 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6782 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6783 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6788 // If both operands are the same structure or union type, the result is that
6790 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6791 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6792 if (LHSRT->getDecl() == RHSRT->getDecl())
6793 // "If both the operands have structure or union type, the result has
6794 // that type." This implies that CV qualifiers are dropped.
6795 return LHSTy.getUnqualifiedType();
6796 // FIXME: Type of conditional expression must be complete in C mode.
6799 // C99 6.5.15p5: "If both operands have void type, the result has void type."
6800 // The following || allows only one side to be void (a GCC-ism).
6801 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6802 return checkConditionalVoidType(*this, LHS, RHS);
6805 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6806 // the type of the other operand."
6807 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6808 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6810 // All objective-c pointer type analysis is done here.
6811 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6813 if (LHS.isInvalid() || RHS.isInvalid())
6815 if (!compositeType.isNull())
6816 return compositeType;
6819 // Handle block pointer types.
6820 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6821 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6824 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6825 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6826 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6829 // GCC compatibility: soften pointer/integer mismatch. Note that
6830 // null pointers have been filtered out by this point.
6831 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6832 /*isIntFirstExpr=*/true))
6834 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6835 /*isIntFirstExpr=*/false))
6838 // Emit a better diagnostic if one of the expressions is a null pointer
6839 // constant and the other is not a pointer type. In this case, the user most
6840 // likely forgot to take the address of the other expression.
6841 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6844 // Otherwise, the operands are not compatible.
6845 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6846 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6847 << RHS.get()->getSourceRange();
6851 /// FindCompositeObjCPointerType - Helper method to find composite type of
6852 /// two objective-c pointer types of the two input expressions.
6853 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6854 SourceLocation QuestionLoc) {
6855 QualType LHSTy = LHS.get()->getType();
6856 QualType RHSTy = RHS.get()->getType();
6858 // Handle things like Class and struct objc_class*. Here we case the result
6859 // to the pseudo-builtin, because that will be implicitly cast back to the
6860 // redefinition type if an attempt is made to access its fields.
6861 if (LHSTy->isObjCClassType() &&
6862 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6863 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6866 if (RHSTy->isObjCClassType() &&
6867 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6868 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6871 // And the same for struct objc_object* / id
6872 if (LHSTy->isObjCIdType() &&
6873 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6874 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6877 if (RHSTy->isObjCIdType() &&
6878 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6879 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6882 // And the same for struct objc_selector* / SEL
6883 if (Context.isObjCSelType(LHSTy) &&
6884 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6885 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6888 if (Context.isObjCSelType(RHSTy) &&
6889 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6890 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6893 // Check constraints for Objective-C object pointers types.
6894 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6896 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6897 // Two identical object pointer types are always compatible.
6900 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6901 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6902 QualType compositeType = LHSTy;
6904 // If both operands are interfaces and either operand can be
6905 // assigned to the other, use that type as the composite
6906 // type. This allows
6907 // xxx ? (A*) a : (B*) b
6908 // where B is a subclass of A.
6910 // Additionally, as for assignment, if either type is 'id'
6911 // allow silent coercion. Finally, if the types are
6912 // incompatible then make sure to use 'id' as the composite
6913 // type so the result is acceptable for sending messages to.
6915 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6916 // It could return the composite type.
6917 if (!(compositeType =
6918 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6919 // Nothing more to do.
6920 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6921 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6922 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6923 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6924 } else if ((LHSTy->isObjCQualifiedIdType() ||
6925 RHSTy->isObjCQualifiedIdType()) &&
6926 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6927 // Need to handle "id<xx>" explicitly.
6928 // GCC allows qualified id and any Objective-C type to devolve to
6929 // id. Currently localizing to here until clear this should be
6930 // part of ObjCQualifiedIdTypesAreCompatible.
6931 compositeType = Context.getObjCIdType();
6932 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6933 compositeType = Context.getObjCIdType();
6935 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6937 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6938 QualType incompatTy = Context.getObjCIdType();
6939 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6940 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6943 // The object pointer types are compatible.
6944 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6945 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6946 return compositeType;
6948 // Check Objective-C object pointer types and 'void *'
6949 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6950 if (getLangOpts().ObjCAutoRefCount) {
6951 // ARC forbids the implicit conversion of object pointers to 'void *',
6952 // so these types are not compatible.
6953 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6954 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6958 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6959 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6960 QualType destPointee
6961 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6962 QualType destType = Context.getPointerType(destPointee);
6963 // Add qualifiers if necessary.
6964 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6965 // Promote to void*.
6966 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6969 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6970 if (getLangOpts().ObjCAutoRefCount) {
6971 // ARC forbids the implicit conversion of object pointers to 'void *',
6972 // so these types are not compatible.
6973 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6974 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6978 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6979 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6980 QualType destPointee
6981 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6982 QualType destType = Context.getPointerType(destPointee);
6983 // Add qualifiers if necessary.
6984 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6985 // Promote to void*.
6986 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6992 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6993 /// ParenRange in parentheses.
6994 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6995 const PartialDiagnostic &Note,
6996 SourceRange ParenRange) {
6997 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6998 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7000 Self.Diag(Loc, Note)
7001 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7002 << FixItHint::CreateInsertion(EndLoc, ")");
7004 // We can't display the parentheses, so just show the bare note.
7005 Self.Diag(Loc, Note) << ParenRange;
7009 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7010 return BinaryOperator::isAdditiveOp(Opc) ||
7011 BinaryOperator::isMultiplicativeOp(Opc) ||
7012 BinaryOperator::isShiftOp(Opc);
7015 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7016 /// expression, either using a built-in or overloaded operator,
7017 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7019 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7021 // Don't strip parenthesis: we should not warn if E is in parenthesis.
7022 E = E->IgnoreImpCasts();
7023 E = E->IgnoreConversionOperator();
7024 E = E->IgnoreImpCasts();
7026 // Built-in binary operator.
7027 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7028 if (IsArithmeticOp(OP->getOpcode())) {
7029 *Opcode = OP->getOpcode();
7030 *RHSExprs = OP->getRHS();
7035 // Overloaded operator.
7036 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7037 if (Call->getNumArgs() != 2)
7040 // Make sure this is really a binary operator that is safe to pass into
7041 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7042 OverloadedOperatorKind OO = Call->getOperator();
7043 if (OO < OO_Plus || OO > OO_Arrow ||
7044 OO == OO_PlusPlus || OO == OO_MinusMinus)
7047 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7048 if (IsArithmeticOp(OpKind)) {
7050 *RHSExprs = Call->getArg(1);
7058 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7059 /// or is a logical expression such as (x==y) which has int type, but is
7060 /// commonly interpreted as boolean.
7061 static bool ExprLooksBoolean(Expr *E) {
7062 E = E->IgnoreParenImpCasts();
7064 if (E->getType()->isBooleanType())
7066 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7067 return OP->isComparisonOp() || OP->isLogicalOp();
7068 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7069 return OP->getOpcode() == UO_LNot;
7070 if (E->getType()->isPointerType())
7076 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7077 /// and binary operator are mixed in a way that suggests the programmer assumed
7078 /// the conditional operator has higher precedence, for example:
7079 /// "int x = a + someBinaryCondition ? 1 : 2".
7080 static void DiagnoseConditionalPrecedence(Sema &Self,
7081 SourceLocation OpLoc,
7085 BinaryOperatorKind CondOpcode;
7088 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7090 if (!ExprLooksBoolean(CondRHS))
7093 // The condition is an arithmetic binary expression, with a right-
7094 // hand side that looks boolean, so warn.
7096 Self.Diag(OpLoc, diag::warn_precedence_conditional)
7097 << Condition->getSourceRange()
7098 << BinaryOperator::getOpcodeStr(CondOpcode);
7100 SuggestParentheses(Self, OpLoc,
7101 Self.PDiag(diag::note_precedence_silence)
7102 << BinaryOperator::getOpcodeStr(CondOpcode),
7103 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7105 SuggestParentheses(Self, OpLoc,
7106 Self.PDiag(diag::note_precedence_conditional_first),
7107 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7110 /// Compute the nullability of a conditional expression.
7111 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7112 QualType LHSTy, QualType RHSTy,
7114 if (!ResTy->isAnyPointerType())
7117 auto GetNullability = [&Ctx](QualType Ty) {
7118 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7121 return NullabilityKind::Unspecified;
7124 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7125 NullabilityKind MergedKind;
7127 // Compute nullability of a binary conditional expression.
7129 if (LHSKind == NullabilityKind::NonNull)
7130 MergedKind = NullabilityKind::NonNull;
7132 MergedKind = RHSKind;
7133 // Compute nullability of a normal conditional expression.
7135 if (LHSKind == NullabilityKind::Nullable ||
7136 RHSKind == NullabilityKind::Nullable)
7137 MergedKind = NullabilityKind::Nullable;
7138 else if (LHSKind == NullabilityKind::NonNull)
7139 MergedKind = RHSKind;
7140 else if (RHSKind == NullabilityKind::NonNull)
7141 MergedKind = LHSKind;
7143 MergedKind = NullabilityKind::Unspecified;
7146 // Return if ResTy already has the correct nullability.
7147 if (GetNullability(ResTy) == MergedKind)
7150 // Strip all nullability from ResTy.
7151 while (ResTy->getNullability(Ctx))
7152 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7154 // Create a new AttributedType with the new nullability kind.
7155 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7156 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7159 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7160 /// in the case of a the GNU conditional expr extension.
7161 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7162 SourceLocation ColonLoc,
7163 Expr *CondExpr, Expr *LHSExpr,
7165 if (!getLangOpts().CPlusPlus) {
7166 // C cannot handle TypoExpr nodes in the condition because it
7167 // doesn't handle dependent types properly, so make sure any TypoExprs have
7168 // been dealt with before checking the operands.
7169 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7170 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7171 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7173 if (!CondResult.isUsable())
7177 if (!LHSResult.isUsable())
7181 if (!RHSResult.isUsable())
7184 CondExpr = CondResult.get();
7185 LHSExpr = LHSResult.get();
7186 RHSExpr = RHSResult.get();
7189 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7190 // was the condition.
7191 OpaqueValueExpr *opaqueValue = nullptr;
7192 Expr *commonExpr = nullptr;
7194 commonExpr = CondExpr;
7195 // Lower out placeholder types first. This is important so that we don't
7196 // try to capture a placeholder. This happens in few cases in C++; such
7197 // as Objective-C++'s dictionary subscripting syntax.
7198 if (commonExpr->hasPlaceholderType()) {
7199 ExprResult result = CheckPlaceholderExpr(commonExpr);
7200 if (!result.isUsable()) return ExprError();
7201 commonExpr = result.get();
7203 // We usually want to apply unary conversions *before* saving, except
7204 // in the special case of a C++ l-value conditional.
7205 if (!(getLangOpts().CPlusPlus
7206 && !commonExpr->isTypeDependent()
7207 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7208 && commonExpr->isGLValue()
7209 && commonExpr->isOrdinaryOrBitFieldObject()
7210 && RHSExpr->isOrdinaryOrBitFieldObject()
7211 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7212 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7213 if (commonRes.isInvalid())
7215 commonExpr = commonRes.get();
7218 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7219 commonExpr->getType(),
7220 commonExpr->getValueKind(),
7221 commonExpr->getObjectKind(),
7223 LHSExpr = CondExpr = opaqueValue;
7226 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7227 ExprValueKind VK = VK_RValue;
7228 ExprObjectKind OK = OK_Ordinary;
7229 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7230 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7231 VK, OK, QuestionLoc);
7232 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7236 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7239 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7241 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7245 return new (Context)
7246 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7247 RHS.get(), result, VK, OK);
7249 return new (Context) BinaryConditionalOperator(
7250 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7251 ColonLoc, result, VK, OK);
7254 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7255 // being closely modeled after the C99 spec:-). The odd characteristic of this
7256 // routine is it effectively iqnores the qualifiers on the top level pointee.
7257 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7258 // FIXME: add a couple examples in this comment.
7259 static Sema::AssignConvertType
7260 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7261 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7262 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7264 // get the "pointed to" type (ignoring qualifiers at the top level)
7265 const Type *lhptee, *rhptee;
7266 Qualifiers lhq, rhq;
7267 std::tie(lhptee, lhq) =
7268 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7269 std::tie(rhptee, rhq) =
7270 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7272 Sema::AssignConvertType ConvTy = Sema::Compatible;
7274 // C99 6.5.16.1p1: This following citation is common to constraints
7275 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7276 // qualifiers of the type *pointed to* by the right;
7278 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7279 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7280 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7281 // Ignore lifetime for further calculation.
7282 lhq.removeObjCLifetime();
7283 rhq.removeObjCLifetime();
7286 if (!lhq.compatiblyIncludes(rhq)) {
7287 // Treat address-space mismatches as fatal. TODO: address subspaces
7288 if (!lhq.isAddressSpaceSupersetOf(rhq))
7289 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7291 // It's okay to add or remove GC or lifetime qualifiers when converting to
7293 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7294 .compatiblyIncludes(
7295 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7296 && (lhptee->isVoidType() || rhptee->isVoidType()))
7299 // Treat lifetime mismatches as fatal.
7300 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7301 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7303 // For GCC/MS compatibility, other qualifier mismatches are treated
7304 // as still compatible in C.
7305 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7308 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7309 // incomplete type and the other is a pointer to a qualified or unqualified
7310 // version of void...
7311 if (lhptee->isVoidType()) {
7312 if (rhptee->isIncompleteOrObjectType())
7315 // As an extension, we allow cast to/from void* to function pointer.
7316 assert(rhptee->isFunctionType());
7317 return Sema::FunctionVoidPointer;
7320 if (rhptee->isVoidType()) {
7321 if (lhptee->isIncompleteOrObjectType())
7324 // As an extension, we allow cast to/from void* to function pointer.
7325 assert(lhptee->isFunctionType());
7326 return Sema::FunctionVoidPointer;
7329 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7330 // unqualified versions of compatible types, ...
7331 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7332 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7333 // Check if the pointee types are compatible ignoring the sign.
7334 // We explicitly check for char so that we catch "char" vs
7335 // "unsigned char" on systems where "char" is unsigned.
7336 if (lhptee->isCharType())
7337 ltrans = S.Context.UnsignedCharTy;
7338 else if (lhptee->hasSignedIntegerRepresentation())
7339 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7341 if (rhptee->isCharType())
7342 rtrans = S.Context.UnsignedCharTy;
7343 else if (rhptee->hasSignedIntegerRepresentation())
7344 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7346 if (ltrans == rtrans) {
7347 // Types are compatible ignoring the sign. Qualifier incompatibility
7348 // takes priority over sign incompatibility because the sign
7349 // warning can be disabled.
7350 if (ConvTy != Sema::Compatible)
7353 return Sema::IncompatiblePointerSign;
7356 // If we are a multi-level pointer, it's possible that our issue is simply
7357 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7358 // the eventual target type is the same and the pointers have the same
7359 // level of indirection, this must be the issue.
7360 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7362 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7363 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7364 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7366 if (lhptee == rhptee)
7367 return Sema::IncompatibleNestedPointerQualifiers;
7370 // General pointer incompatibility takes priority over qualifiers.
7371 return Sema::IncompatiblePointer;
7373 if (!S.getLangOpts().CPlusPlus &&
7374 S.IsFunctionConversion(ltrans, rtrans, ltrans))
7375 return Sema::IncompatiblePointer;
7379 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7380 /// block pointer types are compatible or whether a block and normal pointer
7381 /// are compatible. It is more restrict than comparing two function pointer
7383 static Sema::AssignConvertType
7384 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7386 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7387 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7389 QualType lhptee, rhptee;
7391 // get the "pointed to" type (ignoring qualifiers at the top level)
7392 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7393 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7395 // In C++, the types have to match exactly.
7396 if (S.getLangOpts().CPlusPlus)
7397 return Sema::IncompatibleBlockPointer;
7399 Sema::AssignConvertType ConvTy = Sema::Compatible;
7401 // For blocks we enforce that qualifiers are identical.
7402 Qualifiers LQuals = lhptee.getLocalQualifiers();
7403 Qualifiers RQuals = rhptee.getLocalQualifiers();
7404 if (S.getLangOpts().OpenCL) {
7405 LQuals.removeAddressSpace();
7406 RQuals.removeAddressSpace();
7408 if (LQuals != RQuals)
7409 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7411 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7413 // The current behavior is similar to C++ lambdas. A block might be
7414 // assigned to a variable iff its return type and parameters are compatible
7415 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7416 // an assignment. Presumably it should behave in way that a function pointer
7417 // assignment does in C, so for each parameter and return type:
7418 // * CVR and address space of LHS should be a superset of CVR and address
7420 // * unqualified types should be compatible.
7421 if (S.getLangOpts().OpenCL) {
7422 if (!S.Context.typesAreBlockPointerCompatible(
7423 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7424 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7425 return Sema::IncompatibleBlockPointer;
7426 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7427 return Sema::IncompatibleBlockPointer;
7432 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7433 /// for assignment compatibility.
7434 static Sema::AssignConvertType
7435 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7437 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7438 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7440 if (LHSType->isObjCBuiltinType()) {
7441 // Class is not compatible with ObjC object pointers.
7442 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7443 !RHSType->isObjCQualifiedClassType())
7444 return Sema::IncompatiblePointer;
7445 return Sema::Compatible;
7447 if (RHSType->isObjCBuiltinType()) {
7448 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7449 !LHSType->isObjCQualifiedClassType())
7450 return Sema::IncompatiblePointer;
7451 return Sema::Compatible;
7453 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7454 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7456 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7457 // make an exception for id<P>
7458 !LHSType->isObjCQualifiedIdType())
7459 return Sema::CompatiblePointerDiscardsQualifiers;
7461 if (S.Context.typesAreCompatible(LHSType, RHSType))
7462 return Sema::Compatible;
7463 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7464 return Sema::IncompatibleObjCQualifiedId;
7465 return Sema::IncompatiblePointer;
7468 Sema::AssignConvertType
7469 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7470 QualType LHSType, QualType RHSType) {
7471 // Fake up an opaque expression. We don't actually care about what
7472 // cast operations are required, so if CheckAssignmentConstraints
7473 // adds casts to this they'll be wasted, but fortunately that doesn't
7474 // usually happen on valid code.
7475 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7476 ExprResult RHSPtr = &RHSExpr;
7477 CastKind K = CK_Invalid;
7479 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7482 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7483 /// has code to accommodate several GCC extensions when type checking
7484 /// pointers. Here are some objectionable examples that GCC considers warnings:
7488 /// struct foo *pfoo;
7490 /// pint = pshort; // warning: assignment from incompatible pointer type
7491 /// a = pint; // warning: assignment makes integer from pointer without a cast
7492 /// pint = a; // warning: assignment makes pointer from integer without a cast
7493 /// pint = pfoo; // warning: assignment from incompatible pointer type
7495 /// As a result, the code for dealing with pointers is more complex than the
7496 /// C99 spec dictates.
7498 /// Sets 'Kind' for any result kind except Incompatible.
7499 Sema::AssignConvertType
7500 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7501 CastKind &Kind, bool ConvertRHS) {
7502 QualType RHSType = RHS.get()->getType();
7503 QualType OrigLHSType = LHSType;
7505 // Get canonical types. We're not formatting these types, just comparing
7507 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7508 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7510 // Common case: no conversion required.
7511 if (LHSType == RHSType) {
7516 // If we have an atomic type, try a non-atomic assignment, then just add an
7517 // atomic qualification step.
7518 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7519 Sema::AssignConvertType result =
7520 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7521 if (result != Compatible)
7523 if (Kind != CK_NoOp && ConvertRHS)
7524 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7525 Kind = CK_NonAtomicToAtomic;
7529 // If the left-hand side is a reference type, then we are in a
7530 // (rare!) case where we've allowed the use of references in C,
7531 // e.g., as a parameter type in a built-in function. In this case,
7532 // just make sure that the type referenced is compatible with the
7533 // right-hand side type. The caller is responsible for adjusting
7534 // LHSType so that the resulting expression does not have reference
7536 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7537 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7538 Kind = CK_LValueBitCast;
7541 return Incompatible;
7544 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7545 // to the same ExtVector type.
7546 if (LHSType->isExtVectorType()) {
7547 if (RHSType->isExtVectorType())
7548 return Incompatible;
7549 if (RHSType->isArithmeticType()) {
7550 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7552 RHS = prepareVectorSplat(LHSType, RHS.get());
7553 Kind = CK_VectorSplat;
7558 // Conversions to or from vector type.
7559 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7560 if (LHSType->isVectorType() && RHSType->isVectorType()) {
7561 // Allow assignments of an AltiVec vector type to an equivalent GCC
7562 // vector type and vice versa
7563 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7568 // If we are allowing lax vector conversions, and LHS and RHS are both
7569 // vectors, the total size only needs to be the same. This is a bitcast;
7570 // no bits are changed but the result type is different.
7571 if (isLaxVectorConversion(RHSType, LHSType)) {
7573 return IncompatibleVectors;
7577 // When the RHS comes from another lax conversion (e.g. binops between
7578 // scalars and vectors) the result is canonicalized as a vector. When the
7579 // LHS is also a vector, the lax is allowed by the condition above. Handle
7580 // the case where LHS is a scalar.
7581 if (LHSType->isScalarType()) {
7582 const VectorType *VecType = RHSType->getAs<VectorType>();
7583 if (VecType && VecType->getNumElements() == 1 &&
7584 isLaxVectorConversion(RHSType, LHSType)) {
7585 ExprResult *VecExpr = &RHS;
7586 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7592 return Incompatible;
7595 // Diagnose attempts to convert between __float128 and long double where
7596 // such conversions currently can't be handled.
7597 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7598 return Incompatible;
7600 // Arithmetic conversions.
7601 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7602 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7604 Kind = PrepareScalarCast(RHS, LHSType);
7608 // Conversions to normal pointers.
7609 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7611 if (isa<PointerType>(RHSType)) {
7612 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7613 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7614 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7615 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7619 if (RHSType->isIntegerType()) {
7620 Kind = CK_IntegralToPointer; // FIXME: null?
7621 return IntToPointer;
7624 // C pointers are not compatible with ObjC object pointers,
7625 // with two exceptions:
7626 if (isa<ObjCObjectPointerType>(RHSType)) {
7627 // - conversions to void*
7628 if (LHSPointer->getPointeeType()->isVoidType()) {
7633 // - conversions from 'Class' to the redefinition type
7634 if (RHSType->isObjCClassType() &&
7635 Context.hasSameType(LHSType,
7636 Context.getObjCClassRedefinitionType())) {
7642 return IncompatiblePointer;
7646 if (RHSType->getAs<BlockPointerType>()) {
7647 if (LHSPointer->getPointeeType()->isVoidType()) {
7648 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7649 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7653 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7658 return Incompatible;
7661 // Conversions to block pointers.
7662 if (isa<BlockPointerType>(LHSType)) {
7664 if (RHSType->isBlockPointerType()) {
7665 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7668 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7671 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7672 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7675 // int or null -> T^
7676 if (RHSType->isIntegerType()) {
7677 Kind = CK_IntegralToPointer; // FIXME: null
7678 return IntToBlockPointer;
7682 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7683 Kind = CK_AnyPointerToBlockPointerCast;
7688 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7689 if (RHSPT->getPointeeType()->isVoidType()) {
7690 Kind = CK_AnyPointerToBlockPointerCast;
7694 return Incompatible;
7697 // Conversions to Objective-C pointers.
7698 if (isa<ObjCObjectPointerType>(LHSType)) {
7700 if (RHSType->isObjCObjectPointerType()) {
7702 Sema::AssignConvertType result =
7703 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7704 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7705 result == Compatible &&
7706 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7707 result = IncompatibleObjCWeakRef;
7711 // int or null -> A*
7712 if (RHSType->isIntegerType()) {
7713 Kind = CK_IntegralToPointer; // FIXME: null
7714 return IntToPointer;
7717 // In general, C pointers are not compatible with ObjC object pointers,
7718 // with two exceptions:
7719 if (isa<PointerType>(RHSType)) {
7720 Kind = CK_CPointerToObjCPointerCast;
7722 // - conversions from 'void*'
7723 if (RHSType->isVoidPointerType()) {
7727 // - conversions to 'Class' from its redefinition type
7728 if (LHSType->isObjCClassType() &&
7729 Context.hasSameType(RHSType,
7730 Context.getObjCClassRedefinitionType())) {
7734 return IncompatiblePointer;
7737 // Only under strict condition T^ is compatible with an Objective-C pointer.
7738 if (RHSType->isBlockPointerType() &&
7739 LHSType->isBlockCompatibleObjCPointerType(Context)) {
7741 maybeExtendBlockObject(RHS);
7742 Kind = CK_BlockPointerToObjCPointerCast;
7746 return Incompatible;
7749 // Conversions from pointers that are not covered by the above.
7750 if (isa<PointerType>(RHSType)) {
7752 if (LHSType == Context.BoolTy) {
7753 Kind = CK_PointerToBoolean;
7758 if (LHSType->isIntegerType()) {
7759 Kind = CK_PointerToIntegral;
7760 return PointerToInt;
7763 return Incompatible;
7766 // Conversions from Objective-C pointers that are not covered by the above.
7767 if (isa<ObjCObjectPointerType>(RHSType)) {
7769 if (LHSType == Context.BoolTy) {
7770 Kind = CK_PointerToBoolean;
7775 if (LHSType->isIntegerType()) {
7776 Kind = CK_PointerToIntegral;
7777 return PointerToInt;
7780 return Incompatible;
7783 // struct A -> struct B
7784 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7785 if (Context.typesAreCompatible(LHSType, RHSType)) {
7791 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7792 Kind = CK_IntToOCLSampler;
7796 return Incompatible;
7799 /// \brief Constructs a transparent union from an expression that is
7800 /// used to initialize the transparent union.
7801 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7802 ExprResult &EResult, QualType UnionType,
7804 // Build an initializer list that designates the appropriate member
7805 // of the transparent union.
7806 Expr *E = EResult.get();
7807 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7808 E, SourceLocation());
7809 Initializer->setType(UnionType);
7810 Initializer->setInitializedFieldInUnion(Field);
7812 // Build a compound literal constructing a value of the transparent
7813 // union type from this initializer list.
7814 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7815 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7816 VK_RValue, Initializer, false);
7819 Sema::AssignConvertType
7820 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7822 QualType RHSType = RHS.get()->getType();
7824 // If the ArgType is a Union type, we want to handle a potential
7825 // transparent_union GCC extension.
7826 const RecordType *UT = ArgType->getAsUnionType();
7827 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7828 return Incompatible;
7830 // The field to initialize within the transparent union.
7831 RecordDecl *UD = UT->getDecl();
7832 FieldDecl *InitField = nullptr;
7833 // It's compatible if the expression matches any of the fields.
7834 for (auto *it : UD->fields()) {
7835 if (it->getType()->isPointerType()) {
7836 // If the transparent union contains a pointer type, we allow:
7838 // 2) null pointer constant
7839 if (RHSType->isPointerType())
7840 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7841 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7846 if (RHS.get()->isNullPointerConstant(Context,
7847 Expr::NPC_ValueDependentIsNull)) {
7848 RHS = ImpCastExprToType(RHS.get(), it->getType(),
7855 CastKind Kind = CK_Invalid;
7856 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7858 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7865 return Incompatible;
7867 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7871 Sema::AssignConvertType
7872 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7874 bool DiagnoseCFAudited,
7876 // We need to be able to tell the caller whether we diagnosed a problem, if
7877 // they ask us to issue diagnostics.
7878 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7880 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7881 // we can't avoid *all* modifications at the moment, so we need some somewhere
7882 // to put the updated value.
7883 ExprResult LocalRHS = CallerRHS;
7884 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7886 if (getLangOpts().CPlusPlus) {
7887 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7888 // C++ 5.17p3: If the left operand is not of class type, the
7889 // expression is implicitly converted (C++ 4) to the
7890 // cv-unqualified type of the left operand.
7891 QualType RHSType = RHS.get()->getType();
7893 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7896 ImplicitConversionSequence ICS =
7897 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7898 /*SuppressUserConversions=*/false,
7899 /*AllowExplicit=*/false,
7900 /*InOverloadResolution=*/false,
7902 /*AllowObjCWritebackConversion=*/false);
7903 if (ICS.isFailure())
7904 return Incompatible;
7905 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7908 if (RHS.isInvalid())
7909 return Incompatible;
7910 Sema::AssignConvertType result = Compatible;
7911 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7912 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7913 result = IncompatibleObjCWeakRef;
7917 // FIXME: Currently, we fall through and treat C++ classes like C
7919 // FIXME: We also fall through for atomics; not sure what should
7920 // happen there, though.
7921 } else if (RHS.get()->getType() == Context.OverloadTy) {
7922 // As a set of extensions to C, we support overloading on functions. These
7923 // functions need to be resolved here.
7925 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7926 RHS.get(), LHSType, /*Complain=*/false, DAP))
7927 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7929 return Incompatible;
7932 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7933 // a null pointer constant.
7934 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7935 LHSType->isBlockPointerType()) &&
7936 RHS.get()->isNullPointerConstant(Context,
7937 Expr::NPC_ValueDependentIsNull)) {
7938 if (Diagnose || ConvertRHS) {
7941 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7942 /*IgnoreBaseAccess=*/false, Diagnose);
7944 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7949 // This check seems unnatural, however it is necessary to ensure the proper
7950 // conversion of functions/arrays. If the conversion were done for all
7951 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7952 // expressions that suppress this implicit conversion (&, sizeof).
7954 // Suppress this for references: C++ 8.5.3p5.
7955 if (!LHSType->isReferenceType()) {
7956 // FIXME: We potentially allocate here even if ConvertRHS is false.
7957 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7958 if (RHS.isInvalid())
7959 return Incompatible;
7962 Expr *PRE = RHS.get()->IgnoreParenCasts();
7963 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7964 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7965 if (PDecl && !PDecl->hasDefinition()) {
7966 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7967 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7971 CastKind Kind = CK_Invalid;
7972 Sema::AssignConvertType result =
7973 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7975 // C99 6.5.16.1p2: The value of the right operand is converted to the
7976 // type of the assignment expression.
7977 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7978 // so that we can use references in built-in functions even in C.
7979 // The getNonReferenceType() call makes sure that the resulting expression
7980 // does not have reference type.
7981 if (result != Incompatible && RHS.get()->getType() != LHSType) {
7982 QualType Ty = LHSType.getNonLValueExprType(Context);
7983 Expr *E = RHS.get();
7985 // Check for various Objective-C errors. If we are not reporting
7986 // diagnostics and just checking for errors, e.g., during overload
7987 // resolution, return Incompatible to indicate the failure.
7988 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7989 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7990 Diagnose, DiagnoseCFAudited) != ACR_okay) {
7992 return Incompatible;
7994 if (getLangOpts().ObjC1 &&
7995 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7996 E->getType(), E, Diagnose) ||
7997 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7999 return Incompatible;
8000 // Replace the expression with a corrected version and continue so we
8001 // can find further errors.
8007 RHS = ImpCastExprToType(E, Ty, Kind);
8012 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8014 Diag(Loc, diag::err_typecheck_invalid_operands)
8015 << LHS.get()->getType() << RHS.get()->getType()
8016 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8020 /// Try to convert a value of non-vector type to a vector type by converting
8021 /// the type to the element type of the vector and then performing a splat.
8022 /// If the language is OpenCL, we only use conversions that promote scalar
8023 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8026 /// \param scalar - if non-null, actually perform the conversions
8027 /// \return true if the operation fails (but without diagnosing the failure)
8028 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8030 QualType vectorEltTy,
8031 QualType vectorTy) {
8032 // The conversion to apply to the scalar before splatting it,
8034 CastKind scalarCast = CK_Invalid;
8036 if (vectorEltTy->isIntegralType(S.Context)) {
8037 if (!scalarTy->isIntegralType(S.Context))
8039 if (S.getLangOpts().OpenCL &&
8040 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8042 scalarCast = CK_IntegralCast;
8043 } else if (vectorEltTy->isRealFloatingType()) {
8044 if (scalarTy->isRealFloatingType()) {
8045 if (S.getLangOpts().OpenCL &&
8046 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8048 scalarCast = CK_FloatingCast;
8050 else if (scalarTy->isIntegralType(S.Context))
8051 scalarCast = CK_IntegralToFloating;
8058 // Adjust scalar if desired.
8060 if (scalarCast != CK_Invalid)
8061 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8062 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8067 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8068 SourceLocation Loc, bool IsCompAssign,
8070 bool AllowBoolConversions) {
8071 if (!IsCompAssign) {
8072 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8073 if (LHS.isInvalid())
8076 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8077 if (RHS.isInvalid())
8080 // For conversion purposes, we ignore any qualifiers.
8081 // For example, "const float" and "float" are equivalent.
8082 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8083 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8085 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8086 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8087 assert(LHSVecType || RHSVecType);
8089 // AltiVec-style "vector bool op vector bool" combinations are allowed
8090 // for some operators but not others.
8091 if (!AllowBothBool &&
8092 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8093 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8094 return InvalidOperands(Loc, LHS, RHS);
8096 // If the vector types are identical, return.
8097 if (Context.hasSameType(LHSType, RHSType))
8100 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8101 if (LHSVecType && RHSVecType &&
8102 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8103 if (isa<ExtVectorType>(LHSVecType)) {
8104 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8109 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8113 // AllowBoolConversions says that bool and non-bool AltiVec vectors
8114 // can be mixed, with the result being the non-bool type. The non-bool
8115 // operand must have integer element type.
8116 if (AllowBoolConversions && LHSVecType && RHSVecType &&
8117 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8118 (Context.getTypeSize(LHSVecType->getElementType()) ==
8119 Context.getTypeSize(RHSVecType->getElementType()))) {
8120 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8121 LHSVecType->getElementType()->isIntegerType() &&
8122 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8123 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8126 if (!IsCompAssign &&
8127 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8128 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8129 RHSVecType->getElementType()->isIntegerType()) {
8130 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8135 // If there's an ext-vector type and a scalar, try to convert the scalar to
8136 // the vector element type and splat.
8137 // FIXME: this should also work for regular vector types as supported in GCC.
8138 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8139 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8140 LHSVecType->getElementType(), LHSType))
8143 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8144 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8145 LHSType, RHSVecType->getElementType(),
8150 // FIXME: The code below also handles conversion between vectors and
8151 // non-scalars, we should break this down into fine grained specific checks
8152 // and emit proper diagnostics.
8153 QualType VecType = LHSVecType ? LHSType : RHSType;
8154 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8155 QualType OtherType = LHSVecType ? RHSType : LHSType;
8156 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8157 if (isLaxVectorConversion(OtherType, VecType)) {
8158 // If we're allowing lax vector conversions, only the total (data) size
8159 // needs to be the same. For non compound assignment, if one of the types is
8160 // scalar, the result is always the vector type.
8161 if (!IsCompAssign) {
8162 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8164 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8165 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8166 // type. Note that this is already done by non-compound assignments in
8167 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8168 // <1 x T> -> T. The result is also a vector type.
8169 } else if (OtherType->isExtVectorType() ||
8170 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8171 ExprResult *RHSExpr = &RHS;
8172 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8177 // Okay, the expression is invalid.
8179 // If there's a non-vector, non-real operand, diagnose that.
8180 if ((!RHSVecType && !RHSType->isRealType()) ||
8181 (!LHSVecType && !LHSType->isRealType())) {
8182 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8183 << LHSType << RHSType
8184 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8188 // OpenCL V1.1 6.2.6.p1:
8189 // If the operands are of more than one vector type, then an error shall
8190 // occur. Implicit conversions between vector types are not permitted, per
8192 if (getLangOpts().OpenCL &&
8193 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8194 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8195 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8200 // Otherwise, use the generic diagnostic.
8201 Diag(Loc, diag::err_typecheck_vector_not_convertable)
8202 << LHSType << RHSType
8203 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8207 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8208 // expression. These are mainly cases where the null pointer is used as an
8209 // integer instead of a pointer.
8210 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8211 SourceLocation Loc, bool IsCompare) {
8212 // The canonical way to check for a GNU null is with isNullPointerConstant,
8213 // but we use a bit of a hack here for speed; this is a relatively
8214 // hot path, and isNullPointerConstant is slow.
8215 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8216 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8218 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8220 // Avoid analyzing cases where the result will either be invalid (and
8221 // diagnosed as such) or entirely valid and not something to warn about.
8222 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8223 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8226 // Comparison operations would not make sense with a null pointer no matter
8227 // what the other expression is.
8229 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8230 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8231 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8235 // The rest of the operations only make sense with a null pointer
8236 // if the other expression is a pointer.
8237 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8238 NonNullType->canDecayToPointerType())
8241 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8242 << LHSNull /* LHS is NULL */ << NonNullType
8243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8246 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8248 SourceLocation Loc, bool IsDiv) {
8249 // Check for division/remainder by zero.
8250 llvm::APSInt RHSValue;
8251 if (!RHS.get()->isValueDependent() &&
8252 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8253 S.DiagRuntimeBehavior(Loc, RHS.get(),
8254 S.PDiag(diag::warn_remainder_division_by_zero)
8255 << IsDiv << RHS.get()->getSourceRange());
8258 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8260 bool IsCompAssign, bool IsDiv) {
8261 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8263 if (LHS.get()->getType()->isVectorType() ||
8264 RHS.get()->getType()->isVectorType())
8265 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8266 /*AllowBothBool*/getLangOpts().AltiVec,
8267 /*AllowBoolConversions*/false);
8269 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8270 if (LHS.isInvalid() || RHS.isInvalid())
8274 if (compType.isNull() || !compType->isArithmeticType())
8275 return InvalidOperands(Loc, LHS, RHS);
8277 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8281 QualType Sema::CheckRemainderOperands(
8282 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8283 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8285 if (LHS.get()->getType()->isVectorType() ||
8286 RHS.get()->getType()->isVectorType()) {
8287 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8288 RHS.get()->getType()->hasIntegerRepresentation())
8289 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8290 /*AllowBothBool*/getLangOpts().AltiVec,
8291 /*AllowBoolConversions*/false);
8292 return InvalidOperands(Loc, LHS, RHS);
8295 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8296 if (LHS.isInvalid() || RHS.isInvalid())
8299 if (compType.isNull() || !compType->isIntegerType())
8300 return InvalidOperands(Loc, LHS, RHS);
8301 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8305 /// \brief Diagnose invalid arithmetic on two void pointers.
8306 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8307 Expr *LHSExpr, Expr *RHSExpr) {
8308 S.Diag(Loc, S.getLangOpts().CPlusPlus
8309 ? diag::err_typecheck_pointer_arith_void_type
8310 : diag::ext_gnu_void_ptr)
8311 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8312 << RHSExpr->getSourceRange();
8315 /// \brief Diagnose invalid arithmetic on a void pointer.
8316 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8318 S.Diag(Loc, S.getLangOpts().CPlusPlus
8319 ? diag::err_typecheck_pointer_arith_void_type
8320 : diag::ext_gnu_void_ptr)
8321 << 0 /* one pointer */ << Pointer->getSourceRange();
8324 /// \brief Diagnose invalid arithmetic on two function pointers.
8325 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8326 Expr *LHS, Expr *RHS) {
8327 assert(LHS->getType()->isAnyPointerType());
8328 assert(RHS->getType()->isAnyPointerType());
8329 S.Diag(Loc, S.getLangOpts().CPlusPlus
8330 ? diag::err_typecheck_pointer_arith_function_type
8331 : diag::ext_gnu_ptr_func_arith)
8332 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8333 // We only show the second type if it differs from the first.
8334 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8336 << RHS->getType()->getPointeeType()
8337 << LHS->getSourceRange() << RHS->getSourceRange();
8340 /// \brief Diagnose invalid arithmetic on a function pointer.
8341 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8343 assert(Pointer->getType()->isAnyPointerType());
8344 S.Diag(Loc, S.getLangOpts().CPlusPlus
8345 ? diag::err_typecheck_pointer_arith_function_type
8346 : diag::ext_gnu_ptr_func_arith)
8347 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8348 << 0 /* one pointer, so only one type */
8349 << Pointer->getSourceRange();
8352 /// \brief Emit error if Operand is incomplete pointer type
8354 /// \returns True if pointer has incomplete type
8355 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8357 QualType ResType = Operand->getType();
8358 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8359 ResType = ResAtomicType->getValueType();
8361 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8362 QualType PointeeTy = ResType->getPointeeType();
8363 return S.RequireCompleteType(Loc, PointeeTy,
8364 diag::err_typecheck_arithmetic_incomplete_type,
8365 PointeeTy, Operand->getSourceRange());
8368 /// \brief Check the validity of an arithmetic pointer operand.
8370 /// If the operand has pointer type, this code will check for pointer types
8371 /// which are invalid in arithmetic operations. These will be diagnosed
8372 /// appropriately, including whether or not the use is supported as an
8375 /// \returns True when the operand is valid to use (even if as an extension).
8376 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8378 QualType ResType = Operand->getType();
8379 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8380 ResType = ResAtomicType->getValueType();
8382 if (!ResType->isAnyPointerType()) return true;
8384 QualType PointeeTy = ResType->getPointeeType();
8385 if (PointeeTy->isVoidType()) {
8386 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8387 return !S.getLangOpts().CPlusPlus;
8389 if (PointeeTy->isFunctionType()) {
8390 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8391 return !S.getLangOpts().CPlusPlus;
8394 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8399 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8402 /// This routine will diagnose any invalid arithmetic on pointer operands much
8403 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8404 /// for emitting a single diagnostic even for operations where both LHS and RHS
8405 /// are (potentially problematic) pointers.
8407 /// \returns True when the operand is valid to use (even if as an extension).
8408 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8409 Expr *LHSExpr, Expr *RHSExpr) {
8410 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8411 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8412 if (!isLHSPointer && !isRHSPointer) return true;
8414 QualType LHSPointeeTy, RHSPointeeTy;
8415 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8416 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8418 // if both are pointers check if operation is valid wrt address spaces
8419 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8420 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8421 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8422 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8424 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8425 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8426 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8431 // Check for arithmetic on pointers to incomplete types.
8432 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8433 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8434 if (isLHSVoidPtr || isRHSVoidPtr) {
8435 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8436 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8437 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8439 return !S.getLangOpts().CPlusPlus;
8442 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8443 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8444 if (isLHSFuncPtr || isRHSFuncPtr) {
8445 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8446 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8448 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8450 return !S.getLangOpts().CPlusPlus;
8453 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8455 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8461 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8463 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8464 Expr *LHSExpr, Expr *RHSExpr) {
8465 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8466 Expr* IndexExpr = RHSExpr;
8468 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8469 IndexExpr = LHSExpr;
8472 bool IsStringPlusInt = StrExpr &&
8473 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8474 if (!IsStringPlusInt || IndexExpr->isValueDependent())
8478 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8479 unsigned StrLenWithNull = StrExpr->getLength() + 1;
8480 if (index.isNonNegative() &&
8481 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8482 index.isUnsigned()))
8486 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8487 Self.Diag(OpLoc, diag::warn_string_plus_int)
8488 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8490 // Only print a fixit for "str" + int, not for int + "str".
8491 if (IndexExpr == RHSExpr) {
8492 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8493 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8494 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8495 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8496 << FixItHint::CreateInsertion(EndLoc, "]");
8498 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8501 /// \brief Emit a warning when adding a char literal to a string.
8502 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8503 Expr *LHSExpr, Expr *RHSExpr) {
8504 const Expr *StringRefExpr = LHSExpr;
8505 const CharacterLiteral *CharExpr =
8506 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8509 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8510 StringRefExpr = RHSExpr;
8513 if (!CharExpr || !StringRefExpr)
8516 const QualType StringType = StringRefExpr->getType();
8518 // Return if not a PointerType.
8519 if (!StringType->isAnyPointerType())
8522 // Return if not a CharacterType.
8523 if (!StringType->getPointeeType()->isAnyCharacterType())
8526 ASTContext &Ctx = Self.getASTContext();
8527 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8529 const QualType CharType = CharExpr->getType();
8530 if (!CharType->isAnyCharacterType() &&
8531 CharType->isIntegerType() &&
8532 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8533 Self.Diag(OpLoc, diag::warn_string_plus_char)
8534 << DiagRange << Ctx.CharTy;
8536 Self.Diag(OpLoc, diag::warn_string_plus_char)
8537 << DiagRange << CharExpr->getType();
8540 // Only print a fixit for str + char, not for char + str.
8541 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8542 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8543 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8544 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8545 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8546 << FixItHint::CreateInsertion(EndLoc, "]");
8548 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8552 /// \brief Emit error when two pointers are incompatible.
8553 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8554 Expr *LHSExpr, Expr *RHSExpr) {
8555 assert(LHSExpr->getType()->isAnyPointerType());
8556 assert(RHSExpr->getType()->isAnyPointerType());
8557 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8558 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8559 << RHSExpr->getSourceRange();
8563 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8564 SourceLocation Loc, BinaryOperatorKind Opc,
8565 QualType* CompLHSTy) {
8566 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8568 if (LHS.get()->getType()->isVectorType() ||
8569 RHS.get()->getType()->isVectorType()) {
8570 QualType compType = CheckVectorOperands(
8571 LHS, RHS, Loc, CompLHSTy,
8572 /*AllowBothBool*/getLangOpts().AltiVec,
8573 /*AllowBoolConversions*/getLangOpts().ZVector);
8574 if (CompLHSTy) *CompLHSTy = compType;
8578 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8579 if (LHS.isInvalid() || RHS.isInvalid())
8582 // Diagnose "string literal" '+' int and string '+' "char literal".
8583 if (Opc == BO_Add) {
8584 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8585 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8588 // handle the common case first (both operands are arithmetic).
8589 if (!compType.isNull() && compType->isArithmeticType()) {
8590 if (CompLHSTy) *CompLHSTy = compType;
8594 // Type-checking. Ultimately the pointer's going to be in PExp;
8595 // note that we bias towards the LHS being the pointer.
8596 Expr *PExp = LHS.get(), *IExp = RHS.get();
8599 if (PExp->getType()->isPointerType()) {
8600 isObjCPointer = false;
8601 } else if (PExp->getType()->isObjCObjectPointerType()) {
8602 isObjCPointer = true;
8604 std::swap(PExp, IExp);
8605 if (PExp->getType()->isPointerType()) {
8606 isObjCPointer = false;
8607 } else if (PExp->getType()->isObjCObjectPointerType()) {
8608 isObjCPointer = true;
8610 return InvalidOperands(Loc, LHS, RHS);
8613 assert(PExp->getType()->isAnyPointerType());
8615 if (!IExp->getType()->isIntegerType())
8616 return InvalidOperands(Loc, LHS, RHS);
8618 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8621 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8624 // Check array bounds for pointer arithemtic
8625 CheckArrayAccess(PExp, IExp);
8628 QualType LHSTy = Context.isPromotableBitField(LHS.get());
8629 if (LHSTy.isNull()) {
8630 LHSTy = LHS.get()->getType();
8631 if (LHSTy->isPromotableIntegerType())
8632 LHSTy = Context.getPromotedIntegerType(LHSTy);
8637 return PExp->getType();
8641 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8643 QualType* CompLHSTy) {
8644 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8646 if (LHS.get()->getType()->isVectorType() ||
8647 RHS.get()->getType()->isVectorType()) {
8648 QualType compType = CheckVectorOperands(
8649 LHS, RHS, Loc, CompLHSTy,
8650 /*AllowBothBool*/getLangOpts().AltiVec,
8651 /*AllowBoolConversions*/getLangOpts().ZVector);
8652 if (CompLHSTy) *CompLHSTy = compType;
8656 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8657 if (LHS.isInvalid() || RHS.isInvalid())
8660 // Enforce type constraints: C99 6.5.6p3.
8662 // Handle the common case first (both operands are arithmetic).
8663 if (!compType.isNull() && compType->isArithmeticType()) {
8664 if (CompLHSTy) *CompLHSTy = compType;
8668 // Either ptr - int or ptr - ptr.
8669 if (LHS.get()->getType()->isAnyPointerType()) {
8670 QualType lpointee = LHS.get()->getType()->getPointeeType();
8672 // Diagnose bad cases where we step over interface counts.
8673 if (LHS.get()->getType()->isObjCObjectPointerType() &&
8674 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8677 // The result type of a pointer-int computation is the pointer type.
8678 if (RHS.get()->getType()->isIntegerType()) {
8679 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8682 // Check array bounds for pointer arithemtic
8683 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8684 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8686 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8687 return LHS.get()->getType();
8690 // Handle pointer-pointer subtractions.
8691 if (const PointerType *RHSPTy
8692 = RHS.get()->getType()->getAs<PointerType>()) {
8693 QualType rpointee = RHSPTy->getPointeeType();
8695 if (getLangOpts().CPlusPlus) {
8696 // Pointee types must be the same: C++ [expr.add]
8697 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8698 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8701 // Pointee types must be compatible C99 6.5.6p3
8702 if (!Context.typesAreCompatible(
8703 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8704 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8705 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8710 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8711 LHS.get(), RHS.get()))
8714 // The pointee type may have zero size. As an extension, a structure or
8715 // union may have zero size or an array may have zero length. In this
8716 // case subtraction does not make sense.
8717 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8718 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8719 if (ElementSize.isZero()) {
8720 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8721 << rpointee.getUnqualifiedType()
8722 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8726 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8727 return Context.getPointerDiffType();
8731 return InvalidOperands(Loc, LHS, RHS);
8734 static bool isScopedEnumerationType(QualType T) {
8735 if (const EnumType *ET = T->getAs<EnumType>())
8736 return ET->getDecl()->isScoped();
8740 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8741 SourceLocation Loc, BinaryOperatorKind Opc,
8743 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8744 // so skip remaining warnings as we don't want to modify values within Sema.
8745 if (S.getLangOpts().OpenCL)
8749 // Check right/shifter operand
8750 if (RHS.get()->isValueDependent() ||
8751 !RHS.get()->EvaluateAsInt(Right, S.Context))
8754 if (Right.isNegative()) {
8755 S.DiagRuntimeBehavior(Loc, RHS.get(),
8756 S.PDiag(diag::warn_shift_negative)
8757 << RHS.get()->getSourceRange());
8760 llvm::APInt LeftBits(Right.getBitWidth(),
8761 S.Context.getTypeSize(LHS.get()->getType()));
8762 if (Right.uge(LeftBits)) {
8763 S.DiagRuntimeBehavior(Loc, RHS.get(),
8764 S.PDiag(diag::warn_shift_gt_typewidth)
8765 << RHS.get()->getSourceRange());
8771 // When left shifting an ICE which is signed, we can check for overflow which
8772 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8773 // integers have defined behavior modulo one more than the maximum value
8774 // representable in the result type, so never warn for those.
8776 if (LHS.get()->isValueDependent() ||
8777 LHSType->hasUnsignedIntegerRepresentation() ||
8778 !LHS.get()->EvaluateAsInt(Left, S.Context))
8781 // If LHS does not have a signed type and non-negative value
8782 // then, the behavior is undefined. Warn about it.
8783 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8784 S.DiagRuntimeBehavior(Loc, LHS.get(),
8785 S.PDiag(diag::warn_shift_lhs_negative)
8786 << LHS.get()->getSourceRange());
8790 llvm::APInt ResultBits =
8791 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8792 if (LeftBits.uge(ResultBits))
8794 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8795 Result = Result.shl(Right);
8797 // Print the bit representation of the signed integer as an unsigned
8798 // hexadecimal number.
8799 SmallString<40> HexResult;
8800 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8802 // If we are only missing a sign bit, this is less likely to result in actual
8803 // bugs -- if the result is cast back to an unsigned type, it will have the
8804 // expected value. Thus we place this behind a different warning that can be
8805 // turned off separately if needed.
8806 if (LeftBits == ResultBits - 1) {
8807 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8808 << HexResult << LHSType
8809 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8813 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8814 << HexResult.str() << Result.getMinSignedBits() << LHSType
8815 << Left.getBitWidth() << LHS.get()->getSourceRange()
8816 << RHS.get()->getSourceRange();
8819 /// \brief Return the resulting type when a vector is shifted
8820 /// by a scalar or vector shift amount.
8821 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8822 SourceLocation Loc, bool IsCompAssign) {
8823 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8824 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8825 !LHS.get()->getType()->isVectorType()) {
8826 S.Diag(Loc, diag::err_shift_rhs_only_vector)
8827 << RHS.get()->getType() << LHS.get()->getType()
8828 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8832 if (!IsCompAssign) {
8833 LHS = S.UsualUnaryConversions(LHS.get());
8834 if (LHS.isInvalid()) return QualType();
8837 RHS = S.UsualUnaryConversions(RHS.get());
8838 if (RHS.isInvalid()) return QualType();
8840 QualType LHSType = LHS.get()->getType();
8841 // Note that LHS might be a scalar because the routine calls not only in
8843 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8844 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8846 // Note that RHS might not be a vector.
8847 QualType RHSType = RHS.get()->getType();
8848 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8849 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8851 // The operands need to be integers.
8852 if (!LHSEleType->isIntegerType()) {
8853 S.Diag(Loc, diag::err_typecheck_expect_int)
8854 << LHS.get()->getType() << LHS.get()->getSourceRange();
8858 if (!RHSEleType->isIntegerType()) {
8859 S.Diag(Loc, diag::err_typecheck_expect_int)
8860 << RHS.get()->getType() << RHS.get()->getSourceRange();
8868 if (LHSEleType != RHSEleType) {
8869 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8870 LHSEleType = RHSEleType;
8873 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8874 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8876 } else if (RHSVecTy) {
8877 // OpenCL v1.1 s6.3.j says that for vector types, the operators
8878 // are applied component-wise. So if RHS is a vector, then ensure
8879 // that the number of elements is the same as LHS...
8880 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8881 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8882 << LHS.get()->getType() << RHS.get()->getType()
8883 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8886 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8887 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8888 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8889 if (LHSBT != RHSBT &&
8890 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8891 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8892 << LHS.get()->getType() << RHS.get()->getType()
8893 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8897 // ...else expand RHS to match the number of elements in LHS.
8899 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8900 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8907 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8908 SourceLocation Loc, BinaryOperatorKind Opc,
8909 bool IsCompAssign) {
8910 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8912 // Vector shifts promote their scalar inputs to vector type.
8913 if (LHS.get()->getType()->isVectorType() ||
8914 RHS.get()->getType()->isVectorType()) {
8915 if (LangOpts.ZVector) {
8916 // The shift operators for the z vector extensions work basically
8917 // like general shifts, except that neither the LHS nor the RHS is
8918 // allowed to be a "vector bool".
8919 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8920 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8921 return InvalidOperands(Loc, LHS, RHS);
8922 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8923 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8924 return InvalidOperands(Loc, LHS, RHS);
8926 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8929 // Shifts don't perform usual arithmetic conversions, they just do integer
8930 // promotions on each operand. C99 6.5.7p3
8932 // For the LHS, do usual unary conversions, but then reset them away
8933 // if this is a compound assignment.
8934 ExprResult OldLHS = LHS;
8935 LHS = UsualUnaryConversions(LHS.get());
8936 if (LHS.isInvalid())
8938 QualType LHSType = LHS.get()->getType();
8939 if (IsCompAssign) LHS = OldLHS;
8941 // The RHS is simpler.
8942 RHS = UsualUnaryConversions(RHS.get());
8943 if (RHS.isInvalid())
8945 QualType RHSType = RHS.get()->getType();
8947 // C99 6.5.7p2: Each of the operands shall have integer type.
8948 if (!LHSType->hasIntegerRepresentation() ||
8949 !RHSType->hasIntegerRepresentation())
8950 return InvalidOperands(Loc, LHS, RHS);
8952 // C++0x: Don't allow scoped enums. FIXME: Use something better than
8953 // hasIntegerRepresentation() above instead of this.
8954 if (isScopedEnumerationType(LHSType) ||
8955 isScopedEnumerationType(RHSType)) {
8956 return InvalidOperands(Loc, LHS, RHS);
8958 // Sanity-check shift operands
8959 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8961 // "The type of the result is that of the promoted left operand."
8965 static bool IsWithinTemplateSpecialization(Decl *D) {
8966 if (DeclContext *DC = D->getDeclContext()) {
8967 if (isa<ClassTemplateSpecializationDecl>(DC))
8969 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8970 return FD->isFunctionTemplateSpecialization();
8975 /// If two different enums are compared, raise a warning.
8976 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8978 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8979 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8981 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8984 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8988 // Ignore anonymous enums.
8989 if (!LHSEnumType->getDecl()->getIdentifier())
8991 if (!RHSEnumType->getDecl()->getIdentifier())
8994 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8997 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8998 << LHSStrippedType << RHSStrippedType
8999 << LHS->getSourceRange() << RHS->getSourceRange();
9002 /// \brief Diagnose bad pointer comparisons.
9003 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9004 ExprResult &LHS, ExprResult &RHS,
9006 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9007 : diag::ext_typecheck_comparison_of_distinct_pointers)
9008 << LHS.get()->getType() << RHS.get()->getType()
9009 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9012 /// \brief Returns false if the pointers are converted to a composite type,
9014 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9015 ExprResult &LHS, ExprResult &RHS) {
9016 // C++ [expr.rel]p2:
9017 // [...] Pointer conversions (4.10) and qualification
9018 // conversions (4.4) are performed on pointer operands (or on
9019 // a pointer operand and a null pointer constant) to bring
9020 // them to their composite pointer type. [...]
9022 // C++ [expr.eq]p1 uses the same notion for (in)equality
9023 // comparisons of pointers.
9025 QualType LHSType = LHS.get()->getType();
9026 QualType RHSType = RHS.get()->getType();
9027 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9028 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9030 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9032 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9033 (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9034 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9036 S.InvalidOperands(Loc, LHS, RHS);
9040 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9041 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9045 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9049 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9050 : diag::ext_typecheck_comparison_of_fptr_to_void)
9051 << LHS.get()->getType() << RHS.get()->getType()
9052 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9055 static bool isObjCObjectLiteral(ExprResult &E) {
9056 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9057 case Stmt::ObjCArrayLiteralClass:
9058 case Stmt::ObjCDictionaryLiteralClass:
9059 case Stmt::ObjCStringLiteralClass:
9060 case Stmt::ObjCBoxedExprClass:
9063 // Note that ObjCBoolLiteral is NOT an object literal!
9068 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9069 const ObjCObjectPointerType *Type =
9070 LHS->getType()->getAs<ObjCObjectPointerType>();
9072 // If this is not actually an Objective-C object, bail out.
9076 // Get the LHS object's interface type.
9077 QualType InterfaceType = Type->getPointeeType();
9079 // If the RHS isn't an Objective-C object, bail out.
9080 if (!RHS->getType()->isObjCObjectPointerType())
9083 // Try to find the -isEqual: method.
9084 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9085 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9089 if (Type->isObjCIdType()) {
9090 // For 'id', just check the global pool.
9091 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9092 /*receiverId=*/true);
9095 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9103 QualType T = Method->parameters()[0]->getType();
9104 if (!T->isObjCObjectPointerType())
9107 QualType R = Method->getReturnType();
9108 if (!R->isScalarType())
9114 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9115 FromE = FromE->IgnoreParenImpCasts();
9116 switch (FromE->getStmtClass()) {
9119 case Stmt::ObjCStringLiteralClass:
9122 case Stmt::ObjCArrayLiteralClass:
9125 case Stmt::ObjCDictionaryLiteralClass:
9126 // "dictionary literal"
9127 return LK_Dictionary;
9128 case Stmt::BlockExprClass:
9130 case Stmt::ObjCBoxedExprClass: {
9131 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9132 switch (Inner->getStmtClass()) {
9133 case Stmt::IntegerLiteralClass:
9134 case Stmt::FloatingLiteralClass:
9135 case Stmt::CharacterLiteralClass:
9136 case Stmt::ObjCBoolLiteralExprClass:
9137 case Stmt::CXXBoolLiteralExprClass:
9138 // "numeric literal"
9140 case Stmt::ImplicitCastExprClass: {
9141 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9142 // Boolean literals can be represented by implicit casts.
9143 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9156 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9157 ExprResult &LHS, ExprResult &RHS,
9158 BinaryOperator::Opcode Opc){
9161 if (isObjCObjectLiteral(LHS)) {
9162 Literal = LHS.get();
9165 Literal = RHS.get();
9169 // Don't warn on comparisons against nil.
9170 Other = Other->IgnoreParenCasts();
9171 if (Other->isNullPointerConstant(S.getASTContext(),
9172 Expr::NPC_ValueDependentIsNotNull))
9175 // This should be kept in sync with warn_objc_literal_comparison.
9176 // LK_String should always be after the other literals, since it has its own
9178 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9179 assert(LiteralKind != Sema::LK_Block);
9180 if (LiteralKind == Sema::LK_None) {
9181 llvm_unreachable("Unknown Objective-C object literal kind");
9184 if (LiteralKind == Sema::LK_String)
9185 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9186 << Literal->getSourceRange();
9188 S.Diag(Loc, diag::warn_objc_literal_comparison)
9189 << LiteralKind << Literal->getSourceRange();
9191 if (BinaryOperator::isEqualityOp(Opc) &&
9192 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9193 SourceLocation Start = LHS.get()->getLocStart();
9194 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9195 CharSourceRange OpRange =
9196 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9198 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9199 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9200 << FixItHint::CreateReplacement(OpRange, " isEqual:")
9201 << FixItHint::CreateInsertion(End, "]");
9205 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9206 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9207 ExprResult &RHS, SourceLocation Loc,
9208 BinaryOperatorKind Opc) {
9209 // Check that left hand side is !something.
9210 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9211 if (!UO || UO->getOpcode() != UO_LNot) return;
9213 // Only check if the right hand side is non-bool arithmetic type.
9214 if (RHS.get()->isKnownToHaveBooleanValue()) return;
9216 // Make sure that the something in !something is not bool.
9217 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9218 if (SubExpr->isKnownToHaveBooleanValue()) return;
9221 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9222 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9223 << Loc << IsBitwiseOp;
9225 // First note suggest !(x < y)
9226 SourceLocation FirstOpen = SubExpr->getLocStart();
9227 SourceLocation FirstClose = RHS.get()->getLocEnd();
9228 FirstClose = S.getLocForEndOfToken(FirstClose);
9229 if (FirstClose.isInvalid())
9230 FirstOpen = SourceLocation();
9231 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9233 << FixItHint::CreateInsertion(FirstOpen, "(")
9234 << FixItHint::CreateInsertion(FirstClose, ")");
9236 // Second note suggests (!x) < y
9237 SourceLocation SecondOpen = LHS.get()->getLocStart();
9238 SourceLocation SecondClose = LHS.get()->getLocEnd();
9239 SecondClose = S.getLocForEndOfToken(SecondClose);
9240 if (SecondClose.isInvalid())
9241 SecondOpen = SourceLocation();
9242 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9243 << FixItHint::CreateInsertion(SecondOpen, "(")
9244 << FixItHint::CreateInsertion(SecondClose, ")");
9247 // Get the decl for a simple expression: a reference to a variable,
9248 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9249 static ValueDecl *getCompareDecl(Expr *E) {
9250 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9251 return DR->getDecl();
9252 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9253 if (Ivar->isFreeIvar())
9254 return Ivar->getDecl();
9256 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9257 if (Mem->isImplicitAccess())
9258 return Mem->getMemberDecl();
9263 // C99 6.5.8, C++ [expr.rel]
9264 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9265 SourceLocation Loc, BinaryOperatorKind Opc,
9266 bool IsRelational) {
9267 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9269 // Handle vector comparisons separately.
9270 if (LHS.get()->getType()->isVectorType() ||
9271 RHS.get()->getType()->isVectorType())
9272 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9274 QualType LHSType = LHS.get()->getType();
9275 QualType RHSType = RHS.get()->getType();
9277 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9278 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9280 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9281 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9283 if (!LHSType->hasFloatingRepresentation() &&
9284 !(LHSType->isBlockPointerType() && IsRelational) &&
9285 !LHS.get()->getLocStart().isMacroID() &&
9286 !RHS.get()->getLocStart().isMacroID() &&
9287 !inTemplateInstantiation()) {
9288 // For non-floating point types, check for self-comparisons of the form
9289 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9290 // often indicate logic errors in the program.
9292 // NOTE: Don't warn about comparison expressions resulting from macro
9293 // expansion. Also don't warn about comparisons which are only self
9294 // comparisons within a template specialization. The warnings should catch
9295 // obvious cases in the definition of the template anyways. The idea is to
9296 // warn when the typed comparison operator will always evaluate to the same
9298 ValueDecl *DL = getCompareDecl(LHSStripped);
9299 ValueDecl *DR = getCompareDecl(RHSStripped);
9300 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9301 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9306 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9307 !DL->getType()->isReferenceType() &&
9308 !DR->getType()->isReferenceType()) {
9309 // what is it always going to eval to?
9310 char always_evals_to;
9312 case BO_EQ: // e.g. array1 == array2
9313 always_evals_to = 0; // false
9315 case BO_NE: // e.g. array1 != array2
9316 always_evals_to = 1; // true
9319 // best we can say is 'a constant'
9320 always_evals_to = 2; // e.g. array1 <= array2
9323 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9325 << always_evals_to);
9328 if (isa<CastExpr>(LHSStripped))
9329 LHSStripped = LHSStripped->IgnoreParenCasts();
9330 if (isa<CastExpr>(RHSStripped))
9331 RHSStripped = RHSStripped->IgnoreParenCasts();
9333 // Warn about comparisons against a string constant (unless the other
9334 // operand is null), the user probably wants strcmp.
9335 Expr *literalString = nullptr;
9336 Expr *literalStringStripped = nullptr;
9337 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9338 !RHSStripped->isNullPointerConstant(Context,
9339 Expr::NPC_ValueDependentIsNull)) {
9340 literalString = LHS.get();
9341 literalStringStripped = LHSStripped;
9342 } else if ((isa<StringLiteral>(RHSStripped) ||
9343 isa<ObjCEncodeExpr>(RHSStripped)) &&
9344 !LHSStripped->isNullPointerConstant(Context,
9345 Expr::NPC_ValueDependentIsNull)) {
9346 literalString = RHS.get();
9347 literalStringStripped = RHSStripped;
9350 if (literalString) {
9351 DiagRuntimeBehavior(Loc, nullptr,
9352 PDiag(diag::warn_stringcompare)
9353 << isa<ObjCEncodeExpr>(literalStringStripped)
9354 << literalString->getSourceRange());
9358 // C99 6.5.8p3 / C99 6.5.9p4
9359 UsualArithmeticConversions(LHS, RHS);
9360 if (LHS.isInvalid() || RHS.isInvalid())
9363 LHSType = LHS.get()->getType();
9364 RHSType = RHS.get()->getType();
9366 // The result of comparisons is 'bool' in C++, 'int' in C.
9367 QualType ResultTy = Context.getLogicalOperationType();
9370 if (LHSType->isRealType() && RHSType->isRealType())
9373 // Check for comparisons of floating point operands using != and ==.
9374 if (LHSType->hasFloatingRepresentation())
9375 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9377 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9381 const Expr::NullPointerConstantKind LHSNullKind =
9382 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9383 const Expr::NullPointerConstantKind RHSNullKind =
9384 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9385 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9386 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9388 if (!IsRelational && LHSIsNull != RHSIsNull) {
9389 bool IsEquality = Opc == BO_EQ;
9391 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9392 RHS.get()->getSourceRange());
9394 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9395 LHS.get()->getSourceRange());
9398 if ((LHSType->isIntegerType() && !LHSIsNull) ||
9399 (RHSType->isIntegerType() && !RHSIsNull)) {
9400 // Skip normal pointer conversion checks in this case; we have better
9401 // diagnostics for this below.
9402 } else if (getLangOpts().CPlusPlus) {
9403 // Equality comparison of a function pointer to a void pointer is invalid,
9404 // but we allow it as an extension.
9405 // FIXME: If we really want to allow this, should it be part of composite
9406 // pointer type computation so it works in conditionals too?
9407 if (!IsRelational &&
9408 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9409 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9410 // This is a gcc extension compatibility comparison.
9411 // In a SFINAE context, we treat this as a hard error to maintain
9412 // conformance with the C++ standard.
9413 diagnoseFunctionPointerToVoidComparison(
9414 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9416 if (isSFINAEContext())
9419 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9424 // If at least one operand is a pointer [...] bring them to their
9425 // composite pointer type.
9426 // C++ [expr.rel]p2:
9427 // If both operands are pointers, [...] bring them to their composite
9429 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9430 (IsRelational ? 2 : 1) &&
9431 (!LangOpts.ObjCAutoRefCount ||
9432 !(LHSType->isObjCObjectPointerType() ||
9433 RHSType->isObjCObjectPointerType()))) {
9434 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9439 } else if (LHSType->isPointerType() &&
9440 RHSType->isPointerType()) { // C99 6.5.8p2
9441 // All of the following pointer-related warnings are GCC extensions, except
9442 // when handling null pointer constants.
9443 QualType LCanPointeeTy =
9444 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9445 QualType RCanPointeeTy =
9446 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9448 // C99 6.5.9p2 and C99 6.5.8p2
9449 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9450 RCanPointeeTy.getUnqualifiedType())) {
9451 // Valid unless a relational comparison of function pointers
9452 if (IsRelational && LCanPointeeTy->isFunctionType()) {
9453 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9454 << LHSType << RHSType << LHS.get()->getSourceRange()
9455 << RHS.get()->getSourceRange();
9457 } else if (!IsRelational &&
9458 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9459 // Valid unless comparison between non-null pointer and function pointer
9460 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9461 && !LHSIsNull && !RHSIsNull)
9462 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9466 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9468 if (LCanPointeeTy != RCanPointeeTy) {
9469 // Treat NULL constant as a special case in OpenCL.
9470 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9471 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9472 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9474 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9475 << LHSType << RHSType << 0 /* comparison */
9476 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9479 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9480 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9481 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9483 if (LHSIsNull && !RHSIsNull)
9484 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9486 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9491 if (getLangOpts().CPlusPlus) {
9493 // Two operands of type std::nullptr_t or one operand of type
9494 // std::nullptr_t and the other a null pointer constant compare equal.
9495 if (!IsRelational && LHSIsNull && RHSIsNull) {
9496 if (LHSType->isNullPtrType()) {
9497 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9500 if (RHSType->isNullPtrType()) {
9501 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9506 // Comparison of Objective-C pointers and block pointers against nullptr_t.
9507 // These aren't covered by the composite pointer type rules.
9508 if (!IsRelational && RHSType->isNullPtrType() &&
9509 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9510 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9513 if (!IsRelational && LHSType->isNullPtrType() &&
9514 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9515 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9520 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9521 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9522 // HACK: Relational comparison of nullptr_t against a pointer type is
9523 // invalid per DR583, but we allow it within std::less<> and friends,
9524 // since otherwise common uses of it break.
9525 // FIXME: Consider removing this hack once LWG fixes std::less<> and
9526 // friends to have std::nullptr_t overload candidates.
9527 DeclContext *DC = CurContext;
9528 if (isa<FunctionDecl>(DC))
9529 DC = DC->getParent();
9530 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9531 if (CTSD->isInStdNamespace() &&
9532 llvm::StringSwitch<bool>(CTSD->getName())
9533 .Cases("less", "less_equal", "greater", "greater_equal", true)
9535 if (RHSType->isNullPtrType())
9536 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9538 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9545 // If at least one operand is a pointer to member, [...] bring them to
9546 // their composite pointer type.
9547 if (!IsRelational &&
9548 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9549 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9555 // Handle scoped enumeration types specifically, since they don't promote
9557 if (LHS.get()->getType()->isEnumeralType() &&
9558 Context.hasSameUnqualifiedType(LHS.get()->getType(),
9559 RHS.get()->getType()))
9563 // Handle block pointer types.
9564 if (!IsRelational && LHSType->isBlockPointerType() &&
9565 RHSType->isBlockPointerType()) {
9566 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9567 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9569 if (!LHSIsNull && !RHSIsNull &&
9570 !Context.typesAreCompatible(lpointee, rpointee)) {
9571 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9572 << LHSType << RHSType << LHS.get()->getSourceRange()
9573 << RHS.get()->getSourceRange();
9575 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9579 // Allow block pointers to be compared with null pointer constants.
9581 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9582 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9583 if (!LHSIsNull && !RHSIsNull) {
9584 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9585 ->getPointeeType()->isVoidType())
9586 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9587 ->getPointeeType()->isVoidType())))
9588 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9589 << LHSType << RHSType << LHS.get()->getSourceRange()
9590 << RHS.get()->getSourceRange();
9592 if (LHSIsNull && !RHSIsNull)
9593 LHS = ImpCastExprToType(LHS.get(), RHSType,
9594 RHSType->isPointerType() ? CK_BitCast
9595 : CK_AnyPointerToBlockPointerCast);
9597 RHS = ImpCastExprToType(RHS.get(), LHSType,
9598 LHSType->isPointerType() ? CK_BitCast
9599 : CK_AnyPointerToBlockPointerCast);
9603 if (LHSType->isObjCObjectPointerType() ||
9604 RHSType->isObjCObjectPointerType()) {
9605 const PointerType *LPT = LHSType->getAs<PointerType>();
9606 const PointerType *RPT = RHSType->getAs<PointerType>();
9608 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9609 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9611 if (!LPtrToVoid && !RPtrToVoid &&
9612 !Context.typesAreCompatible(LHSType, RHSType)) {
9613 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9616 if (LHSIsNull && !RHSIsNull) {
9617 Expr *E = LHS.get();
9618 if (getLangOpts().ObjCAutoRefCount)
9619 CheckObjCConversion(SourceRange(), RHSType, E,
9620 CCK_ImplicitConversion);
9621 LHS = ImpCastExprToType(E, RHSType,
9622 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9625 Expr *E = RHS.get();
9626 if (getLangOpts().ObjCAutoRefCount)
9627 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9629 /*DiagnoseCFAudited=*/false, Opc);
9630 RHS = ImpCastExprToType(E, LHSType,
9631 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9635 if (LHSType->isObjCObjectPointerType() &&
9636 RHSType->isObjCObjectPointerType()) {
9637 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9638 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9640 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9641 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9643 if (LHSIsNull && !RHSIsNull)
9644 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9646 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9650 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9651 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9652 unsigned DiagID = 0;
9653 bool isError = false;
9654 if (LangOpts.DebuggerSupport) {
9655 // Under a debugger, allow the comparison of pointers to integers,
9656 // since users tend to want to compare addresses.
9657 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9658 (RHSIsNull && RHSType->isIntegerType())) {
9660 isError = getLangOpts().CPlusPlus;
9662 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9663 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9665 } else if (getLangOpts().CPlusPlus) {
9666 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9668 } else if (IsRelational)
9669 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9671 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9675 << LHSType << RHSType << LHS.get()->getSourceRange()
9676 << RHS.get()->getSourceRange();
9681 if (LHSType->isIntegerType())
9682 LHS = ImpCastExprToType(LHS.get(), RHSType,
9683 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9685 RHS = ImpCastExprToType(RHS.get(), LHSType,
9686 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9690 // Handle block pointers.
9691 if (!IsRelational && RHSIsNull
9692 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9693 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9696 if (!IsRelational && LHSIsNull
9697 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9698 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9702 if (getLangOpts().OpenCLVersion >= 200) {
9703 if (LHSIsNull && RHSType->isQueueT()) {
9704 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9708 if (LHSType->isQueueT() && RHSIsNull) {
9709 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9714 return InvalidOperands(Loc, LHS, RHS);
9717 // Return a signed ext_vector_type that is of identical size and number of
9718 // elements. For floating point vectors, return an integer type of identical
9719 // size and number of elements. In the non ext_vector_type case, search from
9720 // the largest type to the smallest type to avoid cases where long long == long,
9721 // where long gets picked over long long.
9722 QualType Sema::GetSignedVectorType(QualType V) {
9723 const VectorType *VTy = V->getAs<VectorType>();
9724 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9726 if (isa<ExtVectorType>(VTy)) {
9727 if (TypeSize == Context.getTypeSize(Context.CharTy))
9728 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9729 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9730 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9731 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9732 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9733 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9734 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9735 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9736 "Unhandled vector element size in vector compare");
9737 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9740 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9741 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9742 VectorType::GenericVector);
9743 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9744 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9745 VectorType::GenericVector);
9746 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9747 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9748 VectorType::GenericVector);
9749 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9750 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9751 VectorType::GenericVector);
9752 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9753 "Unhandled vector element size in vector compare");
9754 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9755 VectorType::GenericVector);
9758 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9759 /// operates on extended vector types. Instead of producing an IntTy result,
9760 /// like a scalar comparison, a vector comparison produces a vector of integer
9762 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9764 bool IsRelational) {
9765 // Check to make sure we're operating on vectors of the same type and width,
9766 // Allowing one side to be a scalar of element type.
9767 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9768 /*AllowBothBool*/true,
9769 /*AllowBoolConversions*/getLangOpts().ZVector);
9773 QualType LHSType = LHS.get()->getType();
9775 // If AltiVec, the comparison results in a numeric type, i.e.
9776 // bool for C++, int for C
9777 if (getLangOpts().AltiVec &&
9778 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9779 return Context.getLogicalOperationType();
9781 // For non-floating point types, check for self-comparisons of the form
9782 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9783 // often indicate logic errors in the program.
9784 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9785 if (DeclRefExpr* DRL
9786 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9787 if (DeclRefExpr* DRR
9788 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9789 if (DRL->getDecl() == DRR->getDecl())
9790 DiagRuntimeBehavior(Loc, nullptr,
9791 PDiag(diag::warn_comparison_always)
9793 << 2 // "a constant"
9797 // Check for comparisons of floating point operands using != and ==.
9798 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9799 assert (RHS.get()->getType()->hasFloatingRepresentation());
9800 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9803 // Return a signed type for the vector.
9804 return GetSignedVectorType(vType);
9807 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9808 SourceLocation Loc) {
9809 // Ensure that either both operands are of the same vector type, or
9810 // one operand is of a vector type and the other is of its element type.
9811 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9812 /*AllowBothBool*/true,
9813 /*AllowBoolConversions*/false);
9815 return InvalidOperands(Loc, LHS, RHS);
9816 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9817 vType->hasFloatingRepresentation())
9818 return InvalidOperands(Loc, LHS, RHS);
9820 return GetSignedVectorType(LHS.get()->getType());
9823 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9825 BinaryOperatorKind Opc) {
9826 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9829 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9831 if (LHS.get()->getType()->isVectorType() ||
9832 RHS.get()->getType()->isVectorType()) {
9833 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9834 RHS.get()->getType()->hasIntegerRepresentation())
9835 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9836 /*AllowBothBool*/true,
9837 /*AllowBoolConversions*/getLangOpts().ZVector);
9838 return InvalidOperands(Loc, LHS, RHS);
9842 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9844 ExprResult LHSResult = LHS, RHSResult = RHS;
9845 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9847 if (LHSResult.isInvalid() || RHSResult.isInvalid())
9849 LHS = LHSResult.get();
9850 RHS = RHSResult.get();
9852 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9854 return InvalidOperands(Loc, LHS, RHS);
9858 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9860 BinaryOperatorKind Opc) {
9861 // Check vector operands differently.
9862 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9863 return CheckVectorLogicalOperands(LHS, RHS, Loc);
9865 // Diagnose cases where the user write a logical and/or but probably meant a
9866 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
9868 if (LHS.get()->getType()->isIntegerType() &&
9869 !LHS.get()->getType()->isBooleanType() &&
9870 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9871 // Don't warn in macros or template instantiations.
9872 !Loc.isMacroID() && !inTemplateInstantiation()) {
9873 // If the RHS can be constant folded, and if it constant folds to something
9874 // that isn't 0 or 1 (which indicate a potential logical operation that
9875 // happened to fold to true/false) then warn.
9876 // Parens on the RHS are ignored.
9877 llvm::APSInt Result;
9878 if (RHS.get()->EvaluateAsInt(Result, Context))
9879 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9880 !RHS.get()->getExprLoc().isMacroID()) ||
9881 (Result != 0 && Result != 1)) {
9882 Diag(Loc, diag::warn_logical_instead_of_bitwise)
9883 << RHS.get()->getSourceRange()
9884 << (Opc == BO_LAnd ? "&&" : "||");
9885 // Suggest replacing the logical operator with the bitwise version
9886 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9887 << (Opc == BO_LAnd ? "&" : "|")
9888 << FixItHint::CreateReplacement(SourceRange(
9889 Loc, getLocForEndOfToken(Loc)),
9890 Opc == BO_LAnd ? "&" : "|");
9892 // Suggest replacing "Foo() && kNonZero" with "Foo()"
9893 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9894 << FixItHint::CreateRemoval(
9895 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9896 RHS.get()->getLocEnd()));
9900 if (!Context.getLangOpts().CPlusPlus) {
9901 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9902 // not operate on the built-in scalar and vector float types.
9903 if (Context.getLangOpts().OpenCL &&
9904 Context.getLangOpts().OpenCLVersion < 120) {
9905 if (LHS.get()->getType()->isFloatingType() ||
9906 RHS.get()->getType()->isFloatingType())
9907 return InvalidOperands(Loc, LHS, RHS);
9910 LHS = UsualUnaryConversions(LHS.get());
9911 if (LHS.isInvalid())
9914 RHS = UsualUnaryConversions(RHS.get());
9915 if (RHS.isInvalid())
9918 if (!LHS.get()->getType()->isScalarType() ||
9919 !RHS.get()->getType()->isScalarType())
9920 return InvalidOperands(Loc, LHS, RHS);
9922 return Context.IntTy;
9925 // The following is safe because we only use this method for
9926 // non-overloadable operands.
9928 // C++ [expr.log.and]p1
9929 // C++ [expr.log.or]p1
9930 // The operands are both contextually converted to type bool.
9931 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9932 if (LHSRes.isInvalid())
9933 return InvalidOperands(Loc, LHS, RHS);
9936 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9937 if (RHSRes.isInvalid())
9938 return InvalidOperands(Loc, LHS, RHS);
9941 // C++ [expr.log.and]p2
9942 // C++ [expr.log.or]p2
9943 // The result is a bool.
9944 return Context.BoolTy;
9947 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9948 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9949 if (!ME) return false;
9950 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9951 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9952 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9953 if (!Base) return false;
9954 return Base->getMethodDecl() != nullptr;
9957 /// Is the given expression (which must be 'const') a reference to a
9958 /// variable which was originally non-const, but which has become
9959 /// 'const' due to being captured within a block?
9960 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9961 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9962 assert(E->isLValue() && E->getType().isConstQualified());
9963 E = E->IgnoreParens();
9965 // Must be a reference to a declaration from an enclosing scope.
9966 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9967 if (!DRE) return NCCK_None;
9968 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9970 // The declaration must be a variable which is not declared 'const'.
9971 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9972 if (!var) return NCCK_None;
9973 if (var->getType().isConstQualified()) return NCCK_None;
9974 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9976 // Decide whether the first capture was for a block or a lambda.
9977 DeclContext *DC = S.CurContext, *Prev = nullptr;
9978 // Decide whether the first capture was for a block or a lambda.
9980 // For init-capture, it is possible that the variable belongs to the
9981 // template pattern of the current context.
9982 if (auto *FD = dyn_cast<FunctionDecl>(DC))
9983 if (var->isInitCapture() &&
9984 FD->getTemplateInstantiationPattern() == var->getDeclContext())
9986 if (DC == var->getDeclContext())
9989 DC = DC->getParent();
9991 // Unless we have an init-capture, we've gone one step too far.
9992 if (!var->isInitCapture())
9994 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9997 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9998 Ty = Ty.getNonReferenceType();
9999 if (IsDereference && Ty->isPointerType())
10000 Ty = Ty->getPointeeType();
10001 return !Ty.isConstQualified();
10004 /// Emit the "read-only variable not assignable" error and print notes to give
10005 /// more information about why the variable is not assignable, such as pointing
10006 /// to the declaration of a const variable, showing that a method is const, or
10007 /// that the function is returning a const reference.
10008 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10009 SourceLocation Loc) {
10010 // Update err_typecheck_assign_const and note_typecheck_assign_const
10011 // when this enum is changed.
10017 ConstUnknown, // Keep as last element
10020 SourceRange ExprRange = E->getSourceRange();
10022 // Only emit one error on the first const found. All other consts will emit
10023 // a note to the error.
10024 bool DiagnosticEmitted = false;
10026 // Track if the current expression is the result of a dereference, and if the
10027 // next checked expression is the result of a dereference.
10028 bool IsDereference = false;
10029 bool NextIsDereference = false;
10031 // Loop to process MemberExpr chains.
10033 IsDereference = NextIsDereference;
10035 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10036 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10037 NextIsDereference = ME->isArrow();
10038 const ValueDecl *VD = ME->getMemberDecl();
10039 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10040 // Mutable fields can be modified even if the class is const.
10041 if (Field->isMutable()) {
10042 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10046 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10047 if (!DiagnosticEmitted) {
10048 S.Diag(Loc, diag::err_typecheck_assign_const)
10049 << ExprRange << ConstMember << false /*static*/ << Field
10050 << Field->getType();
10051 DiagnosticEmitted = true;
10053 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10054 << ConstMember << false /*static*/ << Field << Field->getType()
10055 << Field->getSourceRange();
10059 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10060 if (VDecl->getType().isConstQualified()) {
10061 if (!DiagnosticEmitted) {
10062 S.Diag(Loc, diag::err_typecheck_assign_const)
10063 << ExprRange << ConstMember << true /*static*/ << VDecl
10064 << VDecl->getType();
10065 DiagnosticEmitted = true;
10067 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10068 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10069 << VDecl->getSourceRange();
10071 // Static fields do not inherit constness from parents.
10075 } // End MemberExpr
10079 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10081 const FunctionDecl *FD = CE->getDirectCallee();
10082 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10083 if (!DiagnosticEmitted) {
10084 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10085 << ConstFunction << FD;
10086 DiagnosticEmitted = true;
10088 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10089 diag::note_typecheck_assign_const)
10090 << ConstFunction << FD << FD->getReturnType()
10091 << FD->getReturnTypeSourceRange();
10093 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10094 // Point to variable declaration.
10095 if (const ValueDecl *VD = DRE->getDecl()) {
10096 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10097 if (!DiagnosticEmitted) {
10098 S.Diag(Loc, diag::err_typecheck_assign_const)
10099 << ExprRange << ConstVariable << VD << VD->getType();
10100 DiagnosticEmitted = true;
10102 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10103 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10106 } else if (isa<CXXThisExpr>(E)) {
10107 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10108 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10109 if (MD->isConst()) {
10110 if (!DiagnosticEmitted) {
10111 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10112 << ConstMethod << MD;
10113 DiagnosticEmitted = true;
10115 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10116 << ConstMethod << MD << MD->getSourceRange();
10122 if (DiagnosticEmitted)
10125 // Can't determine a more specific message, so display the generic error.
10126 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10129 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
10130 /// emit an error and return true. If so, return false.
10131 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10132 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10134 S.CheckShadowingDeclModification(E, Loc);
10136 SourceLocation OrigLoc = Loc;
10137 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10139 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10140 IsLV = Expr::MLV_InvalidMessageExpression;
10141 if (IsLV == Expr::MLV_Valid)
10144 unsigned DiagID = 0;
10145 bool NeedType = false;
10146 switch (IsLV) { // C99 6.5.16p2
10147 case Expr::MLV_ConstQualified:
10148 // Use a specialized diagnostic when we're assigning to an object
10149 // from an enclosing function or block.
10150 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10151 if (NCCK == NCCK_Block)
10152 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10154 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10158 // In ARC, use some specialized diagnostics for occasions where we
10159 // infer 'const'. These are always pseudo-strong variables.
10160 if (S.getLangOpts().ObjCAutoRefCount) {
10161 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10162 if (declRef && isa<VarDecl>(declRef->getDecl())) {
10163 VarDecl *var = cast<VarDecl>(declRef->getDecl());
10165 // Use the normal diagnostic if it's pseudo-__strong but the
10166 // user actually wrote 'const'.
10167 if (var->isARCPseudoStrong() &&
10168 (!var->getTypeSourceInfo() ||
10169 !var->getTypeSourceInfo()->getType().isConstQualified())) {
10170 // There are two pseudo-strong cases:
10172 ObjCMethodDecl *method = S.getCurMethodDecl();
10173 if (method && var == method->getSelfDecl())
10174 DiagID = method->isClassMethod()
10175 ? diag::err_typecheck_arc_assign_self_class_method
10176 : diag::err_typecheck_arc_assign_self;
10178 // - fast enumeration variables
10180 DiagID = diag::err_typecheck_arr_assign_enumeration;
10182 SourceRange Assign;
10183 if (Loc != OrigLoc)
10184 Assign = SourceRange(OrigLoc, OrigLoc);
10185 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10186 // We need to preserve the AST regardless, so migration tool
10193 // If none of the special cases above are triggered, then this is a
10194 // simple const assignment.
10196 DiagnoseConstAssignment(S, E, Loc);
10201 case Expr::MLV_ConstAddrSpace:
10202 DiagnoseConstAssignment(S, E, Loc);
10204 case Expr::MLV_ArrayType:
10205 case Expr::MLV_ArrayTemporary:
10206 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10209 case Expr::MLV_NotObjectType:
10210 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10213 case Expr::MLV_LValueCast:
10214 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10216 case Expr::MLV_Valid:
10217 llvm_unreachable("did not take early return for MLV_Valid");
10218 case Expr::MLV_InvalidExpression:
10219 case Expr::MLV_MemberFunction:
10220 case Expr::MLV_ClassTemporary:
10221 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10223 case Expr::MLV_IncompleteType:
10224 case Expr::MLV_IncompleteVoidType:
10225 return S.RequireCompleteType(Loc, E->getType(),
10226 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10227 case Expr::MLV_DuplicateVectorComponents:
10228 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10230 case Expr::MLV_NoSetterProperty:
10231 llvm_unreachable("readonly properties should be processed differently");
10232 case Expr::MLV_InvalidMessageExpression:
10233 DiagID = diag::err_readonly_message_assignment;
10235 case Expr::MLV_SubObjCPropertySetting:
10236 DiagID = diag::err_no_subobject_property_setting;
10240 SourceRange Assign;
10241 if (Loc != OrigLoc)
10242 Assign = SourceRange(OrigLoc, OrigLoc);
10244 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10246 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10250 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10251 SourceLocation Loc,
10254 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10255 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10256 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10257 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10258 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10261 // Objective-C instance variables
10262 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10263 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10264 if (OL && OR && OL->getDecl() == OR->getDecl()) {
10265 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10266 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10267 if (RL && RR && RL->getDecl() == RR->getDecl())
10268 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10273 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10274 SourceLocation Loc,
10275 QualType CompoundType) {
10276 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10278 // Verify that LHS is a modifiable lvalue, and emit error if not.
10279 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10282 QualType LHSType = LHSExpr->getType();
10283 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10285 // OpenCL v1.2 s6.1.1.1 p2:
10286 // The half data type can only be used to declare a pointer to a buffer that
10287 // contains half values
10288 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10289 LHSType->isHalfType()) {
10290 Diag(Loc, diag::err_opencl_half_load_store) << 1
10291 << LHSType.getUnqualifiedType();
10295 AssignConvertType ConvTy;
10296 if (CompoundType.isNull()) {
10297 Expr *RHSCheck = RHS.get();
10299 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10301 QualType LHSTy(LHSType);
10302 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10303 if (RHS.isInvalid())
10305 // Special case of NSObject attributes on c-style pointer types.
10306 if (ConvTy == IncompatiblePointer &&
10307 ((Context.isObjCNSObjectType(LHSType) &&
10308 RHSType->isObjCObjectPointerType()) ||
10309 (Context.isObjCNSObjectType(RHSType) &&
10310 LHSType->isObjCObjectPointerType())))
10311 ConvTy = Compatible;
10313 if (ConvTy == Compatible &&
10314 LHSType->isObjCObjectType())
10315 Diag(Loc, diag::err_objc_object_assignment)
10318 // If the RHS is a unary plus or minus, check to see if they = and + are
10319 // right next to each other. If so, the user may have typo'd "x =+ 4"
10320 // instead of "x += 4".
10321 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10322 RHSCheck = ICE->getSubExpr();
10323 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10324 if ((UO->getOpcode() == UO_Plus ||
10325 UO->getOpcode() == UO_Minus) &&
10326 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10327 // Only if the two operators are exactly adjacent.
10328 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10329 // And there is a space or other character before the subexpr of the
10330 // unary +/-. We don't want to warn on "x=-1".
10331 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10332 UO->getSubExpr()->getLocStart().isFileID()) {
10333 Diag(Loc, diag::warn_not_compound_assign)
10334 << (UO->getOpcode() == UO_Plus ? "+" : "-")
10335 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10339 if (ConvTy == Compatible) {
10340 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10341 // Warn about retain cycles where a block captures the LHS, but
10342 // not if the LHS is a simple variable into which the block is
10343 // being stored...unless that variable can be captured by reference!
10344 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10345 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10346 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10347 checkRetainCycles(LHSExpr, RHS.get());
10350 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10351 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10352 // It is safe to assign a weak reference into a strong variable.
10353 // Although this code can still have problems:
10354 // id x = self.weakProp;
10355 // id y = self.weakProp;
10356 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10357 // paths through the function. This should be revisited if
10358 // -Wrepeated-use-of-weak is made flow-sensitive.
10359 // For ObjCWeak only, we do not warn if the assign is to a non-weak
10360 // variable, which will be valid for the current autorelease scope.
10361 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10362 RHS.get()->getLocStart()))
10363 getCurFunction()->markSafeWeakUse(RHS.get());
10365 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10366 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10370 // Compound assignment "x += y"
10371 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10374 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10375 RHS.get(), AA_Assigning))
10378 CheckForNullPointerDereference(*this, LHSExpr);
10380 // C99 6.5.16p3: The type of an assignment expression is the type of the
10381 // left operand unless the left operand has qualified type, in which case
10382 // it is the unqualified version of the type of the left operand.
10383 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10384 // is converted to the type of the assignment expression (above).
10385 // C++ 5.17p1: the type of the assignment expression is that of its left
10387 return (getLangOpts().CPlusPlus
10388 ? LHSType : LHSType.getUnqualifiedType());
10391 // Only ignore explicit casts to void.
10392 static bool IgnoreCommaOperand(const Expr *E) {
10393 E = E->IgnoreParens();
10395 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10396 if (CE->getCastKind() == CK_ToVoid) {
10404 // Look for instances where it is likely the comma operator is confused with
10405 // another operator. There is a whitelist of acceptable expressions for the
10406 // left hand side of the comma operator, otherwise emit a warning.
10407 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10408 // No warnings in macros
10409 if (Loc.isMacroID())
10412 // Don't warn in template instantiations.
10413 if (inTemplateInstantiation())
10416 // Scope isn't fine-grained enough to whitelist the specific cases, so
10417 // instead, skip more than needed, then call back into here with the
10418 // CommaVisitor in SemaStmt.cpp.
10419 // The whitelisted locations are the initialization and increment portions
10420 // of a for loop. The additional checks are on the condition of
10421 // if statements, do/while loops, and for loops.
10422 const unsigned ForIncrementFlags =
10423 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10424 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10425 const unsigned ScopeFlags = getCurScope()->getFlags();
10426 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10427 (ScopeFlags & ForInitFlags) == ForInitFlags)
10430 // If there are multiple comma operators used together, get the RHS of the
10431 // of the comma operator as the LHS.
10432 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10433 if (BO->getOpcode() != BO_Comma)
10435 LHS = BO->getRHS();
10438 // Only allow some expressions on LHS to not warn.
10439 if (IgnoreCommaOperand(LHS))
10442 Diag(Loc, diag::warn_comma_operator);
10443 Diag(LHS->getLocStart(), diag::note_cast_to_void)
10444 << LHS->getSourceRange()
10445 << FixItHint::CreateInsertion(LHS->getLocStart(),
10446 LangOpts.CPlusPlus ? "static_cast<void>("
10448 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10453 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10454 SourceLocation Loc) {
10455 LHS = S.CheckPlaceholderExpr(LHS.get());
10456 RHS = S.CheckPlaceholderExpr(RHS.get());
10457 if (LHS.isInvalid() || RHS.isInvalid())
10460 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10461 // operands, but not unary promotions.
10462 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10464 // So we treat the LHS as a ignored value, and in C++ we allow the
10465 // containing site to determine what should be done with the RHS.
10466 LHS = S.IgnoredValueConversions(LHS.get());
10467 if (LHS.isInvalid())
10470 S.DiagnoseUnusedExprResult(LHS.get());
10472 if (!S.getLangOpts().CPlusPlus) {
10473 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10474 if (RHS.isInvalid())
10476 if (!RHS.get()->getType()->isVoidType())
10477 S.RequireCompleteType(Loc, RHS.get()->getType(),
10478 diag::err_incomplete_type);
10481 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10482 S.DiagnoseCommaOperator(LHS.get(), Loc);
10484 return RHS.get()->getType();
10487 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10488 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10489 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10491 ExprObjectKind &OK,
10492 SourceLocation OpLoc,
10493 bool IsInc, bool IsPrefix) {
10494 if (Op->isTypeDependent())
10495 return S.Context.DependentTy;
10497 QualType ResType = Op->getType();
10498 // Atomic types can be used for increment / decrement where the non-atomic
10499 // versions can, so ignore the _Atomic() specifier for the purpose of
10501 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10502 ResType = ResAtomicType->getValueType();
10504 assert(!ResType.isNull() && "no type for increment/decrement expression");
10506 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10507 // Decrement of bool is not allowed.
10509 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10512 // Increment of bool sets it to true, but is deprecated.
10513 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10514 : diag::warn_increment_bool)
10515 << Op->getSourceRange();
10516 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10517 // Error on enum increments and decrements in C++ mode
10518 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10520 } else if (ResType->isRealType()) {
10522 } else if (ResType->isPointerType()) {
10523 // C99 6.5.2.4p2, 6.5.6p2
10524 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10526 } else if (ResType->isObjCObjectPointerType()) {
10527 // On modern runtimes, ObjC pointer arithmetic is forbidden.
10528 // Otherwise, we just need a complete type.
10529 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10530 checkArithmeticOnObjCPointer(S, OpLoc, Op))
10532 } else if (ResType->isAnyComplexType()) {
10533 // C99 does not support ++/-- on complex types, we allow as an extension.
10534 S.Diag(OpLoc, diag::ext_integer_increment_complex)
10535 << ResType << Op->getSourceRange();
10536 } else if (ResType->isPlaceholderType()) {
10537 ExprResult PR = S.CheckPlaceholderExpr(Op);
10538 if (PR.isInvalid()) return QualType();
10539 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10541 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10542 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10543 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10544 (ResType->getAs<VectorType>()->getVectorKind() !=
10545 VectorType::AltiVecBool)) {
10546 // The z vector extensions allow ++ and -- for non-bool vectors.
10547 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10548 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10549 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10551 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10552 << ResType << int(IsInc) << Op->getSourceRange();
10555 // At this point, we know we have a real, complex or pointer type.
10556 // Now make sure the operand is a modifiable lvalue.
10557 if (CheckForModifiableLvalue(Op, OpLoc, S))
10559 // In C++, a prefix increment is the same type as the operand. Otherwise
10560 // (in C or with postfix), the increment is the unqualified type of the
10562 if (IsPrefix && S.getLangOpts().CPlusPlus) {
10564 OK = Op->getObjectKind();
10568 return ResType.getUnqualifiedType();
10573 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10574 /// This routine allows us to typecheck complex/recursive expressions
10575 /// where the declaration is needed for type checking. We only need to
10576 /// handle cases when the expression references a function designator
10577 /// or is an lvalue. Here are some examples:
10579 /// - &*****f => f for f a function designator.
10581 /// - &s.zz[1].yy -> s, if zz is an array
10582 /// - *(x + 1) -> x, if x is an array
10583 /// - &"123"[2] -> 0
10584 /// - & __real__ x -> x
10585 static ValueDecl *getPrimaryDecl(Expr *E) {
10586 switch (E->getStmtClass()) {
10587 case Stmt::DeclRefExprClass:
10588 return cast<DeclRefExpr>(E)->getDecl();
10589 case Stmt::MemberExprClass:
10590 // If this is an arrow operator, the address is an offset from
10591 // the base's value, so the object the base refers to is
10593 if (cast<MemberExpr>(E)->isArrow())
10595 // Otherwise, the expression refers to a part of the base
10596 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10597 case Stmt::ArraySubscriptExprClass: {
10598 // FIXME: This code shouldn't be necessary! We should catch the implicit
10599 // promotion of register arrays earlier.
10600 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10601 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10602 if (ICE->getSubExpr()->getType()->isArrayType())
10603 return getPrimaryDecl(ICE->getSubExpr());
10607 case Stmt::UnaryOperatorClass: {
10608 UnaryOperator *UO = cast<UnaryOperator>(E);
10610 switch(UO->getOpcode()) {
10614 return getPrimaryDecl(UO->getSubExpr());
10619 case Stmt::ParenExprClass:
10620 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10621 case Stmt::ImplicitCastExprClass:
10622 // If the result of an implicit cast is an l-value, we care about
10623 // the sub-expression; otherwise, the result here doesn't matter.
10624 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10633 AO_Vector_Element = 1,
10634 AO_Property_Expansion = 2,
10635 AO_Register_Variable = 3,
10639 /// \brief Diagnose invalid operand for address of operations.
10641 /// \param Type The type of operand which cannot have its address taken.
10642 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10643 Expr *E, unsigned Type) {
10644 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10647 /// CheckAddressOfOperand - The operand of & must be either a function
10648 /// designator or an lvalue designating an object. If it is an lvalue, the
10649 /// object cannot be declared with storage class register or be a bit field.
10650 /// Note: The usual conversions are *not* applied to the operand of the &
10651 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10652 /// In C++, the operand might be an overloaded function name, in which case
10653 /// we allow the '&' but retain the overloaded-function type.
10654 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10655 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10656 if (PTy->getKind() == BuiltinType::Overload) {
10657 Expr *E = OrigOp.get()->IgnoreParens();
10658 if (!isa<OverloadExpr>(E)) {
10659 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10660 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10661 << OrigOp.get()->getSourceRange();
10665 OverloadExpr *Ovl = cast<OverloadExpr>(E);
10666 if (isa<UnresolvedMemberExpr>(Ovl))
10667 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10668 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10669 << OrigOp.get()->getSourceRange();
10673 return Context.OverloadTy;
10676 if (PTy->getKind() == BuiltinType::UnknownAny)
10677 return Context.UnknownAnyTy;
10679 if (PTy->getKind() == BuiltinType::BoundMember) {
10680 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10681 << OrigOp.get()->getSourceRange();
10685 OrigOp = CheckPlaceholderExpr(OrigOp.get());
10686 if (OrigOp.isInvalid()) return QualType();
10689 if (OrigOp.get()->isTypeDependent())
10690 return Context.DependentTy;
10692 assert(!OrigOp.get()->getType()->isPlaceholderType());
10694 // Make sure to ignore parentheses in subsequent checks
10695 Expr *op = OrigOp.get()->IgnoreParens();
10697 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10698 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10699 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10703 if (getLangOpts().C99) {
10704 // Implement C99-only parts of addressof rules.
10705 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10706 if (uOp->getOpcode() == UO_Deref)
10707 // Per C99 6.5.3.2, the address of a deref always returns a valid result
10708 // (assuming the deref expression is valid).
10709 return uOp->getSubExpr()->getType();
10711 // Technically, there should be a check for array subscript
10712 // expressions here, but the result of one is always an lvalue anyway.
10714 ValueDecl *dcl = getPrimaryDecl(op);
10716 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10717 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10718 op->getLocStart()))
10721 Expr::LValueClassification lval = op->ClassifyLValue(Context);
10722 unsigned AddressOfError = AO_No_Error;
10724 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10725 bool sfinae = (bool)isSFINAEContext();
10726 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10727 : diag::ext_typecheck_addrof_temporary)
10728 << op->getType() << op->getSourceRange();
10731 // Materialize the temporary as an lvalue so that we can take its address.
10733 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10734 } else if (isa<ObjCSelectorExpr>(op)) {
10735 return Context.getPointerType(op->getType());
10736 } else if (lval == Expr::LV_MemberFunction) {
10737 // If it's an instance method, make a member pointer.
10738 // The expression must have exactly the form &A::foo.
10740 // If the underlying expression isn't a decl ref, give up.
10741 if (!isa<DeclRefExpr>(op)) {
10742 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10743 << OrigOp.get()->getSourceRange();
10746 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10747 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10749 // The id-expression was parenthesized.
10750 if (OrigOp.get() != DRE) {
10751 Diag(OpLoc, diag::err_parens_pointer_member_function)
10752 << OrigOp.get()->getSourceRange();
10754 // The method was named without a qualifier.
10755 } else if (!DRE->getQualifier()) {
10756 if (MD->getParent()->getName().empty())
10757 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10758 << op->getSourceRange();
10760 SmallString<32> Str;
10761 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10762 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10763 << op->getSourceRange()
10764 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10768 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10769 if (isa<CXXDestructorDecl>(MD))
10770 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10772 QualType MPTy = Context.getMemberPointerType(
10773 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10774 // Under the MS ABI, lock down the inheritance model now.
10775 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10776 (void)isCompleteType(OpLoc, MPTy);
10778 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10780 // The operand must be either an l-value or a function designator
10781 if (!op->getType()->isFunctionType()) {
10782 // Use a special diagnostic for loads from property references.
10783 if (isa<PseudoObjectExpr>(op)) {
10784 AddressOfError = AO_Property_Expansion;
10786 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10787 << op->getType() << op->getSourceRange();
10791 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10792 // The operand cannot be a bit-field
10793 AddressOfError = AO_Bit_Field;
10794 } else if (op->getObjectKind() == OK_VectorComponent) {
10795 // The operand cannot be an element of a vector
10796 AddressOfError = AO_Vector_Element;
10797 } else if (dcl) { // C99 6.5.3.2p1
10798 // We have an lvalue with a decl. Make sure the decl is not declared
10799 // with the register storage-class specifier.
10800 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10801 // in C++ it is not error to take address of a register
10802 // variable (c++03 7.1.1P3)
10803 if (vd->getStorageClass() == SC_Register &&
10804 !getLangOpts().CPlusPlus) {
10805 AddressOfError = AO_Register_Variable;
10807 } else if (isa<MSPropertyDecl>(dcl)) {
10808 AddressOfError = AO_Property_Expansion;
10809 } else if (isa<FunctionTemplateDecl>(dcl)) {
10810 return Context.OverloadTy;
10811 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10812 // Okay: we can take the address of a field.
10813 // Could be a pointer to member, though, if there is an explicit
10814 // scope qualifier for the class.
10815 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10816 DeclContext *Ctx = dcl->getDeclContext();
10817 if (Ctx && Ctx->isRecord()) {
10818 if (dcl->getType()->isReferenceType()) {
10820 diag::err_cannot_form_pointer_to_member_of_reference_type)
10821 << dcl->getDeclName() << dcl->getType();
10825 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10826 Ctx = Ctx->getParent();
10828 QualType MPTy = Context.getMemberPointerType(
10830 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10831 // Under the MS ABI, lock down the inheritance model now.
10832 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10833 (void)isCompleteType(OpLoc, MPTy);
10837 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10838 !isa<BindingDecl>(dcl))
10839 llvm_unreachable("Unknown/unexpected decl type");
10842 if (AddressOfError != AO_No_Error) {
10843 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10847 if (lval == Expr::LV_IncompleteVoidType) {
10848 // Taking the address of a void variable is technically illegal, but we
10849 // allow it in cases which are otherwise valid.
10850 // Example: "extern void x; void* y = &x;".
10851 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10854 // If the operand has type "type", the result has type "pointer to type".
10855 if (op->getType()->isObjCObjectType())
10856 return Context.getObjCObjectPointerType(op->getType());
10858 CheckAddressOfPackedMember(op);
10860 return Context.getPointerType(op->getType());
10863 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10864 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10867 const Decl *D = DRE->getDecl();
10870 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10873 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10874 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10876 if (FunctionScopeInfo *FD = S.getCurFunction())
10877 if (!FD->ModifiedNonNullParams.count(Param))
10878 FD->ModifiedNonNullParams.insert(Param);
10881 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10882 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10883 SourceLocation OpLoc) {
10884 if (Op->isTypeDependent())
10885 return S.Context.DependentTy;
10887 ExprResult ConvResult = S.UsualUnaryConversions(Op);
10888 if (ConvResult.isInvalid())
10890 Op = ConvResult.get();
10891 QualType OpTy = Op->getType();
10894 if (isa<CXXReinterpretCastExpr>(Op)) {
10895 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10896 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10897 Op->getSourceRange());
10900 if (const PointerType *PT = OpTy->getAs<PointerType>())
10902 Result = PT->getPointeeType();
10904 else if (const ObjCObjectPointerType *OPT =
10905 OpTy->getAs<ObjCObjectPointerType>())
10906 Result = OPT->getPointeeType();
10908 ExprResult PR = S.CheckPlaceholderExpr(Op);
10909 if (PR.isInvalid()) return QualType();
10910 if (PR.get() != Op)
10911 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10914 if (Result.isNull()) {
10915 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10916 << OpTy << Op->getSourceRange();
10920 // Note that per both C89 and C99, indirection is always legal, even if Result
10921 // is an incomplete type or void. It would be possible to warn about
10922 // dereferencing a void pointer, but it's completely well-defined, and such a
10923 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10924 // for pointers to 'void' but is fine for any other pointer type:
10926 // C++ [expr.unary.op]p1:
10927 // [...] the expression to which [the unary * operator] is applied shall
10928 // be a pointer to an object type, or a pointer to a function type
10929 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10930 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10931 << OpTy << Op->getSourceRange();
10933 // Dereferences are usually l-values...
10936 // ...except that certain expressions are never l-values in C.
10937 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10943 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10944 BinaryOperatorKind Opc;
10946 default: llvm_unreachable("Unknown binop!");
10947 case tok::periodstar: Opc = BO_PtrMemD; break;
10948 case tok::arrowstar: Opc = BO_PtrMemI; break;
10949 case tok::star: Opc = BO_Mul; break;
10950 case tok::slash: Opc = BO_Div; break;
10951 case tok::percent: Opc = BO_Rem; break;
10952 case tok::plus: Opc = BO_Add; break;
10953 case tok::minus: Opc = BO_Sub; break;
10954 case tok::lessless: Opc = BO_Shl; break;
10955 case tok::greatergreater: Opc = BO_Shr; break;
10956 case tok::lessequal: Opc = BO_LE; break;
10957 case tok::less: Opc = BO_LT; break;
10958 case tok::greaterequal: Opc = BO_GE; break;
10959 case tok::greater: Opc = BO_GT; break;
10960 case tok::exclaimequal: Opc = BO_NE; break;
10961 case tok::equalequal: Opc = BO_EQ; break;
10962 case tok::amp: Opc = BO_And; break;
10963 case tok::caret: Opc = BO_Xor; break;
10964 case tok::pipe: Opc = BO_Or; break;
10965 case tok::ampamp: Opc = BO_LAnd; break;
10966 case tok::pipepipe: Opc = BO_LOr; break;
10967 case tok::equal: Opc = BO_Assign; break;
10968 case tok::starequal: Opc = BO_MulAssign; break;
10969 case tok::slashequal: Opc = BO_DivAssign; break;
10970 case tok::percentequal: Opc = BO_RemAssign; break;
10971 case tok::plusequal: Opc = BO_AddAssign; break;
10972 case tok::minusequal: Opc = BO_SubAssign; break;
10973 case tok::lesslessequal: Opc = BO_ShlAssign; break;
10974 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
10975 case tok::ampequal: Opc = BO_AndAssign; break;
10976 case tok::caretequal: Opc = BO_XorAssign; break;
10977 case tok::pipeequal: Opc = BO_OrAssign; break;
10978 case tok::comma: Opc = BO_Comma; break;
10983 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10984 tok::TokenKind Kind) {
10985 UnaryOperatorKind Opc;
10987 default: llvm_unreachable("Unknown unary op!");
10988 case tok::plusplus: Opc = UO_PreInc; break;
10989 case tok::minusminus: Opc = UO_PreDec; break;
10990 case tok::amp: Opc = UO_AddrOf; break;
10991 case tok::star: Opc = UO_Deref; break;
10992 case tok::plus: Opc = UO_Plus; break;
10993 case tok::minus: Opc = UO_Minus; break;
10994 case tok::tilde: Opc = UO_Not; break;
10995 case tok::exclaim: Opc = UO_LNot; break;
10996 case tok::kw___real: Opc = UO_Real; break;
10997 case tok::kw___imag: Opc = UO_Imag; break;
10998 case tok::kw___extension__: Opc = UO_Extension; break;
11003 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11004 /// This warning is only emitted for builtin assignment operations. It is also
11005 /// suppressed in the event of macro expansions.
11006 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11007 SourceLocation OpLoc) {
11008 if (S.inTemplateInstantiation())
11010 if (OpLoc.isInvalid() || OpLoc.isMacroID())
11012 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11013 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11014 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11015 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11016 if (!LHSDeclRef || !RHSDeclRef ||
11017 LHSDeclRef->getLocation().isMacroID() ||
11018 RHSDeclRef->getLocation().isMacroID())
11020 const ValueDecl *LHSDecl =
11021 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11022 const ValueDecl *RHSDecl =
11023 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11024 if (LHSDecl != RHSDecl)
11026 if (LHSDecl->getType().isVolatileQualified())
11028 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11029 if (RefTy->getPointeeType().isVolatileQualified())
11032 S.Diag(OpLoc, diag::warn_self_assignment)
11033 << LHSDeclRef->getType()
11034 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11037 /// Check if a bitwise-& is performed on an Objective-C pointer. This
11038 /// is usually indicative of introspection within the Objective-C pointer.
11039 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11040 SourceLocation OpLoc) {
11041 if (!S.getLangOpts().ObjC1)
11044 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11045 const Expr *LHS = L.get();
11046 const Expr *RHS = R.get();
11048 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11049 ObjCPointerExpr = LHS;
11052 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11053 ObjCPointerExpr = RHS;
11057 // This warning is deliberately made very specific to reduce false
11058 // positives with logic that uses '&' for hashing. This logic mainly
11059 // looks for code trying to introspect into tagged pointers, which
11060 // code should generally never do.
11061 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11062 unsigned Diag = diag::warn_objc_pointer_masking;
11063 // Determine if we are introspecting the result of performSelectorXXX.
11064 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11065 // Special case messages to -performSelector and friends, which
11066 // can return non-pointer values boxed in a pointer value.
11067 // Some clients may wish to silence warnings in this subcase.
11068 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11069 Selector S = ME->getSelector();
11070 StringRef SelArg0 = S.getNameForSlot(0);
11071 if (SelArg0.startswith("performSelector"))
11072 Diag = diag::warn_objc_pointer_masking_performSelector;
11075 S.Diag(OpLoc, Diag)
11076 << ObjCPointerExpr->getSourceRange();
11080 static NamedDecl *getDeclFromExpr(Expr *E) {
11083 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11084 return DRE->getDecl();
11085 if (auto *ME = dyn_cast<MemberExpr>(E))
11086 return ME->getMemberDecl();
11087 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11088 return IRE->getDecl();
11092 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11093 /// operator @p Opc at location @c TokLoc. This routine only supports
11094 /// built-in operations; ActOnBinOp handles overloaded operators.
11095 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11096 BinaryOperatorKind Opc,
11097 Expr *LHSExpr, Expr *RHSExpr) {
11098 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11099 // The syntax only allows initializer lists on the RHS of assignment,
11100 // so we don't need to worry about accepting invalid code for
11101 // non-assignment operators.
11103 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11104 // of x = {} is x = T().
11105 InitializationKind Kind =
11106 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11107 InitializedEntity Entity =
11108 InitializedEntity::InitializeTemporary(LHSExpr->getType());
11109 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11110 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11111 if (Init.isInvalid())
11113 RHSExpr = Init.get();
11116 ExprResult LHS = LHSExpr, RHS = RHSExpr;
11117 QualType ResultTy; // Result type of the binary operator.
11118 // The following two variables are used for compound assignment operators
11119 QualType CompLHSTy; // Type of LHS after promotions for computation
11120 QualType CompResultTy; // Type of computation result
11121 ExprValueKind VK = VK_RValue;
11122 ExprObjectKind OK = OK_Ordinary;
11124 if (!getLangOpts().CPlusPlus) {
11125 // C cannot handle TypoExpr nodes on either side of a binop because it
11126 // doesn't handle dependent types properly, so make sure any TypoExprs have
11127 // been dealt with before checking the operands.
11128 LHS = CorrectDelayedTyposInExpr(LHSExpr);
11129 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11130 if (Opc != BO_Assign)
11131 return ExprResult(E);
11132 // Avoid correcting the RHS to the same Expr as the LHS.
11133 Decl *D = getDeclFromExpr(E);
11134 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11136 if (!LHS.isUsable() || !RHS.isUsable())
11137 return ExprError();
11140 if (getLangOpts().OpenCL) {
11141 QualType LHSTy = LHSExpr->getType();
11142 QualType RHSTy = RHSExpr->getType();
11143 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11144 // the ATOMIC_VAR_INIT macro.
11145 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11146 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11147 if (BO_Assign == Opc)
11148 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11150 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11151 return ExprError();
11154 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11155 // only with a builtin functions and therefore should be disallowed here.
11156 if (LHSTy->isImageType() || RHSTy->isImageType() ||
11157 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11158 LHSTy->isPipeType() || RHSTy->isPipeType() ||
11159 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11160 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11161 return ExprError();
11167 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11168 if (getLangOpts().CPlusPlus &&
11169 LHS.get()->getObjectKind() != OK_ObjCProperty) {
11170 VK = LHS.get()->getValueKind();
11171 OK = LHS.get()->getObjectKind();
11173 if (!ResultTy.isNull()) {
11174 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11175 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11177 RecordModifiableNonNullParam(*this, LHS.get());
11181 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11182 Opc == BO_PtrMemI);
11186 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11190 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11193 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11196 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11200 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11206 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11210 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11213 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11216 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11220 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11224 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11225 Opc == BO_DivAssign);
11226 CompLHSTy = CompResultTy;
11227 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11228 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11231 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11232 CompLHSTy = CompResultTy;
11233 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11234 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11237 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11238 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11239 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11242 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11243 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11244 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11248 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11249 CompLHSTy = CompResultTy;
11250 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11251 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11254 case BO_OrAssign: // fallthrough
11255 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11257 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11258 CompLHSTy = CompResultTy;
11259 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11260 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11263 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11264 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11265 VK = RHS.get()->getValueKind();
11266 OK = RHS.get()->getObjectKind();
11270 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11271 return ExprError();
11273 // Check for array bounds violations for both sides of the BinaryOperator
11274 CheckArrayAccess(LHS.get());
11275 CheckArrayAccess(RHS.get());
11277 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11278 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11279 &Context.Idents.get("object_setClass"),
11280 SourceLocation(), LookupOrdinaryName);
11281 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11282 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11283 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11284 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11285 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11286 FixItHint::CreateInsertion(RHSLocEnd, ")");
11289 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11291 else if (const ObjCIvarRefExpr *OIRE =
11292 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11293 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11295 if (CompResultTy.isNull())
11296 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11297 OK, OpLoc, FPFeatures);
11298 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11301 OK = LHS.get()->getObjectKind();
11303 return new (Context) CompoundAssignOperator(
11304 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11305 OpLoc, FPFeatures);
11308 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11309 /// operators are mixed in a way that suggests that the programmer forgot that
11310 /// comparison operators have higher precedence. The most typical example of
11311 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11312 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11313 SourceLocation OpLoc, Expr *LHSExpr,
11315 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11316 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11318 // Check that one of the sides is a comparison operator and the other isn't.
11319 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11320 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11321 if (isLeftComp == isRightComp)
11324 // Bitwise operations are sometimes used as eager logical ops.
11325 // Don't diagnose this.
11326 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11327 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11328 if (isLeftBitwise || isRightBitwise)
11331 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11333 : SourceRange(OpLoc, RHSExpr->getLocEnd());
11334 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11335 SourceRange ParensRange = isLeftComp ?
11336 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11337 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11339 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11340 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11341 SuggestParentheses(Self, OpLoc,
11342 Self.PDiag(diag::note_precedence_silence) << OpStr,
11343 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11344 SuggestParentheses(Self, OpLoc,
11345 Self.PDiag(diag::note_precedence_bitwise_first)
11346 << BinaryOperator::getOpcodeStr(Opc),
11350 /// \brief It accepts a '&&' expr that is inside a '||' one.
11351 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11352 /// in parentheses.
11354 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11355 BinaryOperator *Bop) {
11356 assert(Bop->getOpcode() == BO_LAnd);
11357 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11358 << Bop->getSourceRange() << OpLoc;
11359 SuggestParentheses(Self, Bop->getOperatorLoc(),
11360 Self.PDiag(diag::note_precedence_silence)
11361 << Bop->getOpcodeStr(),
11362 Bop->getSourceRange());
11365 /// \brief Returns true if the given expression can be evaluated as a constant
11367 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11369 return !E->isValueDependent() &&
11370 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11373 /// \brief Returns true if the given expression can be evaluated as a constant
11375 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11377 return !E->isValueDependent() &&
11378 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11381 /// \brief Look for '&&' in the left hand of a '||' expr.
11382 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11383 Expr *LHSExpr, Expr *RHSExpr) {
11384 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11385 if (Bop->getOpcode() == BO_LAnd) {
11386 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11387 if (EvaluatesAsFalse(S, RHSExpr))
11389 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11390 if (!EvaluatesAsTrue(S, Bop->getLHS()))
11391 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11392 } else if (Bop->getOpcode() == BO_LOr) {
11393 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11394 // If it's "a || b && 1 || c" we didn't warn earlier for
11395 // "a || b && 1", but warn now.
11396 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11397 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11403 /// \brief Look for '&&' in the right hand of a '||' expr.
11404 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11405 Expr *LHSExpr, Expr *RHSExpr) {
11406 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11407 if (Bop->getOpcode() == BO_LAnd) {
11408 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11409 if (EvaluatesAsFalse(S, LHSExpr))
11411 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11412 if (!EvaluatesAsTrue(S, Bop->getRHS()))
11413 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11418 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11419 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11420 /// the '&' expression in parentheses.
11421 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11422 SourceLocation OpLoc, Expr *SubExpr) {
11423 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11424 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11425 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11426 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11427 << Bop->getSourceRange() << OpLoc;
11428 SuggestParentheses(S, Bop->getOperatorLoc(),
11429 S.PDiag(diag::note_precedence_silence)
11430 << Bop->getOpcodeStr(),
11431 Bop->getSourceRange());
11436 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11437 Expr *SubExpr, StringRef Shift) {
11438 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11439 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11440 StringRef Op = Bop->getOpcodeStr();
11441 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11442 << Bop->getSourceRange() << OpLoc << Shift << Op;
11443 SuggestParentheses(S, Bop->getOperatorLoc(),
11444 S.PDiag(diag::note_precedence_silence) << Op,
11445 Bop->getSourceRange());
11450 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11451 Expr *LHSExpr, Expr *RHSExpr) {
11452 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11456 FunctionDecl *FD = OCE->getDirectCallee();
11457 if (!FD || !FD->isOverloadedOperator())
11460 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11461 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11464 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11465 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11466 << (Kind == OO_LessLess);
11467 SuggestParentheses(S, OCE->getOperatorLoc(),
11468 S.PDiag(diag::note_precedence_silence)
11469 << (Kind == OO_LessLess ? "<<" : ">>"),
11470 OCE->getSourceRange());
11471 SuggestParentheses(S, OpLoc,
11472 S.PDiag(diag::note_evaluate_comparison_first),
11473 SourceRange(OCE->getArg(1)->getLocStart(),
11474 RHSExpr->getLocEnd()));
11477 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11479 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11480 SourceLocation OpLoc, Expr *LHSExpr,
11482 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11483 if (BinaryOperator::isBitwiseOp(Opc))
11484 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11486 // Diagnose "arg1 & arg2 | arg3"
11487 if ((Opc == BO_Or || Opc == BO_Xor) &&
11488 !OpLoc.isMacroID()/* Don't warn in macros. */) {
11489 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11490 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11493 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11494 // We don't warn for 'assert(a || b && "bad")' since this is safe.
11495 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11496 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11497 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11500 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11501 || Opc == BO_Shr) {
11502 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11503 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11504 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11507 // Warn on overloaded shift operators and comparisons, such as:
11509 if (BinaryOperator::isComparisonOp(Opc))
11510 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11513 // Binary Operators. 'Tok' is the token for the operator.
11514 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11515 tok::TokenKind Kind,
11516 Expr *LHSExpr, Expr *RHSExpr) {
11517 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11518 assert(LHSExpr && "ActOnBinOp(): missing left expression");
11519 assert(RHSExpr && "ActOnBinOp(): missing right expression");
11521 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11522 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11524 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11527 /// Build an overloaded binary operator expression in the given scope.
11528 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11529 BinaryOperatorKind Opc,
11530 Expr *LHS, Expr *RHS) {
11531 // Find all of the overloaded operators visible from this
11532 // point. We perform both an operator-name lookup from the local
11533 // scope and an argument-dependent lookup based on the types of
11535 UnresolvedSet<16> Functions;
11536 OverloadedOperatorKind OverOp
11537 = BinaryOperator::getOverloadedOperator(Opc);
11538 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11539 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11540 RHS->getType(), Functions);
11542 // Build the (potentially-overloaded, potentially-dependent)
11543 // binary operation.
11544 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11547 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11548 BinaryOperatorKind Opc,
11549 Expr *LHSExpr, Expr *RHSExpr) {
11550 // We want to end up calling one of checkPseudoObjectAssignment
11551 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11552 // both expressions are overloadable or either is type-dependent),
11553 // or CreateBuiltinBinOp (in any other case). We also want to get
11554 // any placeholder types out of the way.
11556 // Handle pseudo-objects in the LHS.
11557 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11558 // Assignments with a pseudo-object l-value need special analysis.
11559 if (pty->getKind() == BuiltinType::PseudoObject &&
11560 BinaryOperator::isAssignmentOp(Opc))
11561 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11563 // Don't resolve overloads if the other type is overloadable.
11564 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11565 // We can't actually test that if we still have a placeholder,
11566 // though. Fortunately, none of the exceptions we see in that
11567 // code below are valid when the LHS is an overload set. Note
11568 // that an overload set can be dependently-typed, but it never
11569 // instantiates to having an overloadable type.
11570 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11571 if (resolvedRHS.isInvalid()) return ExprError();
11572 RHSExpr = resolvedRHS.get();
11574 if (RHSExpr->isTypeDependent() ||
11575 RHSExpr->getType()->isOverloadableType())
11576 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11579 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11580 if (LHS.isInvalid()) return ExprError();
11581 LHSExpr = LHS.get();
11584 // Handle pseudo-objects in the RHS.
11585 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11586 // An overload in the RHS can potentially be resolved by the type
11587 // being assigned to.
11588 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11589 if (getLangOpts().CPlusPlus &&
11590 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11591 LHSExpr->getType()->isOverloadableType()))
11592 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11594 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11597 // Don't resolve overloads if the other type is overloadable.
11598 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11599 LHSExpr->getType()->isOverloadableType())
11600 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11602 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11603 if (!resolvedRHS.isUsable()) return ExprError();
11604 RHSExpr = resolvedRHS.get();
11607 if (getLangOpts().CPlusPlus) {
11608 // If either expression is type-dependent, always build an
11610 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11611 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11613 // Otherwise, build an overloaded op if either expression has an
11614 // overloadable type.
11615 if (LHSExpr->getType()->isOverloadableType() ||
11616 RHSExpr->getType()->isOverloadableType())
11617 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11620 // Build a built-in binary operation.
11621 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11624 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11625 UnaryOperatorKind Opc,
11627 ExprResult Input = InputExpr;
11628 ExprValueKind VK = VK_RValue;
11629 ExprObjectKind OK = OK_Ordinary;
11630 QualType resultType;
11631 if (getLangOpts().OpenCL) {
11632 QualType Ty = InputExpr->getType();
11633 // The only legal unary operation for atomics is '&'.
11634 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11635 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11636 // only with a builtin functions and therefore should be disallowed here.
11637 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11638 || Ty->isBlockPointerType())) {
11639 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11640 << InputExpr->getType()
11641 << Input.get()->getSourceRange());
11649 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11651 Opc == UO_PreInc ||
11653 Opc == UO_PreInc ||
11657 resultType = CheckAddressOfOperand(Input, OpLoc);
11658 RecordModifiableNonNullParam(*this, InputExpr);
11661 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11662 if (Input.isInvalid()) return ExprError();
11663 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11668 Input = UsualUnaryConversions(Input.get());
11669 if (Input.isInvalid()) return ExprError();
11670 resultType = Input.get()->getType();
11671 if (resultType->isDependentType())
11673 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11675 else if (resultType->isVectorType() &&
11676 // The z vector extensions don't allow + or - with bool vectors.
11677 (!Context.getLangOpts().ZVector ||
11678 resultType->getAs<VectorType>()->getVectorKind() !=
11679 VectorType::AltiVecBool))
11681 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11683 resultType->isPointerType())
11686 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11687 << resultType << Input.get()->getSourceRange());
11689 case UO_Not: // bitwise complement
11690 Input = UsualUnaryConversions(Input.get());
11691 if (Input.isInvalid())
11692 return ExprError();
11693 resultType = Input.get()->getType();
11694 if (resultType->isDependentType())
11696 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11697 if (resultType->isComplexType() || resultType->isComplexIntegerType())
11698 // C99 does not support '~' for complex conjugation.
11699 Diag(OpLoc, diag::ext_integer_complement_complex)
11700 << resultType << Input.get()->getSourceRange();
11701 else if (resultType->hasIntegerRepresentation())
11703 else if (resultType->isExtVectorType()) {
11704 if (Context.getLangOpts().OpenCL) {
11705 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11706 // on vector float types.
11707 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11708 if (!T->isIntegerType())
11709 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11710 << resultType << Input.get()->getSourceRange());
11714 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11715 << resultType << Input.get()->getSourceRange());
11719 case UO_LNot: // logical negation
11720 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11721 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11722 if (Input.isInvalid()) return ExprError();
11723 resultType = Input.get()->getType();
11725 // Though we still have to promote half FP to float...
11726 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11727 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11728 resultType = Context.FloatTy;
11731 if (resultType->isDependentType())
11733 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11734 // C99 6.5.3.3p1: ok, fallthrough;
11735 if (Context.getLangOpts().CPlusPlus) {
11736 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11737 // operand contextually converted to bool.
11738 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11739 ScalarTypeToBooleanCastKind(resultType));
11740 } else if (Context.getLangOpts().OpenCL &&
11741 Context.getLangOpts().OpenCLVersion < 120) {
11742 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11743 // operate on scalar float types.
11744 if (!resultType->isIntegerType() && !resultType->isPointerType())
11745 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11746 << resultType << Input.get()->getSourceRange());
11748 } else if (resultType->isExtVectorType()) {
11749 if (Context.getLangOpts().OpenCL &&
11750 Context.getLangOpts().OpenCLVersion < 120) {
11751 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11752 // operate on vector float types.
11753 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11754 if (!T->isIntegerType())
11755 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11756 << resultType << Input.get()->getSourceRange());
11758 // Vector logical not returns the signed variant of the operand type.
11759 resultType = GetSignedVectorType(resultType);
11762 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11763 << resultType << Input.get()->getSourceRange());
11766 // LNot always has type int. C99 6.5.3.3p5.
11767 // In C++, it's bool. C++ 5.3.1p8
11768 resultType = Context.getLogicalOperationType();
11772 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11773 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11774 // complex l-values to ordinary l-values and all other values to r-values.
11775 if (Input.isInvalid()) return ExprError();
11776 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11777 if (Input.get()->getValueKind() != VK_RValue &&
11778 Input.get()->getObjectKind() == OK_Ordinary)
11779 VK = Input.get()->getValueKind();
11780 } else if (!getLangOpts().CPlusPlus) {
11781 // In C, a volatile scalar is read by __imag. In C++, it is not.
11782 Input = DefaultLvalueConversion(Input.get());
11787 resultType = Input.get()->getType();
11788 VK = Input.get()->getValueKind();
11789 OK = Input.get()->getObjectKind();
11792 if (resultType.isNull() || Input.isInvalid())
11793 return ExprError();
11795 // Check for array bounds violations in the operand of the UnaryOperator,
11796 // except for the '*' and '&' operators that have to be handled specially
11797 // by CheckArrayAccess (as there are special cases like &array[arraysize]
11798 // that are explicitly defined as valid by the standard).
11799 if (Opc != UO_AddrOf && Opc != UO_Deref)
11800 CheckArrayAccess(Input.get());
11802 return new (Context)
11803 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11806 /// \brief Determine whether the given expression is a qualified member
11807 /// access expression, of a form that could be turned into a pointer to member
11808 /// with the address-of operator.
11809 static bool isQualifiedMemberAccess(Expr *E) {
11810 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11811 if (!DRE->getQualifier())
11814 ValueDecl *VD = DRE->getDecl();
11815 if (!VD->isCXXClassMember())
11818 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11821 return Method->isInstance();
11826 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11827 if (!ULE->getQualifier())
11830 for (NamedDecl *D : ULE->decls()) {
11831 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11832 if (Method->isInstance())
11835 // Overload set does not contain methods.
11846 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11847 UnaryOperatorKind Opc, Expr *Input) {
11848 // First things first: handle placeholders so that the
11849 // overloaded-operator check considers the right type.
11850 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11851 // Increment and decrement of pseudo-object references.
11852 if (pty->getKind() == BuiltinType::PseudoObject &&
11853 UnaryOperator::isIncrementDecrementOp(Opc))
11854 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11856 // extension is always a builtin operator.
11857 if (Opc == UO_Extension)
11858 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11860 // & gets special logic for several kinds of placeholder.
11861 // The builtin code knows what to do.
11862 if (Opc == UO_AddrOf &&
11863 (pty->getKind() == BuiltinType::Overload ||
11864 pty->getKind() == BuiltinType::UnknownAny ||
11865 pty->getKind() == BuiltinType::BoundMember))
11866 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11868 // Anything else needs to be handled now.
11869 ExprResult Result = CheckPlaceholderExpr(Input);
11870 if (Result.isInvalid()) return ExprError();
11871 Input = Result.get();
11874 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11875 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11876 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11877 // Find all of the overloaded operators visible from this
11878 // point. We perform both an operator-name lookup from the local
11879 // scope and an argument-dependent lookup based on the types of
11881 UnresolvedSet<16> Functions;
11882 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11883 if (S && OverOp != OO_None)
11884 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11887 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11890 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11893 // Unary Operators. 'Tok' is the token for the operator.
11894 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11895 tok::TokenKind Op, Expr *Input) {
11896 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11899 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11900 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11901 LabelDecl *TheDecl) {
11902 TheDecl->markUsed(Context);
11903 // Create the AST node. The address of a label always has type 'void*'.
11904 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11905 Context.getPointerType(Context.VoidTy));
11908 /// Given the last statement in a statement-expression, check whether
11909 /// the result is a producing expression (like a call to an
11910 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11911 /// release out of the full-expression. Otherwise, return null.
11913 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11914 // Should always be wrapped with one of these.
11915 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11916 if (!cleanups) return nullptr;
11918 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11919 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11922 // Splice out the cast. This shouldn't modify any interesting
11923 // features of the statement.
11924 Expr *producer = cast->getSubExpr();
11925 assert(producer->getType() == cast->getType());
11926 assert(producer->getValueKind() == cast->getValueKind());
11927 cleanups->setSubExpr(producer);
11931 void Sema::ActOnStartStmtExpr() {
11932 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11935 void Sema::ActOnStmtExprError() {
11936 // Note that function is also called by TreeTransform when leaving a
11937 // StmtExpr scope without rebuilding anything.
11939 DiscardCleanupsInEvaluationContext();
11940 PopExpressionEvaluationContext();
11944 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11945 SourceLocation RPLoc) { // "({..})"
11946 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11947 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11949 if (hasAnyUnrecoverableErrorsInThisFunction())
11950 DiscardCleanupsInEvaluationContext();
11951 assert(!Cleanup.exprNeedsCleanups() &&
11952 "cleanups within StmtExpr not correctly bound!");
11953 PopExpressionEvaluationContext();
11955 // FIXME: there are a variety of strange constraints to enforce here, for
11956 // example, it is not possible to goto into a stmt expression apparently.
11957 // More semantic analysis is needed.
11959 // If there are sub-stmts in the compound stmt, take the type of the last one
11960 // as the type of the stmtexpr.
11961 QualType Ty = Context.VoidTy;
11962 bool StmtExprMayBindToTemp = false;
11963 if (!Compound->body_empty()) {
11964 Stmt *LastStmt = Compound->body_back();
11965 LabelStmt *LastLabelStmt = nullptr;
11966 // If LastStmt is a label, skip down through into the body.
11967 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11968 LastLabelStmt = Label;
11969 LastStmt = Label->getSubStmt();
11972 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11973 // Do function/array conversion on the last expression, but not
11974 // lvalue-to-rvalue. However, initialize an unqualified type.
11975 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11976 if (LastExpr.isInvalid())
11977 return ExprError();
11978 Ty = LastExpr.get()->getType().getUnqualifiedType();
11980 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11981 // In ARC, if the final expression ends in a consume, splice
11982 // the consume out and bind it later. In the alternate case
11983 // (when dealing with a retainable type), the result
11984 // initialization will create a produce. In both cases the
11985 // result will be +1, and we'll need to balance that out with
11987 if (Expr *rebuiltLastStmt
11988 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11989 LastExpr = rebuiltLastStmt;
11991 LastExpr = PerformCopyInitialization(
11992 InitializedEntity::InitializeResult(LPLoc,
11999 if (LastExpr.isInvalid())
12000 return ExprError();
12001 if (LastExpr.get() != nullptr) {
12002 if (!LastLabelStmt)
12003 Compound->setLastStmt(LastExpr.get());
12005 LastLabelStmt->setSubStmt(LastExpr.get());
12006 StmtExprMayBindToTemp = true;
12012 // FIXME: Check that expression type is complete/non-abstract; statement
12013 // expressions are not lvalues.
12014 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12015 if (StmtExprMayBindToTemp)
12016 return MaybeBindToTemporary(ResStmtExpr);
12017 return ResStmtExpr;
12020 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12021 TypeSourceInfo *TInfo,
12022 ArrayRef<OffsetOfComponent> Components,
12023 SourceLocation RParenLoc) {
12024 QualType ArgTy = TInfo->getType();
12025 bool Dependent = ArgTy->isDependentType();
12026 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12028 // We must have at least one component that refers to the type, and the first
12029 // one is known to be a field designator. Verify that the ArgTy represents
12030 // a struct/union/class.
12031 if (!Dependent && !ArgTy->isRecordType())
12032 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12033 << ArgTy << TypeRange);
12035 // Type must be complete per C99 7.17p3 because a declaring a variable
12036 // with an incomplete type would be ill-formed.
12038 && RequireCompleteType(BuiltinLoc, ArgTy,
12039 diag::err_offsetof_incomplete_type, TypeRange))
12040 return ExprError();
12042 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12043 // GCC extension, diagnose them.
12044 // FIXME: This diagnostic isn't actually visible because the location is in
12045 // a system header!
12046 if (Components.size() != 1)
12047 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12048 << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12050 bool DidWarnAboutNonPOD = false;
12051 QualType CurrentType = ArgTy;
12052 SmallVector<OffsetOfNode, 4> Comps;
12053 SmallVector<Expr*, 4> Exprs;
12054 for (const OffsetOfComponent &OC : Components) {
12055 if (OC.isBrackets) {
12056 // Offset of an array sub-field. TODO: Should we allow vector elements?
12057 if (!CurrentType->isDependentType()) {
12058 const ArrayType *AT = Context.getAsArrayType(CurrentType);
12060 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12062 CurrentType = AT->getElementType();
12064 CurrentType = Context.DependentTy;
12066 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12067 if (IdxRval.isInvalid())
12068 return ExprError();
12069 Expr *Idx = IdxRval.get();
12071 // The expression must be an integral expression.
12072 // FIXME: An integral constant expression?
12073 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12074 !Idx->getType()->isIntegerType())
12075 return ExprError(Diag(Idx->getLocStart(),
12076 diag::err_typecheck_subscript_not_integer)
12077 << Idx->getSourceRange());
12079 // Record this array index.
12080 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12081 Exprs.push_back(Idx);
12085 // Offset of a field.
12086 if (CurrentType->isDependentType()) {
12087 // We have the offset of a field, but we can't look into the dependent
12088 // type. Just record the identifier of the field.
12089 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12090 CurrentType = Context.DependentTy;
12094 // We need to have a complete type to look into.
12095 if (RequireCompleteType(OC.LocStart, CurrentType,
12096 diag::err_offsetof_incomplete_type))
12097 return ExprError();
12099 // Look for the designated field.
12100 const RecordType *RC = CurrentType->getAs<RecordType>();
12102 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12104 RecordDecl *RD = RC->getDecl();
12106 // C++ [lib.support.types]p5:
12107 // The macro offsetof accepts a restricted set of type arguments in this
12108 // International Standard. type shall be a POD structure or a POD union
12110 // C++11 [support.types]p4:
12111 // If type is not a standard-layout class (Clause 9), the results are
12113 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12114 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12116 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12117 : diag::ext_offsetof_non_pod_type;
12119 if (!IsSafe && !DidWarnAboutNonPOD &&
12120 DiagRuntimeBehavior(BuiltinLoc, nullptr,
12122 << SourceRange(Components[0].LocStart, OC.LocEnd)
12124 DidWarnAboutNonPOD = true;
12127 // Look for the field.
12128 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12129 LookupQualifiedName(R, RD);
12130 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12131 IndirectFieldDecl *IndirectMemberDecl = nullptr;
12133 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12134 MemberDecl = IndirectMemberDecl->getAnonField();
12138 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12139 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12143 // (If the specified member is a bit-field, the behavior is undefined.)
12145 // We diagnose this as an error.
12146 if (MemberDecl->isBitField()) {
12147 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12148 << MemberDecl->getDeclName()
12149 << SourceRange(BuiltinLoc, RParenLoc);
12150 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12151 return ExprError();
12154 RecordDecl *Parent = MemberDecl->getParent();
12155 if (IndirectMemberDecl)
12156 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12158 // If the member was found in a base class, introduce OffsetOfNodes for
12159 // the base class indirections.
12160 CXXBasePaths Paths;
12161 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12163 if (Paths.getDetectedVirtual()) {
12164 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12165 << MemberDecl->getDeclName()
12166 << SourceRange(BuiltinLoc, RParenLoc);
12167 return ExprError();
12170 CXXBasePath &Path = Paths.front();
12171 for (const CXXBasePathElement &B : Path)
12172 Comps.push_back(OffsetOfNode(B.Base));
12175 if (IndirectMemberDecl) {
12176 for (auto *FI : IndirectMemberDecl->chain()) {
12177 assert(isa<FieldDecl>(FI));
12178 Comps.push_back(OffsetOfNode(OC.LocStart,
12179 cast<FieldDecl>(FI), OC.LocEnd));
12182 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12184 CurrentType = MemberDecl->getType().getNonReferenceType();
12187 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12188 Comps, Exprs, RParenLoc);
12191 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12192 SourceLocation BuiltinLoc,
12193 SourceLocation TypeLoc,
12194 ParsedType ParsedArgTy,
12195 ArrayRef<OffsetOfComponent> Components,
12196 SourceLocation RParenLoc) {
12198 TypeSourceInfo *ArgTInfo;
12199 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12200 if (ArgTy.isNull())
12201 return ExprError();
12204 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12206 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12210 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12212 Expr *LHSExpr, Expr *RHSExpr,
12213 SourceLocation RPLoc) {
12214 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12216 ExprValueKind VK = VK_RValue;
12217 ExprObjectKind OK = OK_Ordinary;
12219 bool ValueDependent = false;
12220 bool CondIsTrue = false;
12221 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12222 resType = Context.DependentTy;
12223 ValueDependent = true;
12225 // The conditional expression is required to be a constant expression.
12226 llvm::APSInt condEval(32);
12228 = VerifyIntegerConstantExpression(CondExpr, &condEval,
12229 diag::err_typecheck_choose_expr_requires_constant, false);
12230 if (CondICE.isInvalid())
12231 return ExprError();
12232 CondExpr = CondICE.get();
12233 CondIsTrue = condEval.getZExtValue();
12235 // If the condition is > zero, then the AST type is the same as the LSHExpr.
12236 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12238 resType = ActiveExpr->getType();
12239 ValueDependent = ActiveExpr->isValueDependent();
12240 VK = ActiveExpr->getValueKind();
12241 OK = ActiveExpr->getObjectKind();
12244 return new (Context)
12245 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12246 CondIsTrue, resType->isDependentType(), ValueDependent);
12249 //===----------------------------------------------------------------------===//
12250 // Clang Extensions.
12251 //===----------------------------------------------------------------------===//
12253 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12254 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12255 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12257 if (LangOpts.CPlusPlus) {
12258 Decl *ManglingContextDecl;
12259 if (MangleNumberingContext *MCtx =
12260 getCurrentMangleNumberContext(Block->getDeclContext(),
12261 ManglingContextDecl)) {
12262 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12263 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12267 PushBlockScope(CurScope, Block);
12268 CurContext->addDecl(Block);
12270 PushDeclContext(CurScope, Block);
12272 CurContext = Block;
12274 getCurBlock()->HasImplicitReturnType = true;
12276 // Enter a new evaluation context to insulate the block from any
12277 // cleanups from the enclosing full-expression.
12278 PushExpressionEvaluationContext(
12279 ExpressionEvaluationContext::PotentiallyEvaluated);
12282 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12284 assert(ParamInfo.getIdentifier() == nullptr &&
12285 "block-id should have no identifier!");
12286 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12287 BlockScopeInfo *CurBlock = getCurBlock();
12289 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12290 QualType T = Sig->getType();
12292 // FIXME: We should allow unexpanded parameter packs here, but that would,
12293 // in turn, make the block expression contain unexpanded parameter packs.
12294 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12295 // Drop the parameters.
12296 FunctionProtoType::ExtProtoInfo EPI;
12297 EPI.HasTrailingReturn = false;
12298 EPI.TypeQuals |= DeclSpec::TQ_const;
12299 T = Context.getFunctionType(Context.DependentTy, None, EPI);
12300 Sig = Context.getTrivialTypeSourceInfo(T);
12303 // GetTypeForDeclarator always produces a function type for a block
12304 // literal signature. Furthermore, it is always a FunctionProtoType
12305 // unless the function was written with a typedef.
12306 assert(T->isFunctionType() &&
12307 "GetTypeForDeclarator made a non-function block signature");
12309 // Look for an explicit signature in that function type.
12310 FunctionProtoTypeLoc ExplicitSignature;
12312 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12313 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12315 // Check whether that explicit signature was synthesized by
12316 // GetTypeForDeclarator. If so, don't save that as part of the
12317 // written signature.
12318 if (ExplicitSignature.getLocalRangeBegin() ==
12319 ExplicitSignature.getLocalRangeEnd()) {
12320 // This would be much cheaper if we stored TypeLocs instead of
12321 // TypeSourceInfos.
12322 TypeLoc Result = ExplicitSignature.getReturnLoc();
12323 unsigned Size = Result.getFullDataSize();
12324 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12325 Sig->getTypeLoc().initializeFullCopy(Result, Size);
12327 ExplicitSignature = FunctionProtoTypeLoc();
12331 CurBlock->TheDecl->setSignatureAsWritten(Sig);
12332 CurBlock->FunctionType = T;
12334 const FunctionType *Fn = T->getAs<FunctionType>();
12335 QualType RetTy = Fn->getReturnType();
12337 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12339 CurBlock->TheDecl->setIsVariadic(isVariadic);
12341 // Context.DependentTy is used as a placeholder for a missing block
12342 // return type. TODO: what should we do with declarators like:
12344 // If the answer is "apply template argument deduction"....
12345 if (RetTy != Context.DependentTy) {
12346 CurBlock->ReturnType = RetTy;
12347 CurBlock->TheDecl->setBlockMissingReturnType(false);
12348 CurBlock->HasImplicitReturnType = false;
12351 // Push block parameters from the declarator if we had them.
12352 SmallVector<ParmVarDecl*, 8> Params;
12353 if (ExplicitSignature) {
12354 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12355 ParmVarDecl *Param = ExplicitSignature.getParam(I);
12356 if (Param->getIdentifier() == nullptr &&
12357 !Param->isImplicit() &&
12358 !Param->isInvalidDecl() &&
12359 !getLangOpts().CPlusPlus)
12360 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12361 Params.push_back(Param);
12364 // Fake up parameter variables if we have a typedef, like
12365 // ^ fntype { ... }
12366 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12367 for (const auto &I : Fn->param_types()) {
12368 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12369 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12370 Params.push_back(Param);
12374 // Set the parameters on the block decl.
12375 if (!Params.empty()) {
12376 CurBlock->TheDecl->setParams(Params);
12377 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12378 /*CheckParameterNames=*/false);
12381 // Finally we can process decl attributes.
12382 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12384 // Put the parameter variables in scope.
12385 for (auto AI : CurBlock->TheDecl->parameters()) {
12386 AI->setOwningFunction(CurBlock->TheDecl);
12388 // If this has an identifier, add it to the scope stack.
12389 if (AI->getIdentifier()) {
12390 CheckShadow(CurBlock->TheScope, AI);
12392 PushOnScopeChains(AI, CurBlock->TheScope);
12397 /// ActOnBlockError - If there is an error parsing a block, this callback
12398 /// is invoked to pop the information about the block from the action impl.
12399 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12400 // Leave the expression-evaluation context.
12401 DiscardCleanupsInEvaluationContext();
12402 PopExpressionEvaluationContext();
12404 // Pop off CurBlock, handle nested blocks.
12406 PopFunctionScopeInfo();
12409 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12410 /// literal was successfully completed. ^(int x){...}
12411 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12412 Stmt *Body, Scope *CurScope) {
12413 // If blocks are disabled, emit an error.
12414 if (!LangOpts.Blocks)
12415 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12417 // Leave the expression-evaluation context.
12418 if (hasAnyUnrecoverableErrorsInThisFunction())
12419 DiscardCleanupsInEvaluationContext();
12420 assert(!Cleanup.exprNeedsCleanups() &&
12421 "cleanups within block not correctly bound!");
12422 PopExpressionEvaluationContext();
12424 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12426 if (BSI->HasImplicitReturnType)
12427 deduceClosureReturnType(*BSI);
12431 QualType RetTy = Context.VoidTy;
12432 if (!BSI->ReturnType.isNull())
12433 RetTy = BSI->ReturnType;
12435 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12438 // Set the captured variables on the block.
12439 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12440 SmallVector<BlockDecl::Capture, 4> Captures;
12441 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12442 if (Cap.isThisCapture())
12444 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12445 Cap.isNested(), Cap.getInitExpr());
12446 Captures.push_back(NewCap);
12448 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12450 // If the user wrote a function type in some form, try to use that.
12451 if (!BSI->FunctionType.isNull()) {
12452 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12454 FunctionType::ExtInfo Ext = FTy->getExtInfo();
12455 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12457 // Turn protoless block types into nullary block types.
12458 if (isa<FunctionNoProtoType>(FTy)) {
12459 FunctionProtoType::ExtProtoInfo EPI;
12461 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12463 // Otherwise, if we don't need to change anything about the function type,
12464 // preserve its sugar structure.
12465 } else if (FTy->getReturnType() == RetTy &&
12466 (!NoReturn || FTy->getNoReturnAttr())) {
12467 BlockTy = BSI->FunctionType;
12469 // Otherwise, make the minimal modifications to the function type.
12471 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12472 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12473 EPI.TypeQuals = 0; // FIXME: silently?
12475 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12478 // If we don't have a function type, just build one from nothing.
12480 FunctionProtoType::ExtProtoInfo EPI;
12481 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12482 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12485 DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12486 BlockTy = Context.getBlockPointerType(BlockTy);
12488 // If needed, diagnose invalid gotos and switches in the block.
12489 if (getCurFunction()->NeedsScopeChecking() &&
12490 !PP.isCodeCompletionEnabled())
12491 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12493 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12495 // Try to apply the named return value optimization. We have to check again
12496 // if we can do this, though, because blocks keep return statements around
12497 // to deduce an implicit return type.
12498 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12499 !BSI->TheDecl->isDependentContext())
12500 computeNRVO(Body, BSI);
12502 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12503 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12504 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12506 // If the block isn't obviously global, i.e. it captures anything at
12507 // all, then we need to do a few things in the surrounding context:
12508 if (Result->getBlockDecl()->hasCaptures()) {
12509 // First, this expression has a new cleanup object.
12510 ExprCleanupObjects.push_back(Result->getBlockDecl());
12511 Cleanup.setExprNeedsCleanups(true);
12513 // It also gets a branch-protected scope if any of the captured
12514 // variables needs destruction.
12515 for (const auto &CI : Result->getBlockDecl()->captures()) {
12516 const VarDecl *var = CI.getVariable();
12517 if (var->getType().isDestructedType() != QualType::DK_none) {
12518 getCurFunction()->setHasBranchProtectedScope();
12527 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12528 SourceLocation RPLoc) {
12529 TypeSourceInfo *TInfo;
12530 GetTypeFromParser(Ty, &TInfo);
12531 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12534 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12535 Expr *E, TypeSourceInfo *TInfo,
12536 SourceLocation RPLoc) {
12537 Expr *OrigExpr = E;
12540 // CUDA device code does not support varargs.
12541 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12542 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12543 CUDAFunctionTarget T = IdentifyCUDATarget(F);
12544 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12545 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12549 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12550 // as Microsoft ABI on an actual Microsoft platform, where
12551 // __builtin_ms_va_list and __builtin_va_list are the same.)
12552 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12553 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12554 QualType MSVaListType = Context.getBuiltinMSVaListType();
12555 if (Context.hasSameType(MSVaListType, E->getType())) {
12556 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12557 return ExprError();
12562 // Get the va_list type
12563 QualType VaListType = Context.getBuiltinVaListType();
12565 if (VaListType->isArrayType()) {
12566 // Deal with implicit array decay; for example, on x86-64,
12567 // va_list is an array, but it's supposed to decay to
12568 // a pointer for va_arg.
12569 VaListType = Context.getArrayDecayedType(VaListType);
12570 // Make sure the input expression also decays appropriately.
12571 ExprResult Result = UsualUnaryConversions(E);
12572 if (Result.isInvalid())
12573 return ExprError();
12575 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12576 // If va_list is a record type and we are compiling in C++ mode,
12577 // check the argument using reference binding.
12578 InitializedEntity Entity = InitializedEntity::InitializeParameter(
12579 Context, Context.getLValueReferenceType(VaListType), false);
12580 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12581 if (Init.isInvalid())
12582 return ExprError();
12583 E = Init.getAs<Expr>();
12585 // Otherwise, the va_list argument must be an l-value because
12586 // it is modified by va_arg.
12587 if (!E->isTypeDependent() &&
12588 CheckForModifiableLvalue(E, BuiltinLoc, *this))
12589 return ExprError();
12593 if (!IsMS && !E->isTypeDependent() &&
12594 !Context.hasSameType(VaListType, E->getType()))
12595 return ExprError(Diag(E->getLocStart(),
12596 diag::err_first_argument_to_va_arg_not_of_type_va_list)
12597 << OrigExpr->getType() << E->getSourceRange());
12599 if (!TInfo->getType()->isDependentType()) {
12600 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12601 diag::err_second_parameter_to_va_arg_incomplete,
12602 TInfo->getTypeLoc()))
12603 return ExprError();
12605 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12607 diag::err_second_parameter_to_va_arg_abstract,
12608 TInfo->getTypeLoc()))
12609 return ExprError();
12611 if (!TInfo->getType().isPODType(Context)) {
12612 Diag(TInfo->getTypeLoc().getBeginLoc(),
12613 TInfo->getType()->isObjCLifetimeType()
12614 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12615 : diag::warn_second_parameter_to_va_arg_not_pod)
12616 << TInfo->getType()
12617 << TInfo->getTypeLoc().getSourceRange();
12620 // Check for va_arg where arguments of the given type will be promoted
12621 // (i.e. this va_arg is guaranteed to have undefined behavior).
12622 QualType PromoteType;
12623 if (TInfo->getType()->isPromotableIntegerType()) {
12624 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12625 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12626 PromoteType = QualType();
12628 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12629 PromoteType = Context.DoubleTy;
12630 if (!PromoteType.isNull())
12631 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12632 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12633 << TInfo->getType()
12635 << TInfo->getTypeLoc().getSourceRange());
12638 QualType T = TInfo->getType().getNonLValueExprType(Context);
12639 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12642 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12643 // The type of __null will be int or long, depending on the size of
12644 // pointers on the target.
12646 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12647 if (pw == Context.getTargetInfo().getIntWidth())
12648 Ty = Context.IntTy;
12649 else if (pw == Context.getTargetInfo().getLongWidth())
12650 Ty = Context.LongTy;
12651 else if (pw == Context.getTargetInfo().getLongLongWidth())
12652 Ty = Context.LongLongTy;
12654 llvm_unreachable("I don't know size of pointer!");
12657 return new (Context) GNUNullExpr(Ty, TokenLoc);
12660 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12662 if (!getLangOpts().ObjC1)
12665 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12669 if (!PT->isObjCIdType()) {
12670 // Check if the destination is the 'NSString' interface.
12671 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12672 if (!ID || !ID->getIdentifier()->isStr("NSString"))
12676 // Ignore any parens, implicit casts (should only be
12677 // array-to-pointer decays), and not-so-opaque values. The last is
12678 // important for making this trigger for property assignments.
12679 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12680 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12681 if (OV->getSourceExpr())
12682 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12684 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12685 if (!SL || !SL->isAscii())
12688 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12689 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12690 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12695 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12696 const Expr *SrcExpr) {
12697 if (!DstType->isFunctionPointerType() ||
12698 !SrcExpr->getType()->isFunctionType())
12701 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12705 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12709 return !S.checkAddressOfFunctionIsAvailable(FD,
12711 SrcExpr->getLocStart());
12714 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12715 SourceLocation Loc,
12716 QualType DstType, QualType SrcType,
12717 Expr *SrcExpr, AssignmentAction Action,
12718 bool *Complained) {
12720 *Complained = false;
12722 // Decode the result (notice that AST's are still created for extensions).
12723 bool CheckInferredResultType = false;
12724 bool isInvalid = false;
12725 unsigned DiagKind = 0;
12727 ConversionFixItGenerator ConvHints;
12728 bool MayHaveConvFixit = false;
12729 bool MayHaveFunctionDiff = false;
12730 const ObjCInterfaceDecl *IFace = nullptr;
12731 const ObjCProtocolDecl *PDecl = nullptr;
12735 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12739 DiagKind = diag::ext_typecheck_convert_pointer_int;
12740 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12741 MayHaveConvFixit = true;
12744 DiagKind = diag::ext_typecheck_convert_int_pointer;
12745 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12746 MayHaveConvFixit = true;
12748 case IncompatiblePointer:
12749 if (Action == AA_Passing_CFAudited)
12750 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12751 else if (SrcType->isFunctionPointerType() &&
12752 DstType->isFunctionPointerType())
12753 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12755 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12757 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12758 SrcType->isObjCObjectPointerType();
12759 if (Hint.isNull() && !CheckInferredResultType) {
12760 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12762 else if (CheckInferredResultType) {
12763 SrcType = SrcType.getUnqualifiedType();
12764 DstType = DstType.getUnqualifiedType();
12766 MayHaveConvFixit = true;
12768 case IncompatiblePointerSign:
12769 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12771 case FunctionVoidPointer:
12772 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12774 case IncompatiblePointerDiscardsQualifiers: {
12775 // Perform array-to-pointer decay if necessary.
12776 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12778 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12779 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12780 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12781 DiagKind = diag::err_typecheck_incompatible_address_space;
12785 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12786 DiagKind = diag::err_typecheck_incompatible_ownership;
12790 llvm_unreachable("unknown error case for discarding qualifiers!");
12793 case CompatiblePointerDiscardsQualifiers:
12794 // If the qualifiers lost were because we were applying the
12795 // (deprecated) C++ conversion from a string literal to a char*
12796 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
12797 // Ideally, this check would be performed in
12798 // checkPointerTypesForAssignment. However, that would require a
12799 // bit of refactoring (so that the second argument is an
12800 // expression, rather than a type), which should be done as part
12801 // of a larger effort to fix checkPointerTypesForAssignment for
12803 if (getLangOpts().CPlusPlus &&
12804 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12806 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12808 case IncompatibleNestedPointerQualifiers:
12809 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12811 case IntToBlockPointer:
12812 DiagKind = diag::err_int_to_block_pointer;
12814 case IncompatibleBlockPointer:
12815 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12817 case IncompatibleObjCQualifiedId: {
12818 if (SrcType->isObjCQualifiedIdType()) {
12819 const ObjCObjectPointerType *srcOPT =
12820 SrcType->getAs<ObjCObjectPointerType>();
12821 for (auto *srcProto : srcOPT->quals()) {
12825 if (const ObjCInterfaceType *IFaceT =
12826 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12827 IFace = IFaceT->getDecl();
12829 else if (DstType->isObjCQualifiedIdType()) {
12830 const ObjCObjectPointerType *dstOPT =
12831 DstType->getAs<ObjCObjectPointerType>();
12832 for (auto *dstProto : dstOPT->quals()) {
12836 if (const ObjCInterfaceType *IFaceT =
12837 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12838 IFace = IFaceT->getDecl();
12840 DiagKind = diag::warn_incompatible_qualified_id;
12843 case IncompatibleVectors:
12844 DiagKind = diag::warn_incompatible_vectors;
12846 case IncompatibleObjCWeakRef:
12847 DiagKind = diag::err_arc_weak_unavailable_assign;
12850 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12852 *Complained = true;
12856 DiagKind = diag::err_typecheck_convert_incompatible;
12857 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12858 MayHaveConvFixit = true;
12860 MayHaveFunctionDiff = true;
12864 QualType FirstType, SecondType;
12867 case AA_Initializing:
12868 // The destination type comes first.
12869 FirstType = DstType;
12870 SecondType = SrcType;
12875 case AA_Passing_CFAudited:
12876 case AA_Converting:
12879 // The source type comes first.
12880 FirstType = SrcType;
12881 SecondType = DstType;
12885 PartialDiagnostic FDiag = PDiag(DiagKind);
12886 if (Action == AA_Passing_CFAudited)
12887 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12889 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12891 // If we can fix the conversion, suggest the FixIts.
12892 assert(ConvHints.isNull() || Hint.isNull());
12893 if (!ConvHints.isNull()) {
12894 for (FixItHint &H : ConvHints.Hints)
12899 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12901 if (MayHaveFunctionDiff)
12902 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12905 if (DiagKind == diag::warn_incompatible_qualified_id &&
12906 PDecl && IFace && !IFace->hasDefinition())
12907 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12908 << IFace->getName() << PDecl->getName();
12910 if (SecondType == Context.OverloadTy)
12911 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12912 FirstType, /*TakingAddress=*/true);
12914 if (CheckInferredResultType)
12915 EmitRelatedResultTypeNote(SrcExpr);
12917 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12918 EmitRelatedResultTypeNoteForReturn(DstType);
12921 *Complained = true;
12925 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12926 llvm::APSInt *Result) {
12927 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12929 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12930 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12934 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12937 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12938 llvm::APSInt *Result,
12941 class IDDiagnoser : public VerifyICEDiagnoser {
12945 IDDiagnoser(unsigned DiagID)
12946 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12948 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12949 S.Diag(Loc, DiagID) << SR;
12951 } Diagnoser(DiagID);
12953 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12956 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12958 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12962 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12963 VerifyICEDiagnoser &Diagnoser,
12965 SourceLocation DiagLoc = E->getLocStart();
12967 if (getLangOpts().CPlusPlus11) {
12968 // C++11 [expr.const]p5:
12969 // If an expression of literal class type is used in a context where an
12970 // integral constant expression is required, then that class type shall
12971 // have a single non-explicit conversion function to an integral or
12972 // unscoped enumeration type
12973 ExprResult Converted;
12974 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12976 CXX11ConvertDiagnoser(bool Silent)
12977 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12980 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12981 QualType T) override {
12982 return S.Diag(Loc, diag::err_ice_not_integral) << T;
12985 SemaDiagnosticBuilder diagnoseIncomplete(
12986 Sema &S, SourceLocation Loc, QualType T) override {
12987 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12990 SemaDiagnosticBuilder diagnoseExplicitConv(
12991 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12992 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12995 SemaDiagnosticBuilder noteExplicitConv(
12996 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12997 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12998 << ConvTy->isEnumeralType() << ConvTy;
13001 SemaDiagnosticBuilder diagnoseAmbiguous(
13002 Sema &S, SourceLocation Loc, QualType T) override {
13003 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13006 SemaDiagnosticBuilder noteAmbiguous(
13007 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13008 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13009 << ConvTy->isEnumeralType() << ConvTy;
13012 SemaDiagnosticBuilder diagnoseConversion(
13013 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13014 llvm_unreachable("conversion functions are permitted");
13016 } ConvertDiagnoser(Diagnoser.Suppress);
13018 Converted = PerformContextualImplicitConversion(DiagLoc, E,
13020 if (Converted.isInvalid())
13022 E = Converted.get();
13023 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13024 return ExprError();
13025 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13026 // An ICE must be of integral or unscoped enumeration type.
13027 if (!Diagnoser.Suppress)
13028 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13029 return ExprError();
13032 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13033 // in the non-ICE case.
13034 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13036 *Result = E->EvaluateKnownConstInt(Context);
13040 Expr::EvalResult EvalResult;
13041 SmallVector<PartialDiagnosticAt, 8> Notes;
13042 EvalResult.Diag = &Notes;
13044 // Try to evaluate the expression, and produce diagnostics explaining why it's
13045 // not a constant expression as a side-effect.
13046 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13047 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13049 // In C++11, we can rely on diagnostics being produced for any expression
13050 // which is not a constant expression. If no diagnostics were produced, then
13051 // this is a constant expression.
13052 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13054 *Result = EvalResult.Val.getInt();
13058 // If our only note is the usual "invalid subexpression" note, just point
13059 // the caret at its location rather than producing an essentially
13061 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13062 diag::note_invalid_subexpr_in_const_expr) {
13063 DiagLoc = Notes[0].first;
13067 if (!Folded || !AllowFold) {
13068 if (!Diagnoser.Suppress) {
13069 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13070 for (const PartialDiagnosticAt &Note : Notes)
13071 Diag(Note.first, Note.second);
13074 return ExprError();
13077 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13078 for (const PartialDiagnosticAt &Note : Notes)
13079 Diag(Note.first, Note.second);
13082 *Result = EvalResult.Val.getInt();
13087 // Handle the case where we conclude a expression which we speculatively
13088 // considered to be unevaluated is actually evaluated.
13089 class TransformToPE : public TreeTransform<TransformToPE> {
13090 typedef TreeTransform<TransformToPE> BaseTransform;
13093 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13095 // Make sure we redo semantic analysis
13096 bool AlwaysRebuild() { return true; }
13098 // Make sure we handle LabelStmts correctly.
13099 // FIXME: This does the right thing, but maybe we need a more general
13100 // fix to TreeTransform?
13101 StmtResult TransformLabelStmt(LabelStmt *S) {
13102 S->getDecl()->setStmt(nullptr);
13103 return BaseTransform::TransformLabelStmt(S);
13106 // We need to special-case DeclRefExprs referring to FieldDecls which
13107 // are not part of a member pointer formation; normal TreeTransforming
13108 // doesn't catch this case because of the way we represent them in the AST.
13109 // FIXME: This is a bit ugly; is it really the best way to handle this
13112 // Error on DeclRefExprs referring to FieldDecls.
13113 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13114 if (isa<FieldDecl>(E->getDecl()) &&
13115 !SemaRef.isUnevaluatedContext())
13116 return SemaRef.Diag(E->getLocation(),
13117 diag::err_invalid_non_static_member_use)
13118 << E->getDecl() << E->getSourceRange();
13120 return BaseTransform::TransformDeclRefExpr(E);
13123 // Exception: filter out member pointer formation
13124 ExprResult TransformUnaryOperator(UnaryOperator *E) {
13125 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13128 return BaseTransform::TransformUnaryOperator(E);
13131 ExprResult TransformLambdaExpr(LambdaExpr *E) {
13132 // Lambdas never need to be transformed.
13138 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13139 assert(isUnevaluatedContext() &&
13140 "Should only transform unevaluated expressions");
13141 ExprEvalContexts.back().Context =
13142 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13143 if (isUnevaluatedContext())
13145 return TransformToPE(*this).TransformExpr(E);
13149 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13150 Decl *LambdaContextDecl,
13152 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13153 LambdaContextDecl, IsDecltype);
13155 if (!MaybeODRUseExprs.empty())
13156 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13160 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13161 ReuseLambdaContextDecl_t,
13163 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13164 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13167 void Sema::PopExpressionEvaluationContext() {
13168 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13169 unsigned NumTypos = Rec.NumTypos;
13171 if (!Rec.Lambdas.empty()) {
13172 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13174 if (Rec.isUnevaluated()) {
13175 // C++11 [expr.prim.lambda]p2:
13176 // A lambda-expression shall not appear in an unevaluated operand
13178 D = diag::err_lambda_unevaluated_operand;
13180 // C++1y [expr.const]p2:
13181 // A conditional-expression e is a core constant expression unless the
13182 // evaluation of e, following the rules of the abstract machine, would
13183 // evaluate [...] a lambda-expression.
13184 D = diag::err_lambda_in_constant_expression;
13187 // C++1z allows lambda expressions as core constant expressions.
13188 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13189 // 1607) from appearing within template-arguments and array-bounds that
13190 // are part of function-signatures. Be mindful that P0315 (Lambdas in
13191 // unevaluated contexts) might lift some of these restrictions in a
13193 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13194 for (const auto *L : Rec.Lambdas)
13195 Diag(L->getLocStart(), D);
13197 // Mark the capture expressions odr-used. This was deferred
13198 // during lambda expression creation.
13199 for (auto *Lambda : Rec.Lambdas) {
13200 for (auto *C : Lambda->capture_inits())
13201 MarkDeclarationsReferencedInExpr(C);
13206 // When are coming out of an unevaluated context, clear out any
13207 // temporaries that we may have created as part of the evaluation of
13208 // the expression in that context: they aren't relevant because they
13209 // will never be constructed.
13210 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13211 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13212 ExprCleanupObjects.end());
13213 Cleanup = Rec.ParentCleanup;
13214 CleanupVarDeclMarking();
13215 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13216 // Otherwise, merge the contexts together.
13218 Cleanup.mergeFrom(Rec.ParentCleanup);
13219 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13220 Rec.SavedMaybeODRUseExprs.end());
13223 // Pop the current expression evaluation context off the stack.
13224 ExprEvalContexts.pop_back();
13226 if (!ExprEvalContexts.empty())
13227 ExprEvalContexts.back().NumTypos += NumTypos;
13229 assert(NumTypos == 0 && "There are outstanding typos after popping the "
13230 "last ExpressionEvaluationContextRecord");
13233 void Sema::DiscardCleanupsInEvaluationContext() {
13234 ExprCleanupObjects.erase(
13235 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13236 ExprCleanupObjects.end());
13238 MaybeODRUseExprs.clear();
13241 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13242 if (!E->getType()->isVariablyModifiedType())
13244 return TransformToPotentiallyEvaluated(E);
13247 /// Are we within a context in which some evaluation could be performed (be it
13248 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13249 /// captured by C++'s idea of an "unevaluated context".
13250 static bool isEvaluatableContext(Sema &SemaRef) {
13251 switch (SemaRef.ExprEvalContexts.back().Context) {
13252 case Sema::ExpressionEvaluationContext::Unevaluated:
13253 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13254 case Sema::ExpressionEvaluationContext::DiscardedStatement:
13255 // Expressions in this context are never evaluated.
13258 case Sema::ExpressionEvaluationContext::UnevaluatedList:
13259 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13260 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13261 // Expressions in this context could be evaluated.
13264 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13265 // Referenced declarations will only be used if the construct in the
13266 // containing expression is used, at which point we'll be given another
13267 // turn to mark them.
13270 llvm_unreachable("Invalid context");
13273 /// Are we within a context in which references to resolved functions or to
13274 /// variables result in odr-use?
13275 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13276 // An expression in a template is not really an expression until it's been
13277 // instantiated, so it doesn't trigger odr-use.
13278 if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13281 switch (SemaRef.ExprEvalContexts.back().Context) {
13282 case Sema::ExpressionEvaluationContext::Unevaluated:
13283 case Sema::ExpressionEvaluationContext::UnevaluatedList:
13284 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13285 case Sema::ExpressionEvaluationContext::DiscardedStatement:
13288 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13289 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13292 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13295 llvm_unreachable("Invalid context");
13298 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13299 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13300 return Func->isConstexpr() &&
13301 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13304 /// \brief Mark a function referenced, and check whether it is odr-used
13305 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13306 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13307 bool MightBeOdrUse) {
13308 assert(Func && "No function?");
13310 Func->setReferenced();
13312 // C++11 [basic.def.odr]p3:
13313 // A function whose name appears as a potentially-evaluated expression is
13314 // odr-used if it is the unique lookup result or the selected member of a
13315 // set of overloaded functions [...].
13317 // We (incorrectly) mark overload resolution as an unevaluated context, so we
13318 // can just check that here.
13319 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13321 // Determine whether we require a function definition to exist, per
13322 // C++11 [temp.inst]p3:
13323 // Unless a function template specialization has been explicitly
13324 // instantiated or explicitly specialized, the function template
13325 // specialization is implicitly instantiated when the specialization is
13326 // referenced in a context that requires a function definition to exist.
13328 // That is either when this is an odr-use, or when a usage of a constexpr
13329 // function occurs within an evaluatable context.
13330 bool NeedDefinition =
13331 OdrUse || (isEvaluatableContext(*this) &&
13332 isImplicitlyDefinableConstexprFunction(Func));
13334 // C++14 [temp.expl.spec]p6:
13335 // If a template [...] is explicitly specialized then that specialization
13336 // shall be declared before the first use of that specialization that would
13337 // cause an implicit instantiation to take place, in every translation unit
13338 // in which such a use occurs
13339 if (NeedDefinition &&
13340 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13341 Func->getMemberSpecializationInfo()))
13342 checkSpecializationVisibility(Loc, Func);
13344 // C++14 [except.spec]p17:
13345 // An exception-specification is considered to be needed when:
13346 // - the function is odr-used or, if it appears in an unevaluated operand,
13347 // would be odr-used if the expression were potentially-evaluated;
13349 // Note, we do this even if MightBeOdrUse is false. That indicates that the
13350 // function is a pure virtual function we're calling, and in that case the
13351 // function was selected by overload resolution and we need to resolve its
13352 // exception specification for a different reason.
13353 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13354 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13355 ResolveExceptionSpec(Loc, FPT);
13357 // If we don't need to mark the function as used, and we don't need to
13358 // try to provide a definition, there's nothing more to do.
13359 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13360 (!NeedDefinition || Func->getBody()))
13363 // Note that this declaration has been used.
13364 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13365 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13366 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13367 if (Constructor->isDefaultConstructor()) {
13368 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13370 DefineImplicitDefaultConstructor(Loc, Constructor);
13371 } else if (Constructor->isCopyConstructor()) {
13372 DefineImplicitCopyConstructor(Loc, Constructor);
13373 } else if (Constructor->isMoveConstructor()) {
13374 DefineImplicitMoveConstructor(Loc, Constructor);
13376 } else if (Constructor->getInheritedConstructor()) {
13377 DefineInheritingConstructor(Loc, Constructor);
13379 } else if (CXXDestructorDecl *Destructor =
13380 dyn_cast<CXXDestructorDecl>(Func)) {
13381 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13382 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13383 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13385 DefineImplicitDestructor(Loc, Destructor);
13387 if (Destructor->isVirtual() && getLangOpts().AppleKext)
13388 MarkVTableUsed(Loc, Destructor->getParent());
13389 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13390 if (MethodDecl->isOverloadedOperator() &&
13391 MethodDecl->getOverloadedOperator() == OO_Equal) {
13392 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13393 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13394 if (MethodDecl->isCopyAssignmentOperator())
13395 DefineImplicitCopyAssignment(Loc, MethodDecl);
13396 else if (MethodDecl->isMoveAssignmentOperator())
13397 DefineImplicitMoveAssignment(Loc, MethodDecl);
13399 } else if (isa<CXXConversionDecl>(MethodDecl) &&
13400 MethodDecl->getParent()->isLambda()) {
13401 CXXConversionDecl *Conversion =
13402 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13403 if (Conversion->isLambdaToBlockPointerConversion())
13404 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13406 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13407 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13408 MarkVTableUsed(Loc, MethodDecl->getParent());
13411 // Recursive functions should be marked when used from another function.
13412 // FIXME: Is this really right?
13413 if (CurContext == Func) return;
13415 // Implicit instantiation of function templates and member functions of
13416 // class templates.
13417 if (Func->isImplicitlyInstantiable()) {
13418 bool AlreadyInstantiated = false;
13419 SourceLocation PointOfInstantiation = Loc;
13420 if (FunctionTemplateSpecializationInfo *SpecInfo
13421 = Func->getTemplateSpecializationInfo()) {
13422 if (SpecInfo->getPointOfInstantiation().isInvalid())
13423 SpecInfo->setPointOfInstantiation(Loc);
13424 else if (SpecInfo->getTemplateSpecializationKind()
13425 == TSK_ImplicitInstantiation) {
13426 AlreadyInstantiated = true;
13427 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13429 } else if (MemberSpecializationInfo *MSInfo
13430 = Func->getMemberSpecializationInfo()) {
13431 if (MSInfo->getPointOfInstantiation().isInvalid())
13432 MSInfo->setPointOfInstantiation(Loc);
13433 else if (MSInfo->getTemplateSpecializationKind()
13434 == TSK_ImplicitInstantiation) {
13435 AlreadyInstantiated = true;
13436 PointOfInstantiation = MSInfo->getPointOfInstantiation();
13440 if (!AlreadyInstantiated || Func->isConstexpr()) {
13441 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13442 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13443 CodeSynthesisContexts.size())
13444 PendingLocalImplicitInstantiations.push_back(
13445 std::make_pair(Func, PointOfInstantiation));
13446 else if (Func->isConstexpr())
13447 // Do not defer instantiations of constexpr functions, to avoid the
13448 // expression evaluator needing to call back into Sema if it sees a
13449 // call to such a function.
13450 InstantiateFunctionDefinition(PointOfInstantiation, Func);
13452 PendingInstantiations.push_back(std::make_pair(Func,
13453 PointOfInstantiation));
13454 // Notify the consumer that a function was implicitly instantiated.
13455 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13459 // Walk redefinitions, as some of them may be instantiable.
13460 for (auto i : Func->redecls()) {
13461 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13462 MarkFunctionReferenced(Loc, i, OdrUse);
13466 if (!OdrUse) return;
13468 // Keep track of used but undefined functions.
13469 if (!Func->isDefined()) {
13470 if (mightHaveNonExternalLinkage(Func))
13471 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13472 else if (Func->getMostRecentDecl()->isInlined() &&
13473 !LangOpts.GNUInline &&
13474 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13475 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13478 Func->markUsed(Context);
13482 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13483 ValueDecl *var, DeclContext *DC) {
13484 DeclContext *VarDC = var->getDeclContext();
13486 // If the parameter still belongs to the translation unit, then
13487 // we're actually just using one parameter in the declaration of
13489 if (isa<ParmVarDecl>(var) &&
13490 isa<TranslationUnitDecl>(VarDC))
13493 // For C code, don't diagnose about capture if we're not actually in code
13494 // right now; it's impossible to write a non-constant expression outside of
13495 // function context, so we'll get other (more useful) diagnostics later.
13497 // For C++, things get a bit more nasty... it would be nice to suppress this
13498 // diagnostic for certain cases like using a local variable in an array bound
13499 // for a member of a local class, but the correct predicate is not obvious.
13500 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13503 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13504 unsigned ContextKind = 3; // unknown
13505 if (isa<CXXMethodDecl>(VarDC) &&
13506 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13508 } else if (isa<FunctionDecl>(VarDC)) {
13510 } else if (isa<BlockDecl>(VarDC)) {
13514 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13515 << var << ValueKind << ContextKind << VarDC;
13516 S.Diag(var->getLocation(), diag::note_entity_declared_at)
13519 // FIXME: Add additional diagnostic info about class etc. which prevents
13524 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13525 bool &SubCapturesAreNested,
13526 QualType &CaptureType,
13527 QualType &DeclRefType) {
13528 // Check whether we've already captured it.
13529 if (CSI->CaptureMap.count(Var)) {
13530 // If we found a capture, any subcaptures are nested.
13531 SubCapturesAreNested = true;
13533 // Retrieve the capture type for this variable.
13534 CaptureType = CSI->getCapture(Var).getCaptureType();
13536 // Compute the type of an expression that refers to this variable.
13537 DeclRefType = CaptureType.getNonReferenceType();
13539 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13540 // are mutable in the sense that user can change their value - they are
13541 // private instances of the captured declarations.
13542 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13543 if (Cap.isCopyCapture() &&
13544 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13545 !(isa<CapturedRegionScopeInfo>(CSI) &&
13546 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13547 DeclRefType.addConst();
13553 // Only block literals, captured statements, and lambda expressions can
13554 // capture; other scopes don't work.
13555 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13556 SourceLocation Loc,
13557 const bool Diagnose, Sema &S) {
13558 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13559 return getLambdaAwareParentOfDeclContext(DC);
13560 else if (Var->hasLocalStorage()) {
13562 diagnoseUncapturableValueReference(S, Loc, Var, DC);
13567 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13568 // certain types of variables (unnamed, variably modified types etc.)
13569 // so check for eligibility.
13570 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13571 SourceLocation Loc,
13572 const bool Diagnose, Sema &S) {
13574 bool IsBlock = isa<BlockScopeInfo>(CSI);
13575 bool IsLambda = isa<LambdaScopeInfo>(CSI);
13577 // Lambdas are not allowed to capture unnamed variables
13578 // (e.g. anonymous unions).
13579 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13580 // assuming that's the intent.
13581 if (IsLambda && !Var->getDeclName()) {
13583 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13584 S.Diag(Var->getLocation(), diag::note_declared_at);
13589 // Prohibit variably-modified types in blocks; they're difficult to deal with.
13590 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13592 S.Diag(Loc, diag::err_ref_vm_type);
13593 S.Diag(Var->getLocation(), diag::note_previous_decl)
13594 << Var->getDeclName();
13598 // Prohibit structs with flexible array members too.
13599 // We cannot capture what is in the tail end of the struct.
13600 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13601 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13604 S.Diag(Loc, diag::err_ref_flexarray_type);
13606 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13607 << Var->getDeclName();
13608 S.Diag(Var->getLocation(), diag::note_previous_decl)
13609 << Var->getDeclName();
13614 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13615 // Lambdas and captured statements are not allowed to capture __block
13616 // variables; they don't support the expected semantics.
13617 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13619 S.Diag(Loc, diag::err_capture_block_variable)
13620 << Var->getDeclName() << !IsLambda;
13621 S.Diag(Var->getLocation(), diag::note_previous_decl)
13622 << Var->getDeclName();
13626 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13627 if (S.getLangOpts().OpenCL && IsBlock &&
13628 Var->getType()->isBlockPointerType()) {
13630 S.Diag(Loc, diag::err_opencl_block_ref_block);
13637 // Returns true if the capture by block was successful.
13638 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13639 SourceLocation Loc,
13640 const bool BuildAndDiagnose,
13641 QualType &CaptureType,
13642 QualType &DeclRefType,
13645 Expr *CopyExpr = nullptr;
13646 bool ByRef = false;
13648 // Blocks are not allowed to capture arrays.
13649 if (CaptureType->isArrayType()) {
13650 if (BuildAndDiagnose) {
13651 S.Diag(Loc, diag::err_ref_array_type);
13652 S.Diag(Var->getLocation(), diag::note_previous_decl)
13653 << Var->getDeclName();
13658 // Forbid the block-capture of autoreleasing variables.
13659 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13660 if (BuildAndDiagnose) {
13661 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13663 S.Diag(Var->getLocation(), diag::note_previous_decl)
13664 << Var->getDeclName();
13669 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13670 if (const auto *PT = CaptureType->getAs<PointerType>()) {
13671 // This function finds out whether there is an AttributedType of kind
13672 // attr_objc_ownership in Ty. The existence of AttributedType of kind
13673 // attr_objc_ownership implies __autoreleasing was explicitly specified
13674 // rather than being added implicitly by the compiler.
13675 auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13676 while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13677 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13680 // Peel off AttributedTypes that are not of kind objc_ownership.
13681 Ty = AttrTy->getModifiedType();
13687 QualType PointeeTy = PT->getPointeeType();
13689 if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13690 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13691 !IsObjCOwnershipAttributedType(PointeeTy)) {
13692 if (BuildAndDiagnose) {
13693 SourceLocation VarLoc = Var->getLocation();
13694 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13696 auto AddAutoreleaseNote =
13697 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13698 // Provide a fix-it for the '__autoreleasing' keyword at the
13699 // appropriate location in the variable's type.
13700 if (const auto *TSI = Var->getTypeSourceInfo()) {
13701 PointerTypeLoc PTL =
13702 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13704 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13705 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13707 if (Loc.isValid()) {
13708 StringRef CharAtLoc = Lexer::getSourceText(
13709 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13710 S.getSourceManager(), S.getLangOpts());
13711 AddAutoreleaseNote << FixItHint::CreateInsertion(
13712 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13713 ? " __autoreleasing "
13714 : " __autoreleasing");
13719 S.Diag(VarLoc, diag::note_declare_parameter_strong);
13724 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13725 if (HasBlocksAttr || CaptureType->isReferenceType() ||
13726 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13727 // Block capture by reference does not change the capture or
13728 // declaration reference types.
13731 // Block capture by copy introduces 'const'.
13732 CaptureType = CaptureType.getNonReferenceType().withConst();
13733 DeclRefType = CaptureType;
13735 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13736 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13737 // The capture logic needs the destructor, so make sure we mark it.
13738 // Usually this is unnecessary because most local variables have
13739 // their destructors marked at declaration time, but parameters are
13740 // an exception because it's technically only the call site that
13741 // actually requires the destructor.
13742 if (isa<ParmVarDecl>(Var))
13743 S.FinalizeVarWithDestructor(Var, Record);
13745 // Enter a new evaluation context to insulate the copy
13746 // full-expression.
13747 EnterExpressionEvaluationContext scope(
13748 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13750 // According to the blocks spec, the capture of a variable from
13751 // the stack requires a const copy constructor. This is not true
13752 // of the copy/move done to move a __block variable to the heap.
13753 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13754 DeclRefType.withConst(),
13758 = S.PerformCopyInitialization(
13759 InitializedEntity::InitializeBlock(Var->getLocation(),
13760 CaptureType, false),
13763 // Build a full-expression copy expression if initialization
13764 // succeeded and used a non-trivial constructor. Recover from
13765 // errors by pretending that the copy isn't necessary.
13766 if (!Result.isInvalid() &&
13767 !cast<CXXConstructExpr>(Result.get())->getConstructor()
13769 Result = S.MaybeCreateExprWithCleanups(Result);
13770 CopyExpr = Result.get();
13776 // Actually capture the variable.
13777 if (BuildAndDiagnose)
13778 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13779 SourceLocation(), CaptureType, CopyExpr);
13786 /// \brief Capture the given variable in the captured region.
13787 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13789 SourceLocation Loc,
13790 const bool BuildAndDiagnose,
13791 QualType &CaptureType,
13792 QualType &DeclRefType,
13793 const bool RefersToCapturedVariable,
13795 // By default, capture variables by reference.
13797 // Using an LValue reference type is consistent with Lambdas (see below).
13798 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13799 if (S.IsOpenMPCapturedDecl(Var))
13800 DeclRefType = DeclRefType.getUnqualifiedType();
13801 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13805 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13807 CaptureType = DeclRefType;
13809 Expr *CopyExpr = nullptr;
13810 if (BuildAndDiagnose) {
13811 // The current implementation assumes that all variables are captured
13812 // by references. Since there is no capture by copy, no expression
13813 // evaluation will be needed.
13814 RecordDecl *RD = RSI->TheRecordDecl;
13817 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13818 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13819 nullptr, false, ICIS_NoInit);
13820 Field->setImplicit(true);
13821 Field->setAccess(AS_private);
13822 RD->addDecl(Field);
13824 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13825 DeclRefType, VK_LValue, Loc);
13826 Var->setReferenced(true);
13827 Var->markUsed(S.Context);
13830 // Actually capture the variable.
13831 if (BuildAndDiagnose)
13832 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13833 SourceLocation(), CaptureType, CopyExpr);
13839 /// \brief Create a field within the lambda class for the variable
13840 /// being captured.
13841 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13842 QualType FieldType, QualType DeclRefType,
13843 SourceLocation Loc,
13844 bool RefersToCapturedVariable) {
13845 CXXRecordDecl *Lambda = LSI->Lambda;
13847 // Build the non-static data member.
13849 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13850 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13851 nullptr, false, ICIS_NoInit);
13852 Field->setImplicit(true);
13853 Field->setAccess(AS_private);
13854 Lambda->addDecl(Field);
13857 /// \brief Capture the given variable in the lambda.
13858 static bool captureInLambda(LambdaScopeInfo *LSI,
13860 SourceLocation Loc,
13861 const bool BuildAndDiagnose,
13862 QualType &CaptureType,
13863 QualType &DeclRefType,
13864 const bool RefersToCapturedVariable,
13865 const Sema::TryCaptureKind Kind,
13866 SourceLocation EllipsisLoc,
13867 const bool IsTopScope,
13870 // Determine whether we are capturing by reference or by value.
13871 bool ByRef = false;
13872 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13873 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13875 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13878 // Compute the type of the field that will capture this variable.
13880 // C++11 [expr.prim.lambda]p15:
13881 // An entity is captured by reference if it is implicitly or
13882 // explicitly captured but not captured by copy. It is
13883 // unspecified whether additional unnamed non-static data
13884 // members are declared in the closure type for entities
13885 // captured by reference.
13887 // FIXME: It is not clear whether we want to build an lvalue reference
13888 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13889 // to do the former, while EDG does the latter. Core issue 1249 will
13890 // clarify, but for now we follow GCC because it's a more permissive and
13891 // easily defensible position.
13892 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13894 // C++11 [expr.prim.lambda]p14:
13895 // For each entity captured by copy, an unnamed non-static
13896 // data member is declared in the closure type. The
13897 // declaration order of these members is unspecified. The type
13898 // of such a data member is the type of the corresponding
13899 // captured entity if the entity is not a reference to an
13900 // object, or the referenced type otherwise. [Note: If the
13901 // captured entity is a reference to a function, the
13902 // corresponding data member is also a reference to a
13903 // function. - end note ]
13904 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13905 if (!RefType->getPointeeType()->isFunctionType())
13906 CaptureType = RefType->getPointeeType();
13909 // Forbid the lambda copy-capture of autoreleasing variables.
13910 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13911 if (BuildAndDiagnose) {
13912 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13913 S.Diag(Var->getLocation(), diag::note_previous_decl)
13914 << Var->getDeclName();
13919 // Make sure that by-copy captures are of a complete and non-abstract type.
13920 if (BuildAndDiagnose) {
13921 if (!CaptureType->isDependentType() &&
13922 S.RequireCompleteType(Loc, CaptureType,
13923 diag::err_capture_of_incomplete_type,
13924 Var->getDeclName()))
13927 if (S.RequireNonAbstractType(Loc, CaptureType,
13928 diag::err_capture_of_abstract_type))
13933 // Capture this variable in the lambda.
13934 if (BuildAndDiagnose)
13935 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13936 RefersToCapturedVariable);
13938 // Compute the type of a reference to this captured variable.
13940 DeclRefType = CaptureType.getNonReferenceType();
13942 // C++ [expr.prim.lambda]p5:
13943 // The closure type for a lambda-expression has a public inline
13944 // function call operator [...]. This function call operator is
13945 // declared const (9.3.1) if and only if the lambda-expression's
13946 // parameter-declaration-clause is not followed by mutable.
13947 DeclRefType = CaptureType.getNonReferenceType();
13948 if (!LSI->Mutable && !CaptureType->isReferenceType())
13949 DeclRefType.addConst();
13952 // Add the capture.
13953 if (BuildAndDiagnose)
13954 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13955 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13960 bool Sema::tryCaptureVariable(
13961 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13962 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13963 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13964 // An init-capture is notionally from the context surrounding its
13965 // declaration, but its parent DC is the lambda class.
13966 DeclContext *VarDC = Var->getDeclContext();
13967 if (Var->isInitCapture())
13968 VarDC = VarDC->getParent();
13970 DeclContext *DC = CurContext;
13971 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13972 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13973 // We need to sync up the Declaration Context with the
13974 // FunctionScopeIndexToStopAt
13975 if (FunctionScopeIndexToStopAt) {
13976 unsigned FSIndex = FunctionScopes.size() - 1;
13977 while (FSIndex != MaxFunctionScopesIndex) {
13978 DC = getLambdaAwareParentOfDeclContext(DC);
13984 // If the variable is declared in the current context, there is no need to
13986 if (VarDC == DC) return true;
13988 // Capture global variables if it is required to use private copy of this
13990 bool IsGlobal = !Var->hasLocalStorage();
13991 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13994 // Walk up the stack to determine whether we can capture the variable,
13995 // performing the "simple" checks that don't depend on type. We stop when
13996 // we've either hit the declared scope of the variable or find an existing
13997 // capture of that variable. We start from the innermost capturing-entity
13998 // (the DC) and ensure that all intervening capturing-entities
13999 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14000 // declcontext can either capture the variable or have already captured
14002 CaptureType = Var->getType();
14003 DeclRefType = CaptureType.getNonReferenceType();
14004 bool Nested = false;
14005 bool Explicit = (Kind != TryCapture_Implicit);
14006 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14008 // Only block literals, captured statements, and lambda expressions can
14009 // capture; other scopes don't work.
14010 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14014 // We need to check for the parent *first* because, if we *have*
14015 // private-captured a global variable, we need to recursively capture it in
14016 // intermediate blocks, lambdas, etc.
14019 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14025 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
14026 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14029 // Check whether we've already captured it.
14030 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14032 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14035 // If we are instantiating a generic lambda call operator body,
14036 // we do not want to capture new variables. What was captured
14037 // during either a lambdas transformation or initial parsing
14039 if (isGenericLambdaCallOperatorSpecialization(DC)) {
14040 if (BuildAndDiagnose) {
14041 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14042 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14043 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14044 Diag(Var->getLocation(), diag::note_previous_decl)
14045 << Var->getDeclName();
14046 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14048 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14052 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14053 // certain types of variables (unnamed, variably modified types etc.)
14054 // so check for eligibility.
14055 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14058 // Try to capture variable-length arrays types.
14059 if (Var->getType()->isVariablyModifiedType()) {
14060 // We're going to walk down into the type and look for VLA
14062 QualType QTy = Var->getType();
14063 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14064 QTy = PVD->getOriginalType();
14065 captureVariablyModifiedType(Context, QTy, CSI);
14068 if (getLangOpts().OpenMP) {
14069 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14070 // OpenMP private variables should not be captured in outer scope, so
14071 // just break here. Similarly, global variables that are captured in a
14072 // target region should not be captured outside the scope of the region.
14073 if (RSI->CapRegionKind == CR_OpenMP) {
14074 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14075 // When we detect target captures we are looking from inside the
14076 // target region, therefore we need to propagate the capture from the
14077 // enclosing region. Therefore, the capture is not initially nested.
14079 FunctionScopesIndex--;
14081 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14082 Nested = !IsTargetCap;
14083 DeclRefType = DeclRefType.getUnqualifiedType();
14084 CaptureType = Context.getLValueReferenceType(DeclRefType);
14090 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14091 // No capture-default, and this is not an explicit capture
14092 // so cannot capture this variable.
14093 if (BuildAndDiagnose) {
14094 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14095 Diag(Var->getLocation(), diag::note_previous_decl)
14096 << Var->getDeclName();
14097 if (cast<LambdaScopeInfo>(CSI)->Lambda)
14098 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14099 diag::note_lambda_decl);
14100 // FIXME: If we error out because an outer lambda can not implicitly
14101 // capture a variable that an inner lambda explicitly captures, we
14102 // should have the inner lambda do the explicit capture - because
14103 // it makes for cleaner diagnostics later. This would purely be done
14104 // so that the diagnostic does not misleadingly claim that a variable
14105 // can not be captured by a lambda implicitly even though it is captured
14106 // explicitly. Suggestion:
14107 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14108 // at the function head
14109 // - cache the StartingDeclContext - this must be a lambda
14110 // - captureInLambda in the innermost lambda the variable.
14115 FunctionScopesIndex--;
14118 } while (!VarDC->Equals(DC));
14120 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14121 // computing the type of the capture at each step, checking type-specific
14122 // requirements, and adding captures if requested.
14123 // If the variable had already been captured previously, we start capturing
14124 // at the lambda nested within that one.
14125 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14127 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14129 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14130 if (!captureInBlock(BSI, Var, ExprLoc,
14131 BuildAndDiagnose, CaptureType,
14132 DeclRefType, Nested, *this))
14135 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14136 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14137 BuildAndDiagnose, CaptureType,
14138 DeclRefType, Nested, *this))
14142 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14143 if (!captureInLambda(LSI, Var, ExprLoc,
14144 BuildAndDiagnose, CaptureType,
14145 DeclRefType, Nested, Kind, EllipsisLoc,
14146 /*IsTopScope*/I == N - 1, *this))
14154 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14155 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14156 QualType CaptureType;
14157 QualType DeclRefType;
14158 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14159 /*BuildAndDiagnose=*/true, CaptureType,
14160 DeclRefType, nullptr);
14163 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14164 QualType CaptureType;
14165 QualType DeclRefType;
14166 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14167 /*BuildAndDiagnose=*/false, CaptureType,
14168 DeclRefType, nullptr);
14171 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14172 QualType CaptureType;
14173 QualType DeclRefType;
14175 // Determine whether we can capture this variable.
14176 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14177 /*BuildAndDiagnose=*/false, CaptureType,
14178 DeclRefType, nullptr))
14181 return DeclRefType;
14186 // If either the type of the variable or the initializer is dependent,
14187 // return false. Otherwise, determine whether the variable is a constant
14188 // expression. Use this if you need to know if a variable that might or
14189 // might not be dependent is truly a constant expression.
14190 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14191 ASTContext &Context) {
14193 if (Var->getType()->isDependentType())
14195 const VarDecl *DefVD = nullptr;
14196 Var->getAnyInitializer(DefVD);
14199 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14200 Expr *Init = cast<Expr>(Eval->Value);
14201 if (Init->isValueDependent())
14203 return IsVariableAConstantExpression(Var, Context);
14207 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14208 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14209 // an object that satisfies the requirements for appearing in a
14210 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14211 // is immediately applied." This function handles the lvalue-to-rvalue
14212 // conversion part.
14213 MaybeODRUseExprs.erase(E->IgnoreParens());
14215 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14216 // to a variable that is a constant expression, and if so, identify it as
14217 // a reference to a variable that does not involve an odr-use of that
14219 if (LambdaScopeInfo *LSI = getCurLambda()) {
14220 Expr *SansParensExpr = E->IgnoreParens();
14221 VarDecl *Var = nullptr;
14222 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14223 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14224 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14225 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14227 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14228 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14232 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14233 Res = CorrectDelayedTyposInExpr(Res);
14235 if (!Res.isUsable())
14238 // If a constant-expression is a reference to a variable where we delay
14239 // deciding whether it is an odr-use, just assume we will apply the
14240 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
14241 // (a non-type template argument), we have special handling anyway.
14242 UpdateMarkingForLValueToRValue(Res.get());
14246 void Sema::CleanupVarDeclMarking() {
14247 for (Expr *E : MaybeODRUseExprs) {
14249 SourceLocation Loc;
14250 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14251 Var = cast<VarDecl>(DRE->getDecl());
14252 Loc = DRE->getLocation();
14253 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14254 Var = cast<VarDecl>(ME->getMemberDecl());
14255 Loc = ME->getMemberLoc();
14257 llvm_unreachable("Unexpected expression");
14260 MarkVarDeclODRUsed(Var, Loc, *this,
14261 /*MaxFunctionScopeIndex Pointer*/ nullptr);
14264 MaybeODRUseExprs.clear();
14268 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14269 VarDecl *Var, Expr *E) {
14270 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14271 "Invalid Expr argument to DoMarkVarDeclReferenced");
14272 Var->setReferenced();
14274 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14276 bool OdrUseContext = isOdrUseContext(SemaRef);
14277 bool NeedDefinition =
14278 OdrUseContext || (isEvaluatableContext(SemaRef) &&
14279 Var->isUsableInConstantExpressions(SemaRef.Context));
14281 VarTemplateSpecializationDecl *VarSpec =
14282 dyn_cast<VarTemplateSpecializationDecl>(Var);
14283 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14284 "Can't instantiate a partial template specialization.");
14286 // If this might be a member specialization of a static data member, check
14287 // the specialization is visible. We already did the checks for variable
14288 // template specializations when we created them.
14289 if (NeedDefinition && TSK != TSK_Undeclared &&
14290 !isa<VarTemplateSpecializationDecl>(Var))
14291 SemaRef.checkSpecializationVisibility(Loc, Var);
14293 // Perform implicit instantiation of static data members, static data member
14294 // templates of class templates, and variable template specializations. Delay
14295 // instantiations of variable templates, except for those that could be used
14296 // in a constant expression.
14297 if (NeedDefinition && isTemplateInstantiation(TSK)) {
14298 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14300 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14301 if (Var->getPointOfInstantiation().isInvalid()) {
14302 // This is a modification of an existing AST node. Notify listeners.
14303 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14304 L->StaticDataMemberInstantiated(Var);
14305 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14306 // Don't bother trying to instantiate it again, unless we might need
14307 // its initializer before we get to the end of the TU.
14308 TryInstantiating = false;
14311 if (Var->getPointOfInstantiation().isInvalid())
14312 Var->setTemplateSpecializationKind(TSK, Loc);
14314 if (TryInstantiating) {
14315 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14316 bool InstantiationDependent = false;
14317 bool IsNonDependent =
14318 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14319 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14322 // Do not instantiate specializations that are still type-dependent.
14323 if (IsNonDependent) {
14324 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14325 // Do not defer instantiations of variables which could be used in a
14326 // constant expression.
14327 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14329 SemaRef.PendingInstantiations
14330 .push_back(std::make_pair(Var, PointOfInstantiation));
14336 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14337 // the requirements for appearing in a constant expression (5.19) and, if
14338 // it is an object, the lvalue-to-rvalue conversion (4.1)
14339 // is immediately applied." We check the first part here, and
14340 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14341 // Note that we use the C++11 definition everywhere because nothing in
14342 // C++03 depends on whether we get the C++03 version correct. The second
14343 // part does not apply to references, since they are not objects.
14344 if (OdrUseContext && E &&
14345 IsVariableAConstantExpression(Var, SemaRef.Context)) {
14346 // A reference initialized by a constant expression can never be
14347 // odr-used, so simply ignore it.
14348 if (!Var->getType()->isReferenceType())
14349 SemaRef.MaybeODRUseExprs.insert(E);
14350 } else if (OdrUseContext) {
14351 MarkVarDeclODRUsed(Var, Loc, SemaRef,
14352 /*MaxFunctionScopeIndex ptr*/ nullptr);
14353 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14354 // If this is a dependent context, we don't need to mark variables as
14355 // odr-used, but we may still need to track them for lambda capture.
14356 // FIXME: Do we also need to do this inside dependent typeid expressions
14357 // (which are modeled as unevaluated at this point)?
14358 const bool RefersToEnclosingScope =
14359 (SemaRef.CurContext != Var->getDeclContext() &&
14360 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14361 if (RefersToEnclosingScope) {
14362 LambdaScopeInfo *const LSI =
14363 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14364 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14365 // If a variable could potentially be odr-used, defer marking it so
14366 // until we finish analyzing the full expression for any
14367 // lvalue-to-rvalue
14368 // or discarded value conversions that would obviate odr-use.
14369 // Add it to the list of potential captures that will be analyzed
14370 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14371 // unless the variable is a reference that was initialized by a constant
14372 // expression (this will never need to be captured or odr-used).
14373 assert(E && "Capture variable should be used in an expression.");
14374 if (!Var->getType()->isReferenceType() ||
14375 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14376 LSI->addPotentialCapture(E->IgnoreParens());
14382 /// \brief Mark a variable referenced, and check whether it is odr-used
14383 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
14384 /// used directly for normal expressions referring to VarDecl.
14385 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14386 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14389 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14390 Decl *D, Expr *E, bool MightBeOdrUse) {
14391 if (SemaRef.isInOpenMPDeclareTargetContext())
14392 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14394 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14395 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14399 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14401 // If this is a call to a method via a cast, also mark the method in the
14402 // derived class used in case codegen can devirtualize the call.
14403 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14406 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14409 // Only attempt to devirtualize if this is truly a virtual call.
14410 bool IsVirtualCall = MD->isVirtual() &&
14411 ME->performsVirtualDispatch(SemaRef.getLangOpts());
14412 if (!IsVirtualCall)
14414 const Expr *Base = ME->getBase();
14415 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14416 if (!MostDerivedClassDecl)
14418 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14419 if (!DM || DM->isPure())
14421 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14424 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14425 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14426 // TODO: update this with DR# once a defect report is filed.
14427 // C++11 defect. The address of a pure member should not be an ODR use, even
14428 // if it's a qualified reference.
14429 bool OdrUse = true;
14430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14431 if (Method->isVirtual())
14433 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14436 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14437 void Sema::MarkMemberReferenced(MemberExpr *E) {
14438 // C++11 [basic.def.odr]p2:
14439 // A non-overloaded function whose name appears as a potentially-evaluated
14440 // expression or a member of a set of candidate functions, if selected by
14441 // overload resolution when referred to from a potentially-evaluated
14442 // expression, is odr-used, unless it is a pure virtual function and its
14443 // name is not explicitly qualified.
14444 bool MightBeOdrUse = true;
14445 if (E->performsVirtualDispatch(getLangOpts())) {
14446 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14447 if (Method->isPure())
14448 MightBeOdrUse = false;
14450 SourceLocation Loc = E->getMemberLoc().isValid() ?
14451 E->getMemberLoc() : E->getLocStart();
14452 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14455 /// \brief Perform marking for a reference to an arbitrary declaration. It
14456 /// marks the declaration referenced, and performs odr-use checking for
14457 /// functions and variables. This method should not be used when building a
14458 /// normal expression which refers to a variable.
14459 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14460 bool MightBeOdrUse) {
14461 if (MightBeOdrUse) {
14462 if (auto *VD = dyn_cast<VarDecl>(D)) {
14463 MarkVariableReferenced(Loc, VD);
14467 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14468 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14471 D->setReferenced();
14475 // Mark all of the declarations used by a type as referenced.
14476 // FIXME: Not fully implemented yet! We need to have a better understanding
14477 // of when we're entering a context we should not recurse into.
14478 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14479 // TreeTransforms rebuilding the type in a new context. Rather than
14480 // duplicating the TreeTransform logic, we should consider reusing it here.
14481 // Currently that causes problems when rebuilding LambdaExprs.
14482 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14484 SourceLocation Loc;
14487 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14489 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14491 bool TraverseTemplateArgument(const TemplateArgument &Arg);
14495 bool MarkReferencedDecls::TraverseTemplateArgument(
14496 const TemplateArgument &Arg) {
14498 // A non-type template argument is a constant-evaluated context.
14499 EnterExpressionEvaluationContext Evaluated(
14500 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14501 if (Arg.getKind() == TemplateArgument::Declaration) {
14502 if (Decl *D = Arg.getAsDecl())
14503 S.MarkAnyDeclReferenced(Loc, D, true);
14504 } else if (Arg.getKind() == TemplateArgument::Expression) {
14505 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14509 return Inherited::TraverseTemplateArgument(Arg);
14512 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14513 MarkReferencedDecls Marker(*this, Loc);
14514 Marker.TraverseType(T);
14518 /// \brief Helper class that marks all of the declarations referenced by
14519 /// potentially-evaluated subexpressions as "referenced".
14520 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14522 bool SkipLocalVariables;
14525 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14527 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14528 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14530 void VisitDeclRefExpr(DeclRefExpr *E) {
14531 // If we were asked not to visit local variables, don't.
14532 if (SkipLocalVariables) {
14533 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14534 if (VD->hasLocalStorage())
14538 S.MarkDeclRefReferenced(E);
14541 void VisitMemberExpr(MemberExpr *E) {
14542 S.MarkMemberReferenced(E);
14543 Inherited::VisitMemberExpr(E);
14546 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14547 S.MarkFunctionReferenced(E->getLocStart(),
14548 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14549 Visit(E->getSubExpr());
14552 void VisitCXXNewExpr(CXXNewExpr *E) {
14553 if (E->getOperatorNew())
14554 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14555 if (E->getOperatorDelete())
14556 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14557 Inherited::VisitCXXNewExpr(E);
14560 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14561 if (E->getOperatorDelete())
14562 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14563 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14564 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14565 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14566 S.MarkFunctionReferenced(E->getLocStart(),
14567 S.LookupDestructor(Record));
14570 Inherited::VisitCXXDeleteExpr(E);
14573 void VisitCXXConstructExpr(CXXConstructExpr *E) {
14574 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14575 Inherited::VisitCXXConstructExpr(E);
14578 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14579 Visit(E->getExpr());
14582 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14583 Inherited::VisitImplicitCastExpr(E);
14585 if (E->getCastKind() == CK_LValueToRValue)
14586 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14591 /// \brief Mark any declarations that appear within this expression or any
14592 /// potentially-evaluated subexpressions as "referenced".
14594 /// \param SkipLocalVariables If true, don't mark local variables as
14596 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14597 bool SkipLocalVariables) {
14598 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14601 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14602 /// of the program being compiled.
14604 /// This routine emits the given diagnostic when the code currently being
14605 /// type-checked is "potentially evaluated", meaning that there is a
14606 /// possibility that the code will actually be executable. Code in sizeof()
14607 /// expressions, code used only during overload resolution, etc., are not
14608 /// potentially evaluated. This routine will suppress such diagnostics or,
14609 /// in the absolutely nutty case of potentially potentially evaluated
14610 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14613 /// This routine should be used for all diagnostics that describe the run-time
14614 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14615 /// Failure to do so will likely result in spurious diagnostics or failures
14616 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14617 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14618 const PartialDiagnostic &PD) {
14619 switch (ExprEvalContexts.back().Context) {
14620 case ExpressionEvaluationContext::Unevaluated:
14621 case ExpressionEvaluationContext::UnevaluatedList:
14622 case ExpressionEvaluationContext::UnevaluatedAbstract:
14623 case ExpressionEvaluationContext::DiscardedStatement:
14624 // The argument will never be evaluated, so don't complain.
14627 case ExpressionEvaluationContext::ConstantEvaluated:
14628 // Relevant diagnostics should be produced by constant evaluation.
14631 case ExpressionEvaluationContext::PotentiallyEvaluated:
14632 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14633 if (Statement && getCurFunctionOrMethodDecl()) {
14634 FunctionScopes.back()->PossiblyUnreachableDiags.
14635 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14646 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14647 CallExpr *CE, FunctionDecl *FD) {
14648 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14651 // If we're inside a decltype's expression, don't check for a valid return
14652 // type or construct temporaries until we know whether this is the last call.
14653 if (ExprEvalContexts.back().IsDecltype) {
14654 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14658 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14663 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14664 : FD(FD), CE(CE) { }
14666 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14668 S.Diag(Loc, diag::err_call_incomplete_return)
14669 << T << CE->getSourceRange();
14673 S.Diag(Loc, diag::err_call_function_incomplete_return)
14674 << CE->getSourceRange() << FD->getDeclName() << T;
14675 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14676 << FD->getDeclName();
14678 } Diagnoser(FD, CE);
14680 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14686 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14687 // will prevent this condition from triggering, which is what we want.
14688 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14689 SourceLocation Loc;
14691 unsigned diagnostic = diag::warn_condition_is_assignment;
14692 bool IsOrAssign = false;
14694 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14695 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14698 IsOrAssign = Op->getOpcode() == BO_OrAssign;
14700 // Greylist some idioms by putting them into a warning subcategory.
14701 if (ObjCMessageExpr *ME
14702 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14703 Selector Sel = ME->getSelector();
14705 // self = [<foo> init...]
14706 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14707 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14709 // <foo> = [<bar> nextObject]
14710 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14711 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14714 Loc = Op->getOperatorLoc();
14715 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14716 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14719 IsOrAssign = Op->getOperator() == OO_PipeEqual;
14720 Loc = Op->getOperatorLoc();
14721 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14722 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14724 // Not an assignment.
14728 Diag(Loc, diagnostic) << E->getSourceRange();
14730 SourceLocation Open = E->getLocStart();
14731 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14732 Diag(Loc, diag::note_condition_assign_silence)
14733 << FixItHint::CreateInsertion(Open, "(")
14734 << FixItHint::CreateInsertion(Close, ")");
14737 Diag(Loc, diag::note_condition_or_assign_to_comparison)
14738 << FixItHint::CreateReplacement(Loc, "!=");
14740 Diag(Loc, diag::note_condition_assign_to_comparison)
14741 << FixItHint::CreateReplacement(Loc, "==");
14744 /// \brief Redundant parentheses over an equality comparison can indicate
14745 /// that the user intended an assignment used as condition.
14746 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14747 // Don't warn if the parens came from a macro.
14748 SourceLocation parenLoc = ParenE->getLocStart();
14749 if (parenLoc.isInvalid() || parenLoc.isMacroID())
14751 // Don't warn for dependent expressions.
14752 if (ParenE->isTypeDependent())
14755 Expr *E = ParenE->IgnoreParens();
14757 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14758 if (opE->getOpcode() == BO_EQ &&
14759 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14760 == Expr::MLV_Valid) {
14761 SourceLocation Loc = opE->getOperatorLoc();
14763 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14764 SourceRange ParenERange = ParenE->getSourceRange();
14765 Diag(Loc, diag::note_equality_comparison_silence)
14766 << FixItHint::CreateRemoval(ParenERange.getBegin())
14767 << FixItHint::CreateRemoval(ParenERange.getEnd());
14768 Diag(Loc, diag::note_equality_comparison_to_assign)
14769 << FixItHint::CreateReplacement(Loc, "=");
14773 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14774 bool IsConstexpr) {
14775 DiagnoseAssignmentAsCondition(E);
14776 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14777 DiagnoseEqualityWithExtraParens(parenE);
14779 ExprResult result = CheckPlaceholderExpr(E);
14780 if (result.isInvalid()) return ExprError();
14783 if (!E->isTypeDependent()) {
14784 if (getLangOpts().CPlusPlus)
14785 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14787 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14788 if (ERes.isInvalid())
14789 return ExprError();
14792 QualType T = E->getType();
14793 if (!T->isScalarType()) { // C99 6.8.4.1p1
14794 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14795 << T << E->getSourceRange();
14796 return ExprError();
14798 CheckBoolLikeConversion(E, Loc);
14804 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14805 Expr *SubExpr, ConditionKind CK) {
14806 // Empty conditions are valid in for-statements.
14808 return ConditionResult();
14812 case ConditionKind::Boolean:
14813 Cond = CheckBooleanCondition(Loc, SubExpr);
14816 case ConditionKind::ConstexprIf:
14817 Cond = CheckBooleanCondition(Loc, SubExpr, true);
14820 case ConditionKind::Switch:
14821 Cond = CheckSwitchCondition(Loc, SubExpr);
14824 if (Cond.isInvalid())
14825 return ConditionError();
14827 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14828 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14829 if (!FullExpr.get())
14830 return ConditionError();
14832 return ConditionResult(*this, nullptr, FullExpr,
14833 CK == ConditionKind::ConstexprIf);
14837 /// A visitor for rebuilding a call to an __unknown_any expression
14838 /// to have an appropriate type.
14839 struct RebuildUnknownAnyFunction
14840 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14844 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14846 ExprResult VisitStmt(Stmt *S) {
14847 llvm_unreachable("unexpected statement!");
14850 ExprResult VisitExpr(Expr *E) {
14851 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14852 << E->getSourceRange();
14853 return ExprError();
14856 /// Rebuild an expression which simply semantically wraps another
14857 /// expression which it shares the type and value kind of.
14858 template <class T> ExprResult rebuildSugarExpr(T *E) {
14859 ExprResult SubResult = Visit(E->getSubExpr());
14860 if (SubResult.isInvalid()) return ExprError();
14862 Expr *SubExpr = SubResult.get();
14863 E->setSubExpr(SubExpr);
14864 E->setType(SubExpr->getType());
14865 E->setValueKind(SubExpr->getValueKind());
14866 assert(E->getObjectKind() == OK_Ordinary);
14870 ExprResult VisitParenExpr(ParenExpr *E) {
14871 return rebuildSugarExpr(E);
14874 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14875 return rebuildSugarExpr(E);
14878 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14879 ExprResult SubResult = Visit(E->getSubExpr());
14880 if (SubResult.isInvalid()) return ExprError();
14882 Expr *SubExpr = SubResult.get();
14883 E->setSubExpr(SubExpr);
14884 E->setType(S.Context.getPointerType(SubExpr->getType()));
14885 assert(E->getValueKind() == VK_RValue);
14886 assert(E->getObjectKind() == OK_Ordinary);
14890 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14891 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14893 E->setType(VD->getType());
14895 assert(E->getValueKind() == VK_RValue);
14896 if (S.getLangOpts().CPlusPlus &&
14897 !(isa<CXXMethodDecl>(VD) &&
14898 cast<CXXMethodDecl>(VD)->isInstance()))
14899 E->setValueKind(VK_LValue);
14904 ExprResult VisitMemberExpr(MemberExpr *E) {
14905 return resolveDecl(E, E->getMemberDecl());
14908 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14909 return resolveDecl(E, E->getDecl());
14914 /// Given a function expression of unknown-any type, try to rebuild it
14915 /// to have a function type.
14916 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14917 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14918 if (Result.isInvalid()) return ExprError();
14919 return S.DefaultFunctionArrayConversion(Result.get());
14923 /// A visitor for rebuilding an expression of type __unknown_anytype
14924 /// into one which resolves the type directly on the referring
14925 /// expression. Strict preservation of the original source
14926 /// structure is not a goal.
14927 struct RebuildUnknownAnyExpr
14928 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14932 /// The current destination type.
14935 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14936 : S(S), DestType(CastType) {}
14938 ExprResult VisitStmt(Stmt *S) {
14939 llvm_unreachable("unexpected statement!");
14942 ExprResult VisitExpr(Expr *E) {
14943 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14944 << E->getSourceRange();
14945 return ExprError();
14948 ExprResult VisitCallExpr(CallExpr *E);
14949 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14951 /// Rebuild an expression which simply semantically wraps another
14952 /// expression which it shares the type and value kind of.
14953 template <class T> ExprResult rebuildSugarExpr(T *E) {
14954 ExprResult SubResult = Visit(E->getSubExpr());
14955 if (SubResult.isInvalid()) return ExprError();
14956 Expr *SubExpr = SubResult.get();
14957 E->setSubExpr(SubExpr);
14958 E->setType(SubExpr->getType());
14959 E->setValueKind(SubExpr->getValueKind());
14960 assert(E->getObjectKind() == OK_Ordinary);
14964 ExprResult VisitParenExpr(ParenExpr *E) {
14965 return rebuildSugarExpr(E);
14968 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14969 return rebuildSugarExpr(E);
14972 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14973 const PointerType *Ptr = DestType->getAs<PointerType>();
14975 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14976 << E->getSourceRange();
14977 return ExprError();
14980 if (isa<CallExpr>(E->getSubExpr())) {
14981 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14982 << E->getSourceRange();
14983 return ExprError();
14986 assert(E->getValueKind() == VK_RValue);
14987 assert(E->getObjectKind() == OK_Ordinary);
14988 E->setType(DestType);
14990 // Build the sub-expression as if it were an object of the pointee type.
14991 DestType = Ptr->getPointeeType();
14992 ExprResult SubResult = Visit(E->getSubExpr());
14993 if (SubResult.isInvalid()) return ExprError();
14994 E->setSubExpr(SubResult.get());
14998 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15000 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15002 ExprResult VisitMemberExpr(MemberExpr *E) {
15003 return resolveDecl(E, E->getMemberDecl());
15006 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15007 return resolveDecl(E, E->getDecl());
15012 /// Rebuilds a call expression which yielded __unknown_anytype.
15013 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15014 Expr *CalleeExpr = E->getCallee();
15018 FK_FunctionPointer,
15023 QualType CalleeType = CalleeExpr->getType();
15024 if (CalleeType == S.Context.BoundMemberTy) {
15025 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15026 Kind = FK_MemberFunction;
15027 CalleeType = Expr::findBoundMemberType(CalleeExpr);
15028 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15029 CalleeType = Ptr->getPointeeType();
15030 Kind = FK_FunctionPointer;
15032 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15033 Kind = FK_BlockPointer;
15035 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15037 // Verify that this is a legal result type of a function.
15038 if (DestType->isArrayType() || DestType->isFunctionType()) {
15039 unsigned diagID = diag::err_func_returning_array_function;
15040 if (Kind == FK_BlockPointer)
15041 diagID = diag::err_block_returning_array_function;
15043 S.Diag(E->getExprLoc(), diagID)
15044 << DestType->isFunctionType() << DestType;
15045 return ExprError();
15048 // Otherwise, go ahead and set DestType as the call's result.
15049 E->setType(DestType.getNonLValueExprType(S.Context));
15050 E->setValueKind(Expr::getValueKindForType(DestType));
15051 assert(E->getObjectKind() == OK_Ordinary);
15053 // Rebuild the function type, replacing the result type with DestType.
15054 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15056 // __unknown_anytype(...) is a special case used by the debugger when
15057 // it has no idea what a function's signature is.
15059 // We want to build this call essentially under the K&R
15060 // unprototyped rules, but making a FunctionNoProtoType in C++
15061 // would foul up all sorts of assumptions. However, we cannot
15062 // simply pass all arguments as variadic arguments, nor can we
15063 // portably just call the function under a non-variadic type; see
15064 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15065 // However, it turns out that in practice it is generally safe to
15066 // call a function declared as "A foo(B,C,D);" under the prototype
15067 // "A foo(B,C,D,...);". The only known exception is with the
15068 // Windows ABI, where any variadic function is implicitly cdecl
15069 // regardless of its normal CC. Therefore we change the parameter
15070 // types to match the types of the arguments.
15072 // This is a hack, but it is far superior to moving the
15073 // corresponding target-specific code from IR-gen to Sema/AST.
15075 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15076 SmallVector<QualType, 8> ArgTypes;
15077 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15078 ArgTypes.reserve(E->getNumArgs());
15079 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15080 Expr *Arg = E->getArg(i);
15081 QualType ArgType = Arg->getType();
15082 if (E->isLValue()) {
15083 ArgType = S.Context.getLValueReferenceType(ArgType);
15084 } else if (E->isXValue()) {
15085 ArgType = S.Context.getRValueReferenceType(ArgType);
15087 ArgTypes.push_back(ArgType);
15089 ParamTypes = ArgTypes;
15091 DestType = S.Context.getFunctionType(DestType, ParamTypes,
15092 Proto->getExtProtoInfo());
15094 DestType = S.Context.getFunctionNoProtoType(DestType,
15095 FnType->getExtInfo());
15098 // Rebuild the appropriate pointer-to-function type.
15100 case FK_MemberFunction:
15104 case FK_FunctionPointer:
15105 DestType = S.Context.getPointerType(DestType);
15108 case FK_BlockPointer:
15109 DestType = S.Context.getBlockPointerType(DestType);
15113 // Finally, we can recurse.
15114 ExprResult CalleeResult = Visit(CalleeExpr);
15115 if (!CalleeResult.isUsable()) return ExprError();
15116 E->setCallee(CalleeResult.get());
15118 // Bind a temporary if necessary.
15119 return S.MaybeBindToTemporary(E);
15122 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15123 // Verify that this is a legal result type of a call.
15124 if (DestType->isArrayType() || DestType->isFunctionType()) {
15125 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15126 << DestType->isFunctionType() << DestType;
15127 return ExprError();
15130 // Rewrite the method result type if available.
15131 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15132 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15133 Method->setReturnType(DestType);
15136 // Change the type of the message.
15137 E->setType(DestType.getNonReferenceType());
15138 E->setValueKind(Expr::getValueKindForType(DestType));
15140 return S.MaybeBindToTemporary(E);
15143 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15144 // The only case we should ever see here is a function-to-pointer decay.
15145 if (E->getCastKind() == CK_FunctionToPointerDecay) {
15146 assert(E->getValueKind() == VK_RValue);
15147 assert(E->getObjectKind() == OK_Ordinary);
15149 E->setType(DestType);
15151 // Rebuild the sub-expression as the pointee (function) type.
15152 DestType = DestType->castAs<PointerType>()->getPointeeType();
15154 ExprResult Result = Visit(E->getSubExpr());
15155 if (!Result.isUsable()) return ExprError();
15157 E->setSubExpr(Result.get());
15159 } else if (E->getCastKind() == CK_LValueToRValue) {
15160 assert(E->getValueKind() == VK_RValue);
15161 assert(E->getObjectKind() == OK_Ordinary);
15163 assert(isa<BlockPointerType>(E->getType()));
15165 E->setType(DestType);
15167 // The sub-expression has to be a lvalue reference, so rebuild it as such.
15168 DestType = S.Context.getLValueReferenceType(DestType);
15170 ExprResult Result = Visit(E->getSubExpr());
15171 if (!Result.isUsable()) return ExprError();
15173 E->setSubExpr(Result.get());
15176 llvm_unreachable("Unhandled cast type!");
15180 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15181 ExprValueKind ValueKind = VK_LValue;
15182 QualType Type = DestType;
15184 // We know how to make this work for certain kinds of decls:
15187 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15188 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15189 DestType = Ptr->getPointeeType();
15190 ExprResult Result = resolveDecl(E, VD);
15191 if (Result.isInvalid()) return ExprError();
15192 return S.ImpCastExprToType(Result.get(), Type,
15193 CK_FunctionToPointerDecay, VK_RValue);
15196 if (!Type->isFunctionType()) {
15197 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15198 << VD << E->getSourceRange();
15199 return ExprError();
15201 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15202 // We must match the FunctionDecl's type to the hack introduced in
15203 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15204 // type. See the lengthy commentary in that routine.
15205 QualType FDT = FD->getType();
15206 const FunctionType *FnType = FDT->castAs<FunctionType>();
15207 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15208 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15209 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15210 SourceLocation Loc = FD->getLocation();
15211 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15212 FD->getDeclContext(),
15213 Loc, Loc, FD->getNameInfo().getName(),
15214 DestType, FD->getTypeSourceInfo(),
15215 SC_None, false/*isInlineSpecified*/,
15216 FD->hasPrototype(),
15217 false/*isConstexprSpecified*/);
15219 if (FD->getQualifier())
15220 NewFD->setQualifierInfo(FD->getQualifierLoc());
15222 SmallVector<ParmVarDecl*, 16> Params;
15223 for (const auto &AI : FT->param_types()) {
15224 ParmVarDecl *Param =
15225 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15226 Param->setScopeInfo(0, Params.size());
15227 Params.push_back(Param);
15229 NewFD->setParams(Params);
15230 DRE->setDecl(NewFD);
15231 VD = DRE->getDecl();
15235 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15236 if (MD->isInstance()) {
15237 ValueKind = VK_RValue;
15238 Type = S.Context.BoundMemberTy;
15241 // Function references aren't l-values in C.
15242 if (!S.getLangOpts().CPlusPlus)
15243 ValueKind = VK_RValue;
15246 } else if (isa<VarDecl>(VD)) {
15247 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15248 Type = RefTy->getPointeeType();
15249 } else if (Type->isFunctionType()) {
15250 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15251 << VD << E->getSourceRange();
15252 return ExprError();
15257 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15258 << VD << E->getSourceRange();
15259 return ExprError();
15262 // Modifying the declaration like this is friendly to IR-gen but
15263 // also really dangerous.
15264 VD->setType(DestType);
15266 E->setValueKind(ValueKind);
15270 /// Check a cast of an unknown-any type. We intentionally only
15271 /// trigger this for C-style casts.
15272 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15273 Expr *CastExpr, CastKind &CastKind,
15274 ExprValueKind &VK, CXXCastPath &Path) {
15275 // The type we're casting to must be either void or complete.
15276 if (!CastType->isVoidType() &&
15277 RequireCompleteType(TypeRange.getBegin(), CastType,
15278 diag::err_typecheck_cast_to_incomplete))
15279 return ExprError();
15281 // Rewrite the casted expression from scratch.
15282 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15283 if (!result.isUsable()) return ExprError();
15285 CastExpr = result.get();
15286 VK = CastExpr->getValueKind();
15287 CastKind = CK_NoOp;
15292 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15293 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15296 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15297 Expr *arg, QualType ¶mType) {
15298 // If the syntactic form of the argument is not an explicit cast of
15299 // any sort, just do default argument promotion.
15300 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15302 ExprResult result = DefaultArgumentPromotion(arg);
15303 if (result.isInvalid()) return ExprError();
15304 paramType = result.get()->getType();
15308 // Otherwise, use the type that was written in the explicit cast.
15309 assert(!arg->hasPlaceholderType());
15310 paramType = castArg->getTypeAsWritten();
15312 // Copy-initialize a parameter of that type.
15313 InitializedEntity entity =
15314 InitializedEntity::InitializeParameter(Context, paramType,
15315 /*consumed*/ false);
15316 return PerformCopyInitialization(entity, callLoc, arg);
15319 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15321 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15323 E = E->IgnoreParenImpCasts();
15324 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15325 E = call->getCallee();
15326 diagID = diag::err_uncasted_call_of_unknown_any;
15332 SourceLocation loc;
15334 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15335 loc = ref->getLocation();
15336 d = ref->getDecl();
15337 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15338 loc = mem->getMemberLoc();
15339 d = mem->getMemberDecl();
15340 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15341 diagID = diag::err_uncasted_call_of_unknown_any;
15342 loc = msg->getSelectorStartLoc();
15343 d = msg->getMethodDecl();
15345 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15346 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15347 << orig->getSourceRange();
15348 return ExprError();
15351 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15352 << E->getSourceRange();
15353 return ExprError();
15356 S.Diag(loc, diagID) << d << orig->getSourceRange();
15358 // Never recoverable.
15359 return ExprError();
15362 /// Check for operands with placeholder types and complain if found.
15363 /// Returns true if there was an error and no recovery was possible.
15364 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15365 if (!getLangOpts().CPlusPlus) {
15366 // C cannot handle TypoExpr nodes on either side of a binop because it
15367 // doesn't handle dependent types properly, so make sure any TypoExprs have
15368 // been dealt with before checking the operands.
15369 ExprResult Result = CorrectDelayedTyposInExpr(E);
15370 if (!Result.isUsable()) return ExprError();
15374 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15375 if (!placeholderType) return E;
15377 switch (placeholderType->getKind()) {
15379 // Overloaded expressions.
15380 case BuiltinType::Overload: {
15381 // Try to resolve a single function template specialization.
15382 // This is obligatory.
15383 ExprResult Result = E;
15384 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15387 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15388 // leaves Result unchanged on failure.
15390 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15393 // If that failed, try to recover with a call.
15394 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15395 /*complain*/ true);
15399 // Bound member functions.
15400 case BuiltinType::BoundMember: {
15401 ExprResult result = E;
15402 const Expr *BME = E->IgnoreParens();
15403 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15404 // Try to give a nicer diagnostic if it is a bound member that we recognize.
15405 if (isa<CXXPseudoDestructorExpr>(BME)) {
15406 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15407 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15408 if (ME->getMemberNameInfo().getName().getNameKind() ==
15409 DeclarationName::CXXDestructorName)
15410 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15412 tryToRecoverWithCall(result, PD,
15413 /*complain*/ true);
15417 // ARC unbridged casts.
15418 case BuiltinType::ARCUnbridgedCast: {
15419 Expr *realCast = stripARCUnbridgedCast(E);
15420 diagnoseARCUnbridgedCast(realCast);
15424 // Expressions of unknown type.
15425 case BuiltinType::UnknownAny:
15426 return diagnoseUnknownAnyExpr(*this, E);
15429 case BuiltinType::PseudoObject:
15430 return checkPseudoObjectRValue(E);
15432 case BuiltinType::BuiltinFn: {
15433 // Accept __noop without parens by implicitly converting it to a call expr.
15434 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15436 auto *FD = cast<FunctionDecl>(DRE->getDecl());
15437 if (FD->getBuiltinID() == Builtin::BI__noop) {
15438 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15439 CK_BuiltinFnToFnPtr).get();
15440 return new (Context) CallExpr(Context, E, None, Context.IntTy,
15441 VK_RValue, SourceLocation());
15445 Diag(E->getLocStart(), diag::err_builtin_fn_use);
15446 return ExprError();
15449 // Expressions of unknown type.
15450 case BuiltinType::OMPArraySection:
15451 Diag(E->getLocStart(), diag::err_omp_array_section_use);
15452 return ExprError();
15454 // Everything else should be impossible.
15455 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15456 case BuiltinType::Id:
15457 #include "clang/Basic/OpenCLImageTypes.def"
15458 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15459 #define PLACEHOLDER_TYPE(Id, SingletonId)
15460 #include "clang/AST/BuiltinTypes.def"
15464 llvm_unreachable("invalid placeholder type!");
15467 bool Sema::CheckCaseExpression(Expr *E) {
15468 if (E->isTypeDependent())
15470 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15471 return E->getType()->isIntegralOrEnumerationType();
15475 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15477 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15478 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15479 "Unknown Objective-C Boolean value!");
15480 QualType BoolT = Context.ObjCBuiltinBoolTy;
15481 if (!Context.getBOOLDecl()) {
15482 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15483 Sema::LookupOrdinaryName);
15484 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15485 NamedDecl *ND = Result.getFoundDecl();
15486 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15487 Context.setBOOLDecl(TD);
15490 if (Context.getBOOLDecl())
15491 BoolT = Context.getBOOLType();
15492 return new (Context)
15493 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15496 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15497 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15498 SourceLocation RParen) {
15500 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15502 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15503 [&](const AvailabilitySpec &Spec) {
15504 return Spec.getPlatform() == Platform;
15507 VersionTuple Version;
15508 if (Spec != AvailSpecs.end())
15509 Version = Spec->getVersion();
15511 return new (Context)
15512 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);