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 if (II && II->isEditorPlaceholder()) {
2133 // FIXME: When typed placeholders are supported we can create a typed
2134 // placeholder expression node.
2138 // C++ [temp.dep.expr]p3:
2139 // An id-expression is type-dependent if it contains:
2140 // -- an identifier that was declared with a dependent type,
2141 // (note: handled after lookup)
2142 // -- a template-id that is dependent,
2143 // (note: handled in BuildTemplateIdExpr)
2144 // -- a conversion-function-id that specifies a dependent type,
2145 // -- a nested-name-specifier that contains a class-name that
2146 // names a dependent type.
2147 // Determine whether this is a member of an unknown specialization;
2148 // we need to handle these differently.
2149 bool DependentID = false;
2150 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2151 Name.getCXXNameType()->isDependentType()) {
2153 } else if (SS.isSet()) {
2154 if (DeclContext *DC = computeDeclContext(SS, false)) {
2155 if (RequireCompleteDeclContext(SS, DC))
2163 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2164 IsAddressOfOperand, TemplateArgs);
2166 // Perform the required lookup.
2167 LookupResult R(*this, NameInfo,
2168 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2169 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2171 // Lookup the template name again to correctly establish the context in
2172 // which it was found. This is really unfortunate as we already did the
2173 // lookup to determine that it was a template name in the first place. If
2174 // this becomes a performance hit, we can work harder to preserve those
2175 // results until we get here but it's likely not worth it.
2176 bool MemberOfUnknownSpecialization;
2177 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2178 MemberOfUnknownSpecialization);
2180 if (MemberOfUnknownSpecialization ||
2181 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2182 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2183 IsAddressOfOperand, TemplateArgs);
2185 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2186 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2188 // If the result might be in a dependent base class, this is a dependent
2190 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2191 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2192 IsAddressOfOperand, TemplateArgs);
2194 // If this reference is in an Objective-C method, then we need to do
2195 // some special Objective-C lookup, too.
2196 if (IvarLookupFollowUp) {
2197 ExprResult E(LookupInObjCMethod(R, S, II, true));
2201 if (Expr *Ex = E.getAs<Expr>())
2206 if (R.isAmbiguous())
2209 // This could be an implicitly declared function reference (legal in C90,
2210 // extension in C99, forbidden in C++).
2211 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2212 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2213 if (D) R.addDecl(D);
2216 // Determine whether this name might be a candidate for
2217 // argument-dependent lookup.
2218 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2220 if (R.empty() && !ADL) {
2221 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2222 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2223 TemplateKWLoc, TemplateArgs))
2227 // Don't diagnose an empty lookup for inline assembly.
2228 if (IsInlineAsmIdentifier)
2231 // If this name wasn't predeclared and if this is not a function
2232 // call, diagnose the problem.
2233 TypoExpr *TE = nullptr;
2234 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2235 II, SS.isValid() ? SS.getScopeRep() : nullptr);
2236 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2237 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2238 "Typo correction callback misconfigured");
2240 // Make sure the callback knows what the typo being diagnosed is.
2241 CCC->setTypoName(II);
2243 CCC->setTypoNNS(SS.getScopeRep());
2245 if (DiagnoseEmptyLookup(S, SS, R,
2246 CCC ? std::move(CCC) : std::move(DefaultValidator),
2247 nullptr, None, &TE)) {
2248 if (TE && KeywordReplacement) {
2249 auto &State = getTypoExprState(TE);
2250 auto BestTC = State.Consumer->getNextCorrection();
2251 if (BestTC.isKeyword()) {
2252 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2253 if (State.DiagHandler)
2254 State.DiagHandler(BestTC);
2255 KeywordReplacement->startToken();
2256 KeywordReplacement->setKind(II->getTokenID());
2257 KeywordReplacement->setIdentifierInfo(II);
2258 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2259 // Clean up the state associated with the TypoExpr, since it has
2260 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2261 clearDelayedTypo(TE);
2262 // Signal that a correction to a keyword was performed by returning a
2263 // valid-but-null ExprResult.
2264 return (Expr*)nullptr;
2266 State.Consumer->resetCorrectionStream();
2268 return TE ? TE : ExprError();
2271 assert(!R.empty() &&
2272 "DiagnoseEmptyLookup returned false but added no results");
2274 // If we found an Objective-C instance variable, let
2275 // LookupInObjCMethod build the appropriate expression to
2276 // reference the ivar.
2277 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2279 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2280 // In a hopelessly buggy code, Objective-C instance variable
2281 // lookup fails and no expression will be built to reference it.
2282 if (!E.isInvalid() && !E.get())
2288 // This is guaranteed from this point on.
2289 assert(!R.empty() || ADL);
2291 // Check whether this might be a C++ implicit instance member access.
2292 // C++ [class.mfct.non-static]p3:
2293 // When an id-expression that is not part of a class member access
2294 // syntax and not used to form a pointer to member is used in the
2295 // body of a non-static member function of class X, if name lookup
2296 // resolves the name in the id-expression to a non-static non-type
2297 // member of some class C, the id-expression is transformed into a
2298 // class member access expression using (*this) as the
2299 // postfix-expression to the left of the . operator.
2301 // But we don't actually need to do this for '&' operands if R
2302 // resolved to a function or overloaded function set, because the
2303 // expression is ill-formed if it actually works out to be a
2304 // non-static member function:
2306 // C++ [expr.ref]p4:
2307 // Otherwise, if E1.E2 refers to a non-static member function. . .
2308 // [t]he expression can be used only as the left-hand operand of a
2309 // member function call.
2311 // There are other safeguards against such uses, but it's important
2312 // to get this right here so that we don't end up making a
2313 // spuriously dependent expression if we're inside a dependent
2315 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2316 bool MightBeImplicitMember;
2317 if (!IsAddressOfOperand)
2318 MightBeImplicitMember = true;
2319 else if (!SS.isEmpty())
2320 MightBeImplicitMember = false;
2321 else if (R.isOverloadedResult())
2322 MightBeImplicitMember = false;
2323 else if (R.isUnresolvableResult())
2324 MightBeImplicitMember = true;
2326 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2327 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2328 isa<MSPropertyDecl>(R.getFoundDecl());
2330 if (MightBeImplicitMember)
2331 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2332 R, TemplateArgs, S);
2335 if (TemplateArgs || TemplateKWLoc.isValid()) {
2337 // In C++1y, if this is a variable template id, then check it
2338 // in BuildTemplateIdExpr().
2339 // The single lookup result must be a variable template declaration.
2340 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2341 Id.TemplateId->Kind == TNK_Var_template) {
2342 assert(R.getAsSingle<VarTemplateDecl>() &&
2343 "There should only be one declaration found.");
2346 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2349 return BuildDeclarationNameExpr(SS, R, ADL);
2352 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2353 /// declaration name, generally during template instantiation.
2354 /// There's a large number of things which don't need to be done along
2356 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2357 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2358 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2359 DeclContext *DC = computeDeclContext(SS, false);
2361 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2362 NameInfo, /*TemplateArgs=*/nullptr);
2364 if (RequireCompleteDeclContext(SS, DC))
2367 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2368 LookupQualifiedName(R, DC);
2370 if (R.isAmbiguous())
2373 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2374 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2375 NameInfo, /*TemplateArgs=*/nullptr);
2378 Diag(NameInfo.getLoc(), diag::err_no_member)
2379 << NameInfo.getName() << DC << SS.getRange();
2383 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2384 // Diagnose a missing typename if this resolved unambiguously to a type in
2385 // a dependent context. If we can recover with a type, downgrade this to
2386 // a warning in Microsoft compatibility mode.
2387 unsigned DiagID = diag::err_typename_missing;
2388 if (RecoveryTSI && getLangOpts().MSVCCompat)
2389 DiagID = diag::ext_typename_missing;
2390 SourceLocation Loc = SS.getBeginLoc();
2391 auto D = Diag(Loc, DiagID);
2392 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2393 << SourceRange(Loc, NameInfo.getEndLoc());
2395 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2400 // Only issue the fixit if we're prepared to recover.
2401 D << FixItHint::CreateInsertion(Loc, "typename ");
2403 // Recover by pretending this was an elaborated type.
2404 QualType Ty = Context.getTypeDeclType(TD);
2406 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2408 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2409 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2410 QTL.setElaboratedKeywordLoc(SourceLocation());
2411 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2413 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2418 // Defend against this resolving to an implicit member access. We usually
2419 // won't get here if this might be a legitimate a class member (we end up in
2420 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2421 // a pointer-to-member or in an unevaluated context in C++11.
2422 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2423 return BuildPossibleImplicitMemberExpr(SS,
2424 /*TemplateKWLoc=*/SourceLocation(),
2425 R, /*TemplateArgs=*/nullptr, S);
2427 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2430 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2431 /// detected that we're currently inside an ObjC method. Perform some
2432 /// additional lookup.
2434 /// Ideally, most of this would be done by lookup, but there's
2435 /// actually quite a lot of extra work involved.
2437 /// Returns a null sentinel to indicate trivial success.
2439 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2440 IdentifierInfo *II, bool AllowBuiltinCreation) {
2441 SourceLocation Loc = Lookup.getNameLoc();
2442 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2444 // Check for error condition which is already reported.
2448 // There are two cases to handle here. 1) scoped lookup could have failed,
2449 // in which case we should look for an ivar. 2) scoped lookup could have
2450 // found a decl, but that decl is outside the current instance method (i.e.
2451 // a global variable). In these two cases, we do a lookup for an ivar with
2452 // this name, if the lookup sucedes, we replace it our current decl.
2454 // If we're in a class method, we don't normally want to look for
2455 // ivars. But if we don't find anything else, and there's an
2456 // ivar, that's an error.
2457 bool IsClassMethod = CurMethod->isClassMethod();
2461 LookForIvars = true;
2462 else if (IsClassMethod)
2463 LookForIvars = false;
2465 LookForIvars = (Lookup.isSingleResult() &&
2466 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2467 ObjCInterfaceDecl *IFace = nullptr;
2469 IFace = CurMethod->getClassInterface();
2470 ObjCInterfaceDecl *ClassDeclared;
2471 ObjCIvarDecl *IV = nullptr;
2472 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2473 // Diagnose using an ivar in a class method.
2475 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2476 << IV->getDeclName());
2478 // If we're referencing an invalid decl, just return this as a silent
2479 // error node. The error diagnostic was already emitted on the decl.
2480 if (IV->isInvalidDecl())
2483 // Check if referencing a field with __attribute__((deprecated)).
2484 if (DiagnoseUseOfDecl(IV, Loc))
2487 // Diagnose the use of an ivar outside of the declaring class.
2488 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2489 !declaresSameEntity(ClassDeclared, IFace) &&
2490 !getLangOpts().DebuggerSupport)
2491 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2493 // FIXME: This should use a new expr for a direct reference, don't
2494 // turn this into Self->ivar, just return a BareIVarExpr or something.
2495 IdentifierInfo &II = Context.Idents.get("self");
2496 UnqualifiedId SelfName;
2497 SelfName.setIdentifier(&II, SourceLocation());
2498 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2499 CXXScopeSpec SelfScopeSpec;
2500 SourceLocation TemplateKWLoc;
2501 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2502 SelfName, false, false);
2503 if (SelfExpr.isInvalid())
2506 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2507 if (SelfExpr.isInvalid())
2510 MarkAnyDeclReferenced(Loc, IV, true);
2512 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2513 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2514 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2515 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2517 ObjCIvarRefExpr *Result = new (Context)
2518 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2519 IV->getLocation(), SelfExpr.get(), true, true);
2521 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2522 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2523 recordUseOfEvaluatedWeak(Result);
2525 if (getLangOpts().ObjCAutoRefCount) {
2526 if (CurContext->isClosure())
2527 Diag(Loc, diag::warn_implicitly_retains_self)
2528 << FixItHint::CreateInsertion(Loc, "self->");
2533 } else if (CurMethod->isInstanceMethod()) {
2534 // We should warn if a local variable hides an ivar.
2535 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2536 ObjCInterfaceDecl *ClassDeclared;
2537 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2538 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2539 declaresSameEntity(IFace, ClassDeclared))
2540 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2543 } else if (Lookup.isSingleResult() &&
2544 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2545 // If accessing a stand-alone ivar in a class method, this is an error.
2546 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2547 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2548 << IV->getDeclName());
2551 if (Lookup.empty() && II && AllowBuiltinCreation) {
2552 // FIXME. Consolidate this with similar code in LookupName.
2553 if (unsigned BuiltinID = II->getBuiltinID()) {
2554 if (!(getLangOpts().CPlusPlus &&
2555 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2556 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2557 S, Lookup.isForRedeclaration(),
2558 Lookup.getNameLoc());
2559 if (D) Lookup.addDecl(D);
2563 // Sentinel value saying that we didn't do anything special.
2564 return ExprResult((Expr *)nullptr);
2567 /// \brief Cast a base object to a member's actual type.
2569 /// Logically this happens in three phases:
2571 /// * First we cast from the base type to the naming class.
2572 /// The naming class is the class into which we were looking
2573 /// when we found the member; it's the qualifier type if a
2574 /// qualifier was provided, and otherwise it's the base type.
2576 /// * Next we cast from the naming class to the declaring class.
2577 /// If the member we found was brought into a class's scope by
2578 /// a using declaration, this is that class; otherwise it's
2579 /// the class declaring the member.
2581 /// * Finally we cast from the declaring class to the "true"
2582 /// declaring class of the member. This conversion does not
2583 /// obey access control.
2585 Sema::PerformObjectMemberConversion(Expr *From,
2586 NestedNameSpecifier *Qualifier,
2587 NamedDecl *FoundDecl,
2588 NamedDecl *Member) {
2589 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2593 QualType DestRecordType;
2595 QualType FromRecordType;
2596 QualType FromType = From->getType();
2597 bool PointerConversions = false;
2598 if (isa<FieldDecl>(Member)) {
2599 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2601 if (FromType->getAs<PointerType>()) {
2602 DestType = Context.getPointerType(DestRecordType);
2603 FromRecordType = FromType->getPointeeType();
2604 PointerConversions = true;
2606 DestType = DestRecordType;
2607 FromRecordType = FromType;
2609 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2610 if (Method->isStatic())
2613 DestType = Method->getThisType(Context);
2614 DestRecordType = DestType->getPointeeType();
2616 if (FromType->getAs<PointerType>()) {
2617 FromRecordType = FromType->getPointeeType();
2618 PointerConversions = true;
2620 FromRecordType = FromType;
2621 DestType = DestRecordType;
2624 // No conversion necessary.
2628 if (DestType->isDependentType() || FromType->isDependentType())
2631 // If the unqualified types are the same, no conversion is necessary.
2632 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2635 SourceRange FromRange = From->getSourceRange();
2636 SourceLocation FromLoc = FromRange.getBegin();
2638 ExprValueKind VK = From->getValueKind();
2640 // C++ [class.member.lookup]p8:
2641 // [...] Ambiguities can often be resolved by qualifying a name with its
2644 // If the member was a qualified name and the qualified referred to a
2645 // specific base subobject type, we'll cast to that intermediate type
2646 // first and then to the object in which the member is declared. That allows
2647 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2649 // class Base { public: int x; };
2650 // class Derived1 : public Base { };
2651 // class Derived2 : public Base { };
2652 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2654 // void VeryDerived::f() {
2655 // x = 17; // error: ambiguous base subobjects
2656 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2658 if (Qualifier && Qualifier->getAsType()) {
2659 QualType QType = QualType(Qualifier->getAsType(), 0);
2660 assert(QType->isRecordType() && "lookup done with non-record type");
2662 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2664 // In C++98, the qualifier type doesn't actually have to be a base
2665 // type of the object type, in which case we just ignore it.
2666 // Otherwise build the appropriate casts.
2667 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2668 CXXCastPath BasePath;
2669 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2670 FromLoc, FromRange, &BasePath))
2673 if (PointerConversions)
2674 QType = Context.getPointerType(QType);
2675 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2676 VK, &BasePath).get();
2679 FromRecordType = QRecordType;
2681 // If the qualifier type was the same as the destination type,
2683 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2688 bool IgnoreAccess = false;
2690 // If we actually found the member through a using declaration, cast
2691 // down to the using declaration's type.
2693 // Pointer equality is fine here because only one declaration of a
2694 // class ever has member declarations.
2695 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2696 assert(isa<UsingShadowDecl>(FoundDecl));
2697 QualType URecordType = Context.getTypeDeclType(
2698 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2700 // We only need to do this if the naming-class to declaring-class
2701 // conversion is non-trivial.
2702 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2703 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2704 CXXCastPath BasePath;
2705 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2706 FromLoc, FromRange, &BasePath))
2709 QualType UType = URecordType;
2710 if (PointerConversions)
2711 UType = Context.getPointerType(UType);
2712 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2713 VK, &BasePath).get();
2715 FromRecordType = URecordType;
2718 // We don't do access control for the conversion from the
2719 // declaring class to the true declaring class.
2720 IgnoreAccess = true;
2723 CXXCastPath BasePath;
2724 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2725 FromLoc, FromRange, &BasePath,
2729 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2733 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2734 const LookupResult &R,
2735 bool HasTrailingLParen) {
2736 // Only when used directly as the postfix-expression of a call.
2737 if (!HasTrailingLParen)
2740 // Never if a scope specifier was provided.
2744 // Only in C++ or ObjC++.
2745 if (!getLangOpts().CPlusPlus)
2748 // Turn off ADL when we find certain kinds of declarations during
2750 for (NamedDecl *D : R) {
2751 // C++0x [basic.lookup.argdep]p3:
2752 // -- a declaration of a class member
2753 // Since using decls preserve this property, we check this on the
2755 if (D->isCXXClassMember())
2758 // C++0x [basic.lookup.argdep]p3:
2759 // -- a block-scope function declaration that is not a
2760 // using-declaration
2761 // NOTE: we also trigger this for function templates (in fact, we
2762 // don't check the decl type at all, since all other decl types
2763 // turn off ADL anyway).
2764 if (isa<UsingShadowDecl>(D))
2765 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2766 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2769 // C++0x [basic.lookup.argdep]p3:
2770 // -- a declaration that is neither a function or a function
2772 // And also for builtin functions.
2773 if (isa<FunctionDecl>(D)) {
2774 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2776 // But also builtin functions.
2777 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2779 } else if (!isa<FunctionTemplateDecl>(D))
2787 /// Diagnoses obvious problems with the use of the given declaration
2788 /// as an expression. This is only actually called for lookups that
2789 /// were not overloaded, and it doesn't promise that the declaration
2790 /// will in fact be used.
2791 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2792 if (D->isInvalidDecl())
2795 if (isa<TypedefNameDecl>(D)) {
2796 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2800 if (isa<ObjCInterfaceDecl>(D)) {
2801 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2805 if (isa<NamespaceDecl>(D)) {
2806 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2813 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2814 LookupResult &R, bool NeedsADL,
2815 bool AcceptInvalidDecl) {
2816 // If this is a single, fully-resolved result and we don't need ADL,
2817 // just build an ordinary singleton decl ref.
2818 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2819 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2820 R.getRepresentativeDecl(), nullptr,
2823 // We only need to check the declaration if there's exactly one
2824 // result, because in the overloaded case the results can only be
2825 // functions and function templates.
2826 if (R.isSingleResult() &&
2827 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2830 // Otherwise, just build an unresolved lookup expression. Suppress
2831 // any lookup-related diagnostics; we'll hash these out later, when
2832 // we've picked a target.
2833 R.suppressDiagnostics();
2835 UnresolvedLookupExpr *ULE
2836 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2837 SS.getWithLocInContext(Context),
2838 R.getLookupNameInfo(),
2839 NeedsADL, R.isOverloadedResult(),
2840 R.begin(), R.end());
2846 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2847 ValueDecl *var, DeclContext *DC);
2849 /// \brief Complete semantic analysis for a reference to the given declaration.
2850 ExprResult Sema::BuildDeclarationNameExpr(
2851 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2852 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2853 bool AcceptInvalidDecl) {
2854 assert(D && "Cannot refer to a NULL declaration");
2855 assert(!isa<FunctionTemplateDecl>(D) &&
2856 "Cannot refer unambiguously to a function template");
2858 SourceLocation Loc = NameInfo.getLoc();
2859 if (CheckDeclInExpr(*this, Loc, D))
2862 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2863 // Specifically diagnose references to class templates that are missing
2864 // a template argument list.
2865 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2866 << Template << SS.getRange();
2867 Diag(Template->getLocation(), diag::note_template_decl_here);
2871 // Make sure that we're referring to a value.
2872 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2874 Diag(Loc, diag::err_ref_non_value)
2875 << D << SS.getRange();
2876 Diag(D->getLocation(), diag::note_declared_at);
2880 // Check whether this declaration can be used. Note that we suppress
2881 // this check when we're going to perform argument-dependent lookup
2882 // on this function name, because this might not be the function
2883 // that overload resolution actually selects.
2884 if (DiagnoseUseOfDecl(VD, Loc))
2887 // Only create DeclRefExpr's for valid Decl's.
2888 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2891 // Handle members of anonymous structs and unions. If we got here,
2892 // and the reference is to a class member indirect field, then this
2893 // must be the subject of a pointer-to-member expression.
2894 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2895 if (!indirectField->isCXXClassMember())
2896 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2900 QualType type = VD->getType();
2901 if (auto *FPT = type->getAs<FunctionProtoType>()) {
2902 // C++ [except.spec]p17:
2903 // An exception-specification is considered to be needed when:
2904 // - in an expression, the function is the unique lookup result or
2905 // the selected member of a set of overloaded functions.
2906 ResolveExceptionSpec(Loc, FPT);
2907 type = VD->getType();
2909 ExprValueKind valueKind = VK_RValue;
2911 switch (D->getKind()) {
2912 // Ignore all the non-ValueDecl kinds.
2913 #define ABSTRACT_DECL(kind)
2914 #define VALUE(type, base)
2915 #define DECL(type, base) \
2917 #include "clang/AST/DeclNodes.inc"
2918 llvm_unreachable("invalid value decl kind");
2920 // These shouldn't make it here.
2921 case Decl::ObjCAtDefsField:
2922 case Decl::ObjCIvar:
2923 llvm_unreachable("forming non-member reference to ivar?");
2925 // Enum constants are always r-values and never references.
2926 // Unresolved using declarations are dependent.
2927 case Decl::EnumConstant:
2928 case Decl::UnresolvedUsingValue:
2929 case Decl::OMPDeclareReduction:
2930 valueKind = VK_RValue;
2933 // Fields and indirect fields that got here must be for
2934 // pointer-to-member expressions; we just call them l-values for
2935 // internal consistency, because this subexpression doesn't really
2936 // exist in the high-level semantics.
2938 case Decl::IndirectField:
2939 assert(getLangOpts().CPlusPlus &&
2940 "building reference to field in C?");
2942 // These can't have reference type in well-formed programs, but
2943 // for internal consistency we do this anyway.
2944 type = type.getNonReferenceType();
2945 valueKind = VK_LValue;
2948 // Non-type template parameters are either l-values or r-values
2949 // depending on the type.
2950 case Decl::NonTypeTemplateParm: {
2951 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2952 type = reftype->getPointeeType();
2953 valueKind = VK_LValue; // even if the parameter is an r-value reference
2957 // For non-references, we need to strip qualifiers just in case
2958 // the template parameter was declared as 'const int' or whatever.
2959 valueKind = VK_RValue;
2960 type = type.getUnqualifiedType();
2965 case Decl::VarTemplateSpecialization:
2966 case Decl::VarTemplatePartialSpecialization:
2967 case Decl::Decomposition:
2968 case Decl::OMPCapturedExpr:
2969 // In C, "extern void blah;" is valid and is an r-value.
2970 if (!getLangOpts().CPlusPlus &&
2971 !type.hasQualifiers() &&
2972 type->isVoidType()) {
2973 valueKind = VK_RValue;
2978 case Decl::ImplicitParam:
2979 case Decl::ParmVar: {
2980 // These are always l-values.
2981 valueKind = VK_LValue;
2982 type = type.getNonReferenceType();
2984 // FIXME: Does the addition of const really only apply in
2985 // potentially-evaluated contexts? Since the variable isn't actually
2986 // captured in an unevaluated context, it seems that the answer is no.
2987 if (!isUnevaluatedContext()) {
2988 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2989 if (!CapturedType.isNull())
2990 type = CapturedType;
2996 case Decl::Binding: {
2997 // These are always lvalues.
2998 valueKind = VK_LValue;
2999 type = type.getNonReferenceType();
3000 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3001 // decides how that's supposed to work.
3002 auto *BD = cast<BindingDecl>(VD);
3003 if (BD->getDeclContext()->isFunctionOrMethod() &&
3004 BD->getDeclContext() != CurContext)
3005 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3009 case Decl::Function: {
3010 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3011 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3012 type = Context.BuiltinFnTy;
3013 valueKind = VK_RValue;
3018 const FunctionType *fty = type->castAs<FunctionType>();
3020 // If we're referring to a function with an __unknown_anytype
3021 // result type, make the entire expression __unknown_anytype.
3022 if (fty->getReturnType() == Context.UnknownAnyTy) {
3023 type = Context.UnknownAnyTy;
3024 valueKind = VK_RValue;
3028 // Functions are l-values in C++.
3029 if (getLangOpts().CPlusPlus) {
3030 valueKind = VK_LValue;
3034 // C99 DR 316 says that, if a function type comes from a
3035 // function definition (without a prototype), that type is only
3036 // used for checking compatibility. Therefore, when referencing
3037 // the function, we pretend that we don't have the full function
3039 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3040 isa<FunctionProtoType>(fty))
3041 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3044 // Functions are r-values in C.
3045 valueKind = VK_RValue;
3049 case Decl::CXXDeductionGuide:
3050 llvm_unreachable("building reference to deduction guide");
3052 case Decl::MSProperty:
3053 valueKind = VK_LValue;
3056 case Decl::CXXMethod:
3057 // If we're referring to a method with an __unknown_anytype
3058 // result type, make the entire expression __unknown_anytype.
3059 // This should only be possible with a type written directly.
3060 if (const FunctionProtoType *proto
3061 = dyn_cast<FunctionProtoType>(VD->getType()))
3062 if (proto->getReturnType() == Context.UnknownAnyTy) {
3063 type = Context.UnknownAnyTy;
3064 valueKind = VK_RValue;
3068 // C++ methods are l-values if static, r-values if non-static.
3069 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3070 valueKind = VK_LValue;
3075 case Decl::CXXConversion:
3076 case Decl::CXXDestructor:
3077 case Decl::CXXConstructor:
3078 valueKind = VK_RValue;
3082 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3087 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3088 SmallString<32> &Target) {
3089 Target.resize(CharByteWidth * (Source.size() + 1));
3090 char *ResultPtr = &Target[0];
3091 const llvm::UTF8 *ErrorPtr;
3093 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3096 Target.resize(ResultPtr - &Target[0]);
3099 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3100 PredefinedExpr::IdentType IT) {
3101 // Pick the current block, lambda, captured statement or function.
3102 Decl *currentDecl = nullptr;
3103 if (const BlockScopeInfo *BSI = getCurBlock())
3104 currentDecl = BSI->TheDecl;
3105 else if (const LambdaScopeInfo *LSI = getCurLambda())
3106 currentDecl = LSI->CallOperator;
3107 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3108 currentDecl = CSI->TheCapturedDecl;
3110 currentDecl = getCurFunctionOrMethodDecl();
3113 Diag(Loc, diag::ext_predef_outside_function);
3114 currentDecl = Context.getTranslationUnitDecl();
3118 StringLiteral *SL = nullptr;
3119 if (cast<DeclContext>(currentDecl)->isDependentContext())
3120 ResTy = Context.DependentTy;
3122 // Pre-defined identifiers are of type char[x], where x is the length of
3124 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3125 unsigned Length = Str.length();
3127 llvm::APInt LengthI(32, Length + 1);
3128 if (IT == PredefinedExpr::LFunction) {
3129 ResTy = Context.WideCharTy.withConst();
3130 SmallString<32> RawChars;
3131 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3133 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3134 /*IndexTypeQuals*/ 0);
3135 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3136 /*Pascal*/ false, ResTy, Loc);
3138 ResTy = Context.CharTy.withConst();
3139 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3140 /*IndexTypeQuals*/ 0);
3141 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3142 /*Pascal*/ false, ResTy, Loc);
3146 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3149 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3150 PredefinedExpr::IdentType IT;
3153 default: llvm_unreachable("Unknown simple primary expr!");
3154 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3155 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3156 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3157 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3158 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3159 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3162 return BuildPredefinedExpr(Loc, IT);
3165 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3166 SmallString<16> CharBuffer;
3167 bool Invalid = false;
3168 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3172 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3174 if (Literal.hadError())
3178 if (Literal.isWide())
3179 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3180 else if (Literal.isUTF16())
3181 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3182 else if (Literal.isUTF32())
3183 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3184 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3185 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3187 Ty = Context.CharTy; // 'x' -> char in C++
3189 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3190 if (Literal.isWide())
3191 Kind = CharacterLiteral::Wide;
3192 else if (Literal.isUTF16())
3193 Kind = CharacterLiteral::UTF16;
3194 else if (Literal.isUTF32())
3195 Kind = CharacterLiteral::UTF32;
3196 else if (Literal.isUTF8())
3197 Kind = CharacterLiteral::UTF8;
3199 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3202 if (Literal.getUDSuffix().empty())
3205 // We're building a user-defined literal.
3206 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3207 SourceLocation UDSuffixLoc =
3208 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3210 // Make sure we're allowed user-defined literals here.
3212 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3214 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3215 // operator "" X (ch)
3216 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3217 Lit, Tok.getLocation());
3220 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3221 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3222 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3223 Context.IntTy, Loc);
3226 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3227 QualType Ty, SourceLocation Loc) {
3228 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3230 using llvm::APFloat;
3231 APFloat Val(Format);
3233 APFloat::opStatus result = Literal.GetFloatValue(Val);
3235 // Overflow is always an error, but underflow is only an error if
3236 // we underflowed to zero (APFloat reports denormals as underflow).
3237 if ((result & APFloat::opOverflow) ||
3238 ((result & APFloat::opUnderflow) && Val.isZero())) {
3239 unsigned diagnostic;
3240 SmallString<20> buffer;
3241 if (result & APFloat::opOverflow) {
3242 diagnostic = diag::warn_float_overflow;
3243 APFloat::getLargest(Format).toString(buffer);
3245 diagnostic = diag::warn_float_underflow;
3246 APFloat::getSmallest(Format).toString(buffer);
3249 S.Diag(Loc, diagnostic)
3251 << StringRef(buffer.data(), buffer.size());
3254 bool isExact = (result == APFloat::opOK);
3255 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3258 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3259 assert(E && "Invalid expression");
3261 if (E->isValueDependent())
3264 QualType QT = E->getType();
3265 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3266 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3270 llvm::APSInt ValueAPS;
3271 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3276 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3277 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3278 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3279 << ValueAPS.toString(10) << ValueIsPositive;
3286 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3287 // Fast path for a single digit (which is quite common). A single digit
3288 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3289 if (Tok.getLength() == 1) {
3290 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3291 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3294 SmallString<128> SpellingBuffer;
3295 // NumericLiteralParser wants to overread by one character. Add padding to
3296 // the buffer in case the token is copied to the buffer. If getSpelling()
3297 // returns a StringRef to the memory buffer, it should have a null char at
3298 // the EOF, so it is also safe.
3299 SpellingBuffer.resize(Tok.getLength() + 1);
3301 // Get the spelling of the token, which eliminates trigraphs, etc.
3302 bool Invalid = false;
3303 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3307 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3308 if (Literal.hadError)
3311 if (Literal.hasUDSuffix()) {
3312 // We're building a user-defined literal.
3313 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3314 SourceLocation UDSuffixLoc =
3315 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3317 // Make sure we're allowed user-defined literals here.
3319 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3322 if (Literal.isFloatingLiteral()) {
3323 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3324 // long double, the literal is treated as a call of the form
3325 // operator "" X (f L)
3326 CookedTy = Context.LongDoubleTy;
3328 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3329 // unsigned long long, the literal is treated as a call of the form
3330 // operator "" X (n ULL)
3331 CookedTy = Context.UnsignedLongLongTy;
3334 DeclarationName OpName =
3335 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3336 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3337 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3339 SourceLocation TokLoc = Tok.getLocation();
3341 // Perform literal operator lookup to determine if we're building a raw
3342 // literal or a cooked one.
3343 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3344 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3345 /*AllowRaw*/true, /*AllowTemplate*/true,
3346 /*AllowStringTemplate*/false)) {
3352 if (Literal.isFloatingLiteral()) {
3353 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3355 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3356 if (Literal.GetIntegerValue(ResultVal))
3357 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3358 << /* Unsigned */ 1;
3359 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3362 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3366 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3367 // literal is treated as a call of the form
3368 // operator "" X ("n")
3369 unsigned Length = Literal.getUDSuffixOffset();
3370 QualType StrTy = Context.getConstantArrayType(
3371 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3372 ArrayType::Normal, 0);
3373 Expr *Lit = StringLiteral::Create(
3374 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3375 /*Pascal*/false, StrTy, &TokLoc, 1);
3376 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3379 case LOLR_Template: {
3380 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3381 // template), L is treated as a call fo the form
3382 // operator "" X <'c1', 'c2', ... 'ck'>()
3383 // where n is the source character sequence c1 c2 ... ck.
3384 TemplateArgumentListInfo ExplicitArgs;
3385 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3386 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3387 llvm::APSInt Value(CharBits, CharIsUnsigned);
3388 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3389 Value = TokSpelling[I];
3390 TemplateArgument Arg(Context, Value, Context.CharTy);
3391 TemplateArgumentLocInfo ArgInfo;
3392 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3394 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3397 case LOLR_StringTemplate:
3398 llvm_unreachable("unexpected literal operator lookup result");
3404 if (Literal.isFloatingLiteral()) {
3406 if (Literal.isHalf){
3407 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3408 Ty = Context.HalfTy;
3410 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3413 } else if (Literal.isFloat)
3414 Ty = Context.FloatTy;
3415 else if (Literal.isLong)
3416 Ty = Context.LongDoubleTy;
3417 else if (Literal.isFloat128)
3418 Ty = Context.Float128Ty;
3420 Ty = Context.DoubleTy;
3422 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3424 if (Ty == Context.DoubleTy) {
3425 if (getLangOpts().SinglePrecisionConstants) {
3426 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3427 if (BTy->getKind() != BuiltinType::Float) {
3428 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3430 } else if (getLangOpts().OpenCL &&
3431 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3432 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3433 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3434 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3437 } else if (!Literal.isIntegerLiteral()) {
3442 // 'long long' is a C99 or C++11 feature.
3443 if (!getLangOpts().C99 && Literal.isLongLong) {
3444 if (getLangOpts().CPlusPlus)
3445 Diag(Tok.getLocation(),
3446 getLangOpts().CPlusPlus11 ?
3447 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3449 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3452 // Get the value in the widest-possible width.
3453 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3454 llvm::APInt ResultVal(MaxWidth, 0);
3456 if (Literal.GetIntegerValue(ResultVal)) {
3457 // If this value didn't fit into uintmax_t, error and force to ull.
3458 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3459 << /* Unsigned */ 1;
3460 Ty = Context.UnsignedLongLongTy;
3461 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3462 "long long is not intmax_t?");
3464 // If this value fits into a ULL, try to figure out what else it fits into
3465 // according to the rules of C99 6.4.4.1p5.
3467 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3468 // be an unsigned int.
3469 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3471 // Check from smallest to largest, picking the smallest type we can.
3474 // Microsoft specific integer suffixes are explicitly sized.
3475 if (Literal.MicrosoftInteger) {
3476 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3478 Ty = Context.CharTy;
3480 Width = Literal.MicrosoftInteger;
3481 Ty = Context.getIntTypeForBitwidth(Width,
3482 /*Signed=*/!Literal.isUnsigned);
3486 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3487 // Are int/unsigned possibilities?
3488 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3490 // Does it fit in a unsigned int?
3491 if (ResultVal.isIntN(IntSize)) {
3492 // Does it fit in a signed int?
3493 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3495 else if (AllowUnsigned)
3496 Ty = Context.UnsignedIntTy;
3501 // Are long/unsigned long possibilities?
3502 if (Ty.isNull() && !Literal.isLongLong) {
3503 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3505 // Does it fit in a unsigned long?
3506 if (ResultVal.isIntN(LongSize)) {
3507 // Does it fit in a signed long?
3508 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3509 Ty = Context.LongTy;
3510 else if (AllowUnsigned)
3511 Ty = Context.UnsignedLongTy;
3512 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3514 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3515 const unsigned LongLongSize =
3516 Context.getTargetInfo().getLongLongWidth();
3517 Diag(Tok.getLocation(),
3518 getLangOpts().CPlusPlus
3520 ? diag::warn_old_implicitly_unsigned_long_cxx
3521 : /*C++98 UB*/ diag::
3522 ext_old_implicitly_unsigned_long_cxx
3523 : diag::warn_old_implicitly_unsigned_long)
3524 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3525 : /*will be ill-formed*/ 1);
3526 Ty = Context.UnsignedLongTy;
3532 // Check long long if needed.
3534 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3536 // Does it fit in a unsigned long long?
3537 if (ResultVal.isIntN(LongLongSize)) {
3538 // Does it fit in a signed long long?
3539 // To be compatible with MSVC, hex integer literals ending with the
3540 // LL or i64 suffix are always signed in Microsoft mode.
3541 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3542 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3543 Ty = Context.LongLongTy;
3544 else if (AllowUnsigned)
3545 Ty = Context.UnsignedLongLongTy;
3546 Width = LongLongSize;
3550 // If we still couldn't decide a type, we probably have something that
3551 // does not fit in a signed long long, but has no U suffix.
3553 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3554 Ty = Context.UnsignedLongLongTy;
3555 Width = Context.getTargetInfo().getLongLongWidth();
3558 if (ResultVal.getBitWidth() != Width)
3559 ResultVal = ResultVal.trunc(Width);
3561 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3564 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3565 if (Literal.isImaginary)
3566 Res = new (Context) ImaginaryLiteral(Res,
3567 Context.getComplexType(Res->getType()));
3572 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3573 assert(E && "ActOnParenExpr() missing expr");
3574 return new (Context) ParenExpr(L, R, E);
3577 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3579 SourceRange ArgRange) {
3580 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3581 // scalar or vector data type argument..."
3582 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3583 // type (C99 6.2.5p18) or void.
3584 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3585 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3590 assert((T->isVoidType() || !T->isIncompleteType()) &&
3591 "Scalar types should always be complete");
3595 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3597 SourceRange ArgRange,
3598 UnaryExprOrTypeTrait TraitKind) {
3599 // Invalid types must be hard errors for SFINAE in C++.
3600 if (S.LangOpts.CPlusPlus)
3604 if (T->isFunctionType() &&
3605 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3606 // sizeof(function)/alignof(function) is allowed as an extension.
3607 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3608 << TraitKind << ArgRange;
3612 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3613 // this is an error (OpenCL v1.1 s6.3.k)
3614 if (T->isVoidType()) {
3615 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3616 : diag::ext_sizeof_alignof_void_type;
3617 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3624 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3626 SourceRange ArgRange,
3627 UnaryExprOrTypeTrait TraitKind) {
3628 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3629 // runtime doesn't allow it.
3630 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3631 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3632 << T << (TraitKind == UETT_SizeOf)
3640 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3641 /// pointer type is equal to T) and emit a warning if it is.
3642 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3644 // Don't warn if the operation changed the type.
3645 if (T != E->getType())
3648 // Now look for array decays.
3649 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3650 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3653 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3655 << ICE->getSubExpr()->getType();
3658 /// \brief Check the constraints on expression operands to unary type expression
3659 /// and type traits.
3661 /// Completes any types necessary and validates the constraints on the operand
3662 /// expression. The logic mostly mirrors the type-based overload, but may modify
3663 /// the expression as it completes the type for that expression through template
3664 /// instantiation, etc.
3665 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3666 UnaryExprOrTypeTrait ExprKind) {
3667 QualType ExprTy = E->getType();
3668 assert(!ExprTy->isReferenceType());
3670 if (ExprKind == UETT_VecStep)
3671 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3672 E->getSourceRange());
3674 // Whitelist some types as extensions
3675 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3676 E->getSourceRange(), ExprKind))
3679 // 'alignof' applied to an expression only requires the base element type of
3680 // the expression to be complete. 'sizeof' requires the expression's type to
3681 // be complete (and will attempt to complete it if it's an array of unknown
3683 if (ExprKind == UETT_AlignOf) {
3684 if (RequireCompleteType(E->getExprLoc(),
3685 Context.getBaseElementType(E->getType()),
3686 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3687 E->getSourceRange()))
3690 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3691 ExprKind, E->getSourceRange()))
3695 // Completing the expression's type may have changed it.
3696 ExprTy = E->getType();
3697 assert(!ExprTy->isReferenceType());
3699 if (ExprTy->isFunctionType()) {
3700 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3701 << ExprKind << E->getSourceRange();
3705 // The operand for sizeof and alignof is in an unevaluated expression context,
3706 // so side effects could result in unintended consequences.
3707 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3708 !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3709 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3711 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3712 E->getSourceRange(), ExprKind))
3715 if (ExprKind == UETT_SizeOf) {
3716 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3717 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3718 QualType OType = PVD->getOriginalType();
3719 QualType Type = PVD->getType();
3720 if (Type->isPointerType() && OType->isArrayType()) {
3721 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3723 Diag(PVD->getLocation(), diag::note_declared_at);
3728 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3729 // decays into a pointer and returns an unintended result. This is most
3730 // likely a typo for "sizeof(array) op x".
3731 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3732 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3734 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3742 /// \brief Check the constraints on operands to unary expression and type
3745 /// This will complete any types necessary, and validate the various constraints
3746 /// on those operands.
3748 /// The UsualUnaryConversions() function is *not* called by this routine.
3749 /// C99 6.3.2.1p[2-4] all state:
3750 /// Except when it is the operand of the sizeof operator ...
3752 /// C++ [expr.sizeof]p4
3753 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3754 /// standard conversions are not applied to the operand of sizeof.
3756 /// This policy is followed for all of the unary trait expressions.
3757 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3758 SourceLocation OpLoc,
3759 SourceRange ExprRange,
3760 UnaryExprOrTypeTrait ExprKind) {
3761 if (ExprType->isDependentType())
3764 // C++ [expr.sizeof]p2:
3765 // When applied to a reference or a reference type, the result
3766 // is the size of the referenced type.
3767 // C++11 [expr.alignof]p3:
3768 // When alignof is applied to a reference type, the result
3769 // shall be the alignment of the referenced type.
3770 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3771 ExprType = Ref->getPointeeType();
3773 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3774 // When alignof or _Alignof is applied to an array type, the result
3775 // is the alignment of the element type.
3776 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3777 ExprType = Context.getBaseElementType(ExprType);
3779 if (ExprKind == UETT_VecStep)
3780 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3782 // Whitelist some types as extensions
3783 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3787 if (RequireCompleteType(OpLoc, ExprType,
3788 diag::err_sizeof_alignof_incomplete_type,
3789 ExprKind, ExprRange))
3792 if (ExprType->isFunctionType()) {
3793 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3794 << ExprKind << ExprRange;
3798 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3805 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3806 E = E->IgnoreParens();
3808 // Cannot know anything else if the expression is dependent.
3809 if (E->isTypeDependent())
3812 if (E->getObjectKind() == OK_BitField) {
3813 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3814 << 1 << E->getSourceRange();
3818 ValueDecl *D = nullptr;
3819 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3821 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3822 D = ME->getMemberDecl();
3825 // If it's a field, require the containing struct to have a
3826 // complete definition so that we can compute the layout.
3828 // This can happen in C++11 onwards, either by naming the member
3829 // in a way that is not transformed into a member access expression
3830 // (in an unevaluated operand, for instance), or by naming the member
3831 // in a trailing-return-type.
3833 // For the record, since __alignof__ on expressions is a GCC
3834 // extension, GCC seems to permit this but always gives the
3835 // nonsensical answer 0.
3837 // We don't really need the layout here --- we could instead just
3838 // directly check for all the appropriate alignment-lowing
3839 // attributes --- but that would require duplicating a lot of
3840 // logic that just isn't worth duplicating for such a marginal
3842 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3843 // Fast path this check, since we at least know the record has a
3844 // definition if we can find a member of it.
3845 if (!FD->getParent()->isCompleteDefinition()) {
3846 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3847 << E->getSourceRange();
3851 // Otherwise, if it's a field, and the field doesn't have
3852 // reference type, then it must have a complete type (or be a
3853 // flexible array member, which we explicitly want to
3854 // white-list anyway), which makes the following checks trivial.
3855 if (!FD->getType()->isReferenceType())
3859 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3862 bool Sema::CheckVecStepExpr(Expr *E) {
3863 E = E->IgnoreParens();
3865 // Cannot know anything else if the expression is dependent.
3866 if (E->isTypeDependent())
3869 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3872 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3873 CapturingScopeInfo *CSI) {
3874 assert(T->isVariablyModifiedType());
3875 assert(CSI != nullptr);
3877 // We're going to walk down into the type and look for VLA expressions.
3879 const Type *Ty = T.getTypePtr();
3880 switch (Ty->getTypeClass()) {
3881 #define TYPE(Class, Base)
3882 #define ABSTRACT_TYPE(Class, Base)
3883 #define NON_CANONICAL_TYPE(Class, Base)
3884 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3885 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3886 #include "clang/AST/TypeNodes.def"
3889 // These types are never variably-modified.
3893 case Type::ExtVector:
3896 case Type::Elaborated:
3897 case Type::TemplateSpecialization:
3898 case Type::ObjCObject:
3899 case Type::ObjCInterface:
3900 case Type::ObjCObjectPointer:
3901 case Type::ObjCTypeParam:
3903 llvm_unreachable("type class is never variably-modified!");
3904 case Type::Adjusted:
3905 T = cast<AdjustedType>(Ty)->getOriginalType();
3908 T = cast<DecayedType>(Ty)->getPointeeType();
3911 T = cast<PointerType>(Ty)->getPointeeType();
3913 case Type::BlockPointer:
3914 T = cast<BlockPointerType>(Ty)->getPointeeType();
3916 case Type::LValueReference:
3917 case Type::RValueReference:
3918 T = cast<ReferenceType>(Ty)->getPointeeType();
3920 case Type::MemberPointer:
3921 T = cast<MemberPointerType>(Ty)->getPointeeType();
3923 case Type::ConstantArray:
3924 case Type::IncompleteArray:
3925 // Losing element qualification here is fine.
3926 T = cast<ArrayType>(Ty)->getElementType();
3928 case Type::VariableArray: {
3929 // Losing element qualification here is fine.
3930 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3932 // Unknown size indication requires no size computation.
3933 // Otherwise, evaluate and record it.
3934 if (auto Size = VAT->getSizeExpr()) {
3935 if (!CSI->isVLATypeCaptured(VAT)) {
3936 RecordDecl *CapRecord = nullptr;
3937 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3938 CapRecord = LSI->Lambda;
3939 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3940 CapRecord = CRSI->TheRecordDecl;
3943 auto ExprLoc = Size->getExprLoc();
3944 auto SizeType = Context.getSizeType();
3945 // Build the non-static data member.
3947 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3948 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3949 /*BW*/ nullptr, /*Mutable*/ false,
3950 /*InitStyle*/ ICIS_NoInit);
3951 Field->setImplicit(true);
3952 Field->setAccess(AS_private);
3953 Field->setCapturedVLAType(VAT);
3954 CapRecord->addDecl(Field);
3956 CSI->addVLATypeCapture(ExprLoc, SizeType);
3960 T = VAT->getElementType();
3963 case Type::FunctionProto:
3964 case Type::FunctionNoProto:
3965 T = cast<FunctionType>(Ty)->getReturnType();
3969 case Type::UnaryTransform:
3970 case Type::Attributed:
3971 case Type::SubstTemplateTypeParm:
3972 case Type::PackExpansion:
3973 // Keep walking after single level desugaring.
3974 T = T.getSingleStepDesugaredType(Context);
3977 T = cast<TypedefType>(Ty)->desugar();
3979 case Type::Decltype:
3980 T = cast<DecltypeType>(Ty)->desugar();
3983 case Type::DeducedTemplateSpecialization:
3984 T = cast<DeducedType>(Ty)->getDeducedType();
3986 case Type::TypeOfExpr:
3987 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3990 T = cast<AtomicType>(Ty)->getValueType();
3993 } while (!T.isNull() && T->isVariablyModifiedType());
3996 /// \brief Build a sizeof or alignof expression given a type operand.
3998 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3999 SourceLocation OpLoc,
4000 UnaryExprOrTypeTrait ExprKind,
4005 QualType T = TInfo->getType();
4007 if (!T->isDependentType() &&
4008 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4011 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4012 if (auto *TT = T->getAs<TypedefType>()) {
4013 for (auto I = FunctionScopes.rbegin(),
4014 E = std::prev(FunctionScopes.rend());
4016 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4019 DeclContext *DC = nullptr;
4020 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4021 DC = LSI->CallOperator;
4022 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4023 DC = CRSI->TheCapturedDecl;
4024 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4027 if (DC->containsDecl(TT->getDecl()))
4029 captureVariablyModifiedType(Context, T, CSI);
4035 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4036 return new (Context) UnaryExprOrTypeTraitExpr(
4037 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4040 /// \brief Build a sizeof or alignof expression given an expression
4043 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4044 UnaryExprOrTypeTrait ExprKind) {
4045 ExprResult PE = CheckPlaceholderExpr(E);
4051 // Verify that the operand is valid.
4052 bool isInvalid = false;
4053 if (E->isTypeDependent()) {
4054 // Delay type-checking for type-dependent expressions.
4055 } else if (ExprKind == UETT_AlignOf) {
4056 isInvalid = CheckAlignOfExpr(*this, E);
4057 } else if (ExprKind == UETT_VecStep) {
4058 isInvalid = CheckVecStepExpr(E);
4059 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4060 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4062 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4063 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4066 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4072 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4073 PE = TransformToPotentiallyEvaluated(E);
4074 if (PE.isInvalid()) return ExprError();
4078 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4079 return new (Context) UnaryExprOrTypeTraitExpr(
4080 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4083 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4084 /// expr and the same for @c alignof and @c __alignof
4085 /// Note that the ArgRange is invalid if isType is false.
4087 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4088 UnaryExprOrTypeTrait ExprKind, bool IsType,
4089 void *TyOrEx, SourceRange ArgRange) {
4090 // If error parsing type, ignore.
4091 if (!TyOrEx) return ExprError();
4094 TypeSourceInfo *TInfo;
4095 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4096 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4099 Expr *ArgEx = (Expr *)TyOrEx;
4100 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4104 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4106 if (V.get()->isTypeDependent())
4107 return S.Context.DependentTy;
4109 // _Real and _Imag are only l-values for normal l-values.
4110 if (V.get()->getObjectKind() != OK_Ordinary) {
4111 V = S.DefaultLvalueConversion(V.get());
4116 // These operators return the element type of a complex type.
4117 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4118 return CT->getElementType();
4120 // Otherwise they pass through real integer and floating point types here.
4121 if (V.get()->getType()->isArithmeticType())
4122 return V.get()->getType();
4124 // Test for placeholders.
4125 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4126 if (PR.isInvalid()) return QualType();
4127 if (PR.get() != V.get()) {
4129 return CheckRealImagOperand(S, V, Loc, IsReal);
4132 // Reject anything else.
4133 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4134 << (IsReal ? "__real" : "__imag");
4141 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4142 tok::TokenKind Kind, Expr *Input) {
4143 UnaryOperatorKind Opc;
4145 default: llvm_unreachable("Unknown unary op!");
4146 case tok::plusplus: Opc = UO_PostInc; break;
4147 case tok::minusminus: Opc = UO_PostDec; break;
4150 // Since this might is a postfix expression, get rid of ParenListExprs.
4151 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4152 if (Result.isInvalid()) return ExprError();
4153 Input = Result.get();
4155 return BuildUnaryOp(S, OpLoc, Opc, Input);
4158 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4160 /// \return true on error
4161 static bool checkArithmeticOnObjCPointer(Sema &S,
4162 SourceLocation opLoc,
4164 assert(op->getType()->isObjCObjectPointerType());
4165 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4166 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4169 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4170 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4171 << op->getSourceRange();
4175 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4176 auto *BaseNoParens = Base->IgnoreParens();
4177 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4178 return MSProp->getPropertyDecl()->getType()->isArrayType();
4179 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4183 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4184 Expr *idx, SourceLocation rbLoc) {
4185 if (base && !base->getType().isNull() &&
4186 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4187 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4188 /*Length=*/nullptr, rbLoc);
4190 // Since this might be a postfix expression, get rid of ParenListExprs.
4191 if (isa<ParenListExpr>(base)) {
4192 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4193 if (result.isInvalid()) return ExprError();
4194 base = result.get();
4197 // Handle any non-overload placeholder types in the base and index
4198 // expressions. We can't handle overloads here because the other
4199 // operand might be an overloadable type, in which case the overload
4200 // resolution for the operator overload should get the first crack
4202 bool IsMSPropertySubscript = false;
4203 if (base->getType()->isNonOverloadPlaceholderType()) {
4204 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4205 if (!IsMSPropertySubscript) {
4206 ExprResult result = CheckPlaceholderExpr(base);
4207 if (result.isInvalid())
4209 base = result.get();
4212 if (idx->getType()->isNonOverloadPlaceholderType()) {
4213 ExprResult result = CheckPlaceholderExpr(idx);
4214 if (result.isInvalid()) return ExprError();
4218 // Build an unanalyzed expression if either operand is type-dependent.
4219 if (getLangOpts().CPlusPlus &&
4220 (base->isTypeDependent() || idx->isTypeDependent())) {
4221 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4222 VK_LValue, OK_Ordinary, rbLoc);
4225 // MSDN, property (C++)
4226 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4227 // This attribute can also be used in the declaration of an empty array in a
4228 // class or structure definition. For example:
4229 // __declspec(property(get=GetX, put=PutX)) int x[];
4230 // The above statement indicates that x[] can be used with one or more array
4231 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4232 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4233 if (IsMSPropertySubscript) {
4234 // Build MS property subscript expression if base is MS property reference
4235 // or MS property subscript.
4236 return new (Context) MSPropertySubscriptExpr(
4237 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4240 // Use C++ overloaded-operator rules if either operand has record
4241 // type. The spec says to do this if either type is *overloadable*,
4242 // but enum types can't declare subscript operators or conversion
4243 // operators, so there's nothing interesting for overload resolution
4244 // to do if there aren't any record types involved.
4246 // ObjC pointers have their own subscripting logic that is not tied
4247 // to overload resolution and so should not take this path.
4248 if (getLangOpts().CPlusPlus &&
4249 (base->getType()->isRecordType() ||
4250 (!base->getType()->isObjCObjectPointerType() &&
4251 idx->getType()->isRecordType()))) {
4252 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4255 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4258 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4260 SourceLocation ColonLoc, Expr *Length,
4261 SourceLocation RBLoc) {
4262 if (Base->getType()->isPlaceholderType() &&
4263 !Base->getType()->isSpecificPlaceholderType(
4264 BuiltinType::OMPArraySection)) {
4265 ExprResult Result = CheckPlaceholderExpr(Base);
4266 if (Result.isInvalid())
4268 Base = Result.get();
4270 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4271 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4272 if (Result.isInvalid())
4274 Result = DefaultLvalueConversion(Result.get());
4275 if (Result.isInvalid())
4277 LowerBound = Result.get();
4279 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4280 ExprResult Result = CheckPlaceholderExpr(Length);
4281 if (Result.isInvalid())
4283 Result = DefaultLvalueConversion(Result.get());
4284 if (Result.isInvalid())
4286 Length = Result.get();
4289 // Build an unanalyzed expression if either operand is type-dependent.
4290 if (Base->isTypeDependent() ||
4292 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4293 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4294 return new (Context)
4295 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4296 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4299 // Perform default conversions.
4300 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4302 if (OriginalTy->isAnyPointerType()) {
4303 ResultTy = OriginalTy->getPointeeType();
4304 } else if (OriginalTy->isArrayType()) {
4305 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4308 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4309 << Base->getSourceRange());
4313 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4315 if (Res.isInvalid())
4316 return ExprError(Diag(LowerBound->getExprLoc(),
4317 diag::err_omp_typecheck_section_not_integer)
4318 << 0 << LowerBound->getSourceRange());
4319 LowerBound = Res.get();
4321 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4322 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4323 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4324 << 0 << LowerBound->getSourceRange();
4328 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4329 if (Res.isInvalid())
4330 return ExprError(Diag(Length->getExprLoc(),
4331 diag::err_omp_typecheck_section_not_integer)
4332 << 1 << Length->getSourceRange());
4335 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4336 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4337 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4338 << 1 << Length->getSourceRange();
4341 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4342 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4343 // type. Note that functions are not objects, and that (in C99 parlance)
4344 // incomplete types are not object types.
4345 if (ResultTy->isFunctionType()) {
4346 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4347 << ResultTy << Base->getSourceRange();
4351 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4352 diag::err_omp_section_incomplete_type, Base))
4355 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4356 llvm::APSInt LowerBoundValue;
4357 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4358 // OpenMP 4.5, [2.4 Array Sections]
4359 // The array section must be a subset of the original array.
4360 if (LowerBoundValue.isNegative()) {
4361 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4362 << LowerBound->getSourceRange();
4369 llvm::APSInt LengthValue;
4370 if (Length->EvaluateAsInt(LengthValue, Context)) {
4371 // OpenMP 4.5, [2.4 Array Sections]
4372 // The length must evaluate to non-negative integers.
4373 if (LengthValue.isNegative()) {
4374 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4375 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4376 << Length->getSourceRange();
4380 } else if (ColonLoc.isValid() &&
4381 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4382 !OriginalTy->isVariableArrayType()))) {
4383 // OpenMP 4.5, [2.4 Array Sections]
4384 // When the size of the array dimension is not known, the length must be
4385 // specified explicitly.
4386 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4387 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4391 if (!Base->getType()->isSpecificPlaceholderType(
4392 BuiltinType::OMPArraySection)) {
4393 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4394 if (Result.isInvalid())
4396 Base = Result.get();
4398 return new (Context)
4399 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4400 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4404 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4405 Expr *Idx, SourceLocation RLoc) {
4406 Expr *LHSExp = Base;
4409 ExprValueKind VK = VK_LValue;
4410 ExprObjectKind OK = OK_Ordinary;
4412 // Per C++ core issue 1213, the result is an xvalue if either operand is
4413 // a non-lvalue array, and an lvalue otherwise.
4414 if (getLangOpts().CPlusPlus11 &&
4415 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4416 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4419 // Perform default conversions.
4420 if (!LHSExp->getType()->getAs<VectorType>()) {
4421 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4422 if (Result.isInvalid())
4424 LHSExp = Result.get();
4426 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4427 if (Result.isInvalid())
4429 RHSExp = Result.get();
4431 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4433 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4434 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4435 // in the subscript position. As a result, we need to derive the array base
4436 // and index from the expression types.
4437 Expr *BaseExpr, *IndexExpr;
4438 QualType ResultType;
4439 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4442 ResultType = Context.DependentTy;
4443 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4446 ResultType = PTy->getPointeeType();
4447 } else if (const ObjCObjectPointerType *PTy =
4448 LHSTy->getAs<ObjCObjectPointerType>()) {
4452 // Use custom logic if this should be the pseudo-object subscript
4454 if (!LangOpts.isSubscriptPointerArithmetic())
4455 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4458 ResultType = PTy->getPointeeType();
4459 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4460 // Handle the uncommon case of "123[Ptr]".
4463 ResultType = PTy->getPointeeType();
4464 } else if (const ObjCObjectPointerType *PTy =
4465 RHSTy->getAs<ObjCObjectPointerType>()) {
4466 // Handle the uncommon case of "123[Ptr]".
4469 ResultType = PTy->getPointeeType();
4470 if (!LangOpts.isSubscriptPointerArithmetic()) {
4471 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4472 << ResultType << BaseExpr->getSourceRange();
4475 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4476 BaseExpr = LHSExp; // vectors: V[123]
4478 VK = LHSExp->getValueKind();
4479 if (VK != VK_RValue)
4480 OK = OK_VectorComponent;
4482 // FIXME: need to deal with const...
4483 ResultType = VTy->getElementType();
4484 } else if (LHSTy->isArrayType()) {
4485 // If we see an array that wasn't promoted by
4486 // DefaultFunctionArrayLvalueConversion, it must be an array that
4487 // wasn't promoted because of the C90 rule that doesn't
4488 // allow promoting non-lvalue arrays. Warn, then
4489 // force the promotion here.
4490 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4491 LHSExp->getSourceRange();
4492 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4493 CK_ArrayToPointerDecay).get();
4494 LHSTy = LHSExp->getType();
4498 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4499 } else if (RHSTy->isArrayType()) {
4500 // Same as previous, except for 123[f().a] case
4501 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4502 RHSExp->getSourceRange();
4503 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4504 CK_ArrayToPointerDecay).get();
4505 RHSTy = RHSExp->getType();
4509 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4511 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4512 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4515 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4516 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4517 << IndexExpr->getSourceRange());
4519 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4520 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4521 && !IndexExpr->isTypeDependent())
4522 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4524 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4525 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4526 // type. Note that Functions are not objects, and that (in C99 parlance)
4527 // incomplete types are not object types.
4528 if (ResultType->isFunctionType()) {
4529 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4530 << ResultType << BaseExpr->getSourceRange();
4534 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4535 // GNU extension: subscripting on pointer to void
4536 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4537 << BaseExpr->getSourceRange();
4539 // C forbids expressions of unqualified void type from being l-values.
4540 // See IsCForbiddenLValueType.
4541 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4542 } else if (!ResultType->isDependentType() &&
4543 RequireCompleteType(LLoc, ResultType,
4544 diag::err_subscript_incomplete_type, BaseExpr))
4547 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4548 !ResultType.isCForbiddenLValueType());
4550 return new (Context)
4551 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4554 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4555 ParmVarDecl *Param) {
4556 if (Param->hasUnparsedDefaultArg()) {
4558 diag::err_use_of_default_argument_to_function_declared_later) <<
4559 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4560 Diag(UnparsedDefaultArgLocs[Param],
4561 diag::note_default_argument_declared_here);
4565 if (Param->hasUninstantiatedDefaultArg()) {
4566 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4568 EnterExpressionEvaluationContext EvalContext(
4569 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4571 // Instantiate the expression.
4572 MultiLevelTemplateArgumentList MutiLevelArgList
4573 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4575 InstantiatingTemplate Inst(*this, CallLoc, Param,
4576 MutiLevelArgList.getInnermost());
4577 if (Inst.isInvalid())
4579 if (Inst.isAlreadyInstantiating()) {
4580 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4581 Param->setInvalidDecl();
4587 // C++ [dcl.fct.default]p5:
4588 // The names in the [default argument] expression are bound, and
4589 // the semantic constraints are checked, at the point where the
4590 // default argument expression appears.
4591 ContextRAII SavedContext(*this, FD);
4592 LocalInstantiationScope Local(*this);
4593 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4594 /*DirectInit*/false);
4596 if (Result.isInvalid())
4599 // Check the expression as an initializer for the parameter.
4600 InitializedEntity Entity
4601 = InitializedEntity::InitializeParameter(Context, Param);
4602 InitializationKind Kind
4603 = InitializationKind::CreateCopy(Param->getLocation(),
4604 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4605 Expr *ResultE = Result.getAs<Expr>();
4607 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4608 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4609 if (Result.isInvalid())
4612 Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4613 Param->getOuterLocStart());
4614 if (Result.isInvalid())
4617 // Remember the instantiated default argument.
4618 Param->setDefaultArg(Result.getAs<Expr>());
4619 if (ASTMutationListener *L = getASTMutationListener()) {
4620 L->DefaultArgumentInstantiated(Param);
4624 // If the default argument expression is not set yet, we are building it now.
4625 if (!Param->hasInit()) {
4626 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4627 Param->setInvalidDecl();
4631 // If the default expression creates temporaries, we need to
4632 // push them to the current stack of expression temporaries so they'll
4633 // be properly destroyed.
4634 // FIXME: We should really be rebuilding the default argument with new
4635 // bound temporaries; see the comment in PR5810.
4636 // We don't need to do that with block decls, though, because
4637 // blocks in default argument expression can never capture anything.
4638 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4639 // Set the "needs cleanups" bit regardless of whether there are
4640 // any explicit objects.
4641 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4643 // Append all the objects to the cleanup list. Right now, this
4644 // should always be a no-op, because blocks in default argument
4645 // expressions should never be able to capture anything.
4646 assert(!Init->getNumObjects() &&
4647 "default argument expression has capturing blocks?");
4650 // We already type-checked the argument, so we know it works.
4651 // Just mark all of the declarations in this potentially-evaluated expression
4652 // as being "referenced".
4653 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4654 /*SkipLocalVariables=*/true);
4658 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4659 FunctionDecl *FD, ParmVarDecl *Param) {
4660 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4662 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4665 Sema::VariadicCallType
4666 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4668 if (Proto && Proto->isVariadic()) {
4669 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4670 return VariadicConstructor;
4671 else if (Fn && Fn->getType()->isBlockPointerType())
4672 return VariadicBlock;
4674 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4675 if (Method->isInstance())
4676 return VariadicMethod;
4677 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4678 return VariadicMethod;
4679 return VariadicFunction;
4681 return VariadicDoesNotApply;
4685 class FunctionCallCCC : public FunctionCallFilterCCC {
4687 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4688 unsigned NumArgs, MemberExpr *ME)
4689 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4690 FunctionName(FuncName) {}
4692 bool ValidateCandidate(const TypoCorrection &candidate) override {
4693 if (!candidate.getCorrectionSpecifier() ||
4694 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4698 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4702 const IdentifierInfo *const FunctionName;
4706 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4707 FunctionDecl *FDecl,
4708 ArrayRef<Expr *> Args) {
4709 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4710 DeclarationName FuncName = FDecl->getDeclName();
4711 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4713 if (TypoCorrection Corrected = S.CorrectTypo(
4714 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4715 S.getScopeForContext(S.CurContext), nullptr,
4716 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4718 Sema::CTK_ErrorRecovery)) {
4719 if (NamedDecl *ND = Corrected.getFoundDecl()) {
4720 if (Corrected.isOverloaded()) {
4721 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4722 OverloadCandidateSet::iterator Best;
4723 for (NamedDecl *CD : Corrected) {
4724 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4725 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4728 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4730 ND = Best->FoundDecl;
4731 Corrected.setCorrectionDecl(ND);
4737 ND = ND->getUnderlyingDecl();
4738 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4742 return TypoCorrection();
4745 /// ConvertArgumentsForCall - Converts the arguments specified in
4746 /// Args/NumArgs to the parameter types of the function FDecl with
4747 /// function prototype Proto. Call is the call expression itself, and
4748 /// Fn is the function expression. For a C++ member function, this
4749 /// routine does not attempt to convert the object argument. Returns
4750 /// true if the call is ill-formed.
4752 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4753 FunctionDecl *FDecl,
4754 const FunctionProtoType *Proto,
4755 ArrayRef<Expr *> Args,
4756 SourceLocation RParenLoc,
4757 bool IsExecConfig) {
4758 // Bail out early if calling a builtin with custom typechecking.
4760 if (unsigned ID = FDecl->getBuiltinID())
4761 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4764 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4765 // assignment, to the types of the corresponding parameter, ...
4766 unsigned NumParams = Proto->getNumParams();
4767 bool Invalid = false;
4768 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4769 unsigned FnKind = Fn->getType()->isBlockPointerType()
4771 : (IsExecConfig ? 3 /* kernel function (exec config) */
4772 : 0 /* function */);
4774 // If too few arguments are available (and we don't have default
4775 // arguments for the remaining parameters), don't make the call.
4776 if (Args.size() < NumParams) {
4777 if (Args.size() < MinArgs) {
4779 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4781 MinArgs == NumParams && !Proto->isVariadic()
4782 ? diag::err_typecheck_call_too_few_args_suggest
4783 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4784 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4785 << static_cast<unsigned>(Args.size())
4786 << TC.getCorrectionRange());
4787 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4789 MinArgs == NumParams && !Proto->isVariadic()
4790 ? diag::err_typecheck_call_too_few_args_one
4791 : diag::err_typecheck_call_too_few_args_at_least_one)
4792 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4794 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4795 ? diag::err_typecheck_call_too_few_args
4796 : diag::err_typecheck_call_too_few_args_at_least)
4797 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4798 << Fn->getSourceRange();
4800 // Emit the location of the prototype.
4801 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4802 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4807 Call->setNumArgs(Context, NumParams);
4810 // If too many are passed and not variadic, error on the extras and drop
4812 if (Args.size() > NumParams) {
4813 if (!Proto->isVariadic()) {
4815 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4817 MinArgs == NumParams && !Proto->isVariadic()
4818 ? diag::err_typecheck_call_too_many_args_suggest
4819 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4820 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4821 << static_cast<unsigned>(Args.size())
4822 << TC.getCorrectionRange());
4823 } else if (NumParams == 1 && FDecl &&
4824 FDecl->getParamDecl(0)->getDeclName())
4825 Diag(Args[NumParams]->getLocStart(),
4826 MinArgs == NumParams
4827 ? diag::err_typecheck_call_too_many_args_one
4828 : diag::err_typecheck_call_too_many_args_at_most_one)
4829 << FnKind << FDecl->getParamDecl(0)
4830 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4831 << SourceRange(Args[NumParams]->getLocStart(),
4832 Args.back()->getLocEnd());
4834 Diag(Args[NumParams]->getLocStart(),
4835 MinArgs == NumParams
4836 ? diag::err_typecheck_call_too_many_args
4837 : diag::err_typecheck_call_too_many_args_at_most)
4838 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4839 << Fn->getSourceRange()
4840 << SourceRange(Args[NumParams]->getLocStart(),
4841 Args.back()->getLocEnd());
4843 // Emit the location of the prototype.
4844 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4845 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4848 // This deletes the extra arguments.
4849 Call->setNumArgs(Context, NumParams);
4853 SmallVector<Expr *, 8> AllArgs;
4854 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4856 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4857 Proto, 0, Args, AllArgs, CallType);
4860 unsigned TotalNumArgs = AllArgs.size();
4861 for (unsigned i = 0; i < TotalNumArgs; ++i)
4862 Call->setArg(i, AllArgs[i]);
4867 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4868 const FunctionProtoType *Proto,
4869 unsigned FirstParam, ArrayRef<Expr *> Args,
4870 SmallVectorImpl<Expr *> &AllArgs,
4871 VariadicCallType CallType, bool AllowExplicit,
4872 bool IsListInitialization) {
4873 unsigned NumParams = Proto->getNumParams();
4874 bool Invalid = false;
4876 // Continue to check argument types (even if we have too few/many args).
4877 for (unsigned i = FirstParam; i < NumParams; i++) {
4878 QualType ProtoArgType = Proto->getParamType(i);
4881 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4882 if (ArgIx < Args.size()) {
4883 Arg = Args[ArgIx++];
4885 if (RequireCompleteType(Arg->getLocStart(),
4887 diag::err_call_incomplete_argument, Arg))
4890 // Strip the unbridged-cast placeholder expression off, if applicable.
4891 bool CFAudited = false;
4892 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4893 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4894 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4895 Arg = stripARCUnbridgedCast(Arg);
4896 else if (getLangOpts().ObjCAutoRefCount &&
4897 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4898 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4901 InitializedEntity Entity =
4902 Param ? InitializedEntity::InitializeParameter(Context, Param,
4904 : InitializedEntity::InitializeParameter(
4905 Context, ProtoArgType, Proto->isParamConsumed(i));
4907 // Remember that parameter belongs to a CF audited API.
4909 Entity.setParameterCFAudited();
4911 ExprResult ArgE = PerformCopyInitialization(
4912 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4913 if (ArgE.isInvalid())
4916 Arg = ArgE.getAs<Expr>();
4918 assert(Param && "can't use default arguments without a known callee");
4920 ExprResult ArgExpr =
4921 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4922 if (ArgExpr.isInvalid())
4925 Arg = ArgExpr.getAs<Expr>();
4928 // Check for array bounds violations for each argument to the call. This
4929 // check only triggers warnings when the argument isn't a more complex Expr
4930 // with its own checking, such as a BinaryOperator.
4931 CheckArrayAccess(Arg);
4933 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4934 CheckStaticArrayArgument(CallLoc, Param, Arg);
4936 AllArgs.push_back(Arg);
4939 // If this is a variadic call, handle args passed through "...".
4940 if (CallType != VariadicDoesNotApply) {
4941 // Assume that extern "C" functions with variadic arguments that
4942 // return __unknown_anytype aren't *really* variadic.
4943 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4944 FDecl->isExternC()) {
4945 for (Expr *A : Args.slice(ArgIx)) {
4946 QualType paramType; // ignored
4947 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4948 Invalid |= arg.isInvalid();
4949 AllArgs.push_back(arg.get());
4952 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4954 for (Expr *A : Args.slice(ArgIx)) {
4955 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4956 Invalid |= Arg.isInvalid();
4957 AllArgs.push_back(Arg.get());
4961 // Check for array bounds violations.
4962 for (Expr *A : Args.slice(ArgIx))
4963 CheckArrayAccess(A);
4968 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4969 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4970 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4971 TL = DTL.getOriginalLoc();
4972 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4973 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4974 << ATL.getLocalSourceRange();
4977 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4978 /// array parameter, check that it is non-null, and that if it is formed by
4979 /// array-to-pointer decay, the underlying array is sufficiently large.
4981 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4982 /// array type derivation, then for each call to the function, the value of the
4983 /// corresponding actual argument shall provide access to the first element of
4984 /// an array with at least as many elements as specified by the size expression.
4986 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4988 const Expr *ArgExpr) {
4989 // Static array parameters are not supported in C++.
4990 if (!Param || getLangOpts().CPlusPlus)
4993 QualType OrigTy = Param->getOriginalType();
4995 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4996 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4999 if (ArgExpr->isNullPointerConstant(Context,
5000 Expr::NPC_NeverValueDependent)) {
5001 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5002 DiagnoseCalleeStaticArrayParam(*this, Param);
5006 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5010 const ConstantArrayType *ArgCAT =
5011 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5015 if (ArgCAT->getSize().ult(CAT->getSize())) {
5016 Diag(CallLoc, diag::warn_static_array_too_small)
5017 << ArgExpr->getSourceRange()
5018 << (unsigned) ArgCAT->getSize().getZExtValue()
5019 << (unsigned) CAT->getSize().getZExtValue();
5020 DiagnoseCalleeStaticArrayParam(*this, Param);
5024 /// Given a function expression of unknown-any type, try to rebuild it
5025 /// to have a function type.
5026 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5028 /// Is the given type a placeholder that we need to lower out
5029 /// immediately during argument processing?
5030 static bool isPlaceholderToRemoveAsArg(QualType type) {
5031 // Placeholders are never sugared.
5032 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5033 if (!placeholder) return false;
5035 switch (placeholder->getKind()) {
5036 // Ignore all the non-placeholder types.
5037 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5038 case BuiltinType::Id:
5039 #include "clang/Basic/OpenCLImageTypes.def"
5040 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5041 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5042 #include "clang/AST/BuiltinTypes.def"
5045 // We cannot lower out overload sets; they might validly be resolved
5046 // by the call machinery.
5047 case BuiltinType::Overload:
5050 // Unbridged casts in ARC can be handled in some call positions and
5051 // should be left in place.
5052 case BuiltinType::ARCUnbridgedCast:
5055 // Pseudo-objects should be converted as soon as possible.
5056 case BuiltinType::PseudoObject:
5059 // The debugger mode could theoretically but currently does not try
5060 // to resolve unknown-typed arguments based on known parameter types.
5061 case BuiltinType::UnknownAny:
5064 // These are always invalid as call arguments and should be reported.
5065 case BuiltinType::BoundMember:
5066 case BuiltinType::BuiltinFn:
5067 case BuiltinType::OMPArraySection:
5071 llvm_unreachable("bad builtin type kind");
5074 /// Check an argument list for placeholders that we won't try to
5076 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5077 // Apply this processing to all the arguments at once instead of
5078 // dying at the first failure.
5079 bool hasInvalid = false;
5080 for (size_t i = 0, e = args.size(); i != e; i++) {
5081 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5082 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5083 if (result.isInvalid()) hasInvalid = true;
5084 else args[i] = result.get();
5085 } else if (hasInvalid) {
5086 (void)S.CorrectDelayedTyposInExpr(args[i]);
5092 /// If a builtin function has a pointer argument with no explicit address
5093 /// space, then it should be able to accept a pointer to any address
5094 /// space as input. In order to do this, we need to replace the
5095 /// standard builtin declaration with one that uses the same address space
5098 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5099 /// it does not contain any pointer arguments without
5100 /// an address space qualifer. Otherwise the rewritten
5101 /// FunctionDecl is returned.
5102 /// TODO: Handle pointer return types.
5103 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5104 const FunctionDecl *FDecl,
5105 MultiExprArg ArgExprs) {
5107 QualType DeclType = FDecl->getType();
5108 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5110 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5111 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5114 bool NeedsNewDecl = false;
5116 SmallVector<QualType, 8> OverloadParams;
5118 for (QualType ParamType : FT->param_types()) {
5120 // Convert array arguments to pointer to simplify type lookup.
5122 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5123 if (ArgRes.isInvalid())
5125 Expr *Arg = ArgRes.get();
5126 QualType ArgType = Arg->getType();
5127 if (!ParamType->isPointerType() ||
5128 ParamType.getQualifiers().hasAddressSpace() ||
5129 !ArgType->isPointerType() ||
5130 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5131 OverloadParams.push_back(ParamType);
5135 NeedsNewDecl = true;
5136 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5138 QualType PointeeType = ParamType->getPointeeType();
5139 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5140 OverloadParams.push_back(Context.getPointerType(PointeeType));
5146 FunctionProtoType::ExtProtoInfo EPI;
5147 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5148 OverloadParams, EPI);
5149 DeclContext *Parent = Context.getTranslationUnitDecl();
5150 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5151 FDecl->getLocation(),
5152 FDecl->getLocation(),
5153 FDecl->getIdentifier(),
5157 /*hasPrototype=*/true);
5158 SmallVector<ParmVarDecl*, 16> Params;
5159 FT = cast<FunctionProtoType>(OverloadTy);
5160 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5161 QualType ParamType = FT->getParamType(i);
5163 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5164 SourceLocation(), nullptr, ParamType,
5165 /*TInfo=*/nullptr, SC_None, nullptr);
5166 Parm->setScopeInfo(0, i);
5167 Params.push_back(Parm);
5169 OverloadDecl->setParams(Params);
5170 return OverloadDecl;
5173 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5174 FunctionDecl *Callee,
5175 MultiExprArg ArgExprs) {
5176 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5177 // similar attributes) really don't like it when functions are called with an
5178 // invalid number of args.
5179 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5180 /*PartialOverloading=*/false) &&
5181 !Callee->isVariadic())
5183 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5186 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5187 S.Diag(Fn->getLocStart(),
5188 isa<CXXMethodDecl>(Callee)
5189 ? diag::err_ovl_no_viable_member_function_in_call
5190 : diag::err_ovl_no_viable_function_in_call)
5191 << Callee << Callee->getSourceRange();
5192 S.Diag(Callee->getLocation(),
5193 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5194 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5199 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5200 /// This provides the location of the left/right parens and a list of comma
5202 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5203 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5204 Expr *ExecConfig, bool IsExecConfig) {
5205 // Since this might be a postfix expression, get rid of ParenListExprs.
5206 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5207 if (Result.isInvalid()) return ExprError();
5210 if (checkArgsForPlaceholders(*this, ArgExprs))
5213 if (getLangOpts().CPlusPlus) {
5214 // If this is a pseudo-destructor expression, build the call immediately.
5215 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5216 if (!ArgExprs.empty()) {
5217 // Pseudo-destructor calls should not have any arguments.
5218 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5219 << FixItHint::CreateRemoval(
5220 SourceRange(ArgExprs.front()->getLocStart(),
5221 ArgExprs.back()->getLocEnd()));
5224 return new (Context)
5225 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5227 if (Fn->getType() == Context.PseudoObjectTy) {
5228 ExprResult result = CheckPlaceholderExpr(Fn);
5229 if (result.isInvalid()) return ExprError();
5233 // Determine whether this is a dependent call inside a C++ template,
5234 // in which case we won't do any semantic analysis now.
5235 bool Dependent = false;
5236 if (Fn->isTypeDependent())
5238 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5243 return new (Context) CUDAKernelCallExpr(
5244 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5245 Context.DependentTy, VK_RValue, RParenLoc);
5247 return new (Context) CallExpr(
5248 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5252 // Determine whether this is a call to an object (C++ [over.call.object]).
5253 if (Fn->getType()->isRecordType())
5254 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5257 if (Fn->getType() == Context.UnknownAnyTy) {
5258 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5259 if (result.isInvalid()) return ExprError();
5263 if (Fn->getType() == Context.BoundMemberTy) {
5264 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5269 // Check for overloaded calls. This can happen even in C due to extensions.
5270 if (Fn->getType() == Context.OverloadTy) {
5271 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5273 // We aren't supposed to apply this logic for if there'Scope an '&'
5275 if (!find.HasFormOfMemberPointer) {
5276 OverloadExpr *ovl = find.Expression;
5277 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5278 return BuildOverloadedCallExpr(
5279 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5280 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5281 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5286 // If we're directly calling a function, get the appropriate declaration.
5287 if (Fn->getType() == Context.UnknownAnyTy) {
5288 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5289 if (result.isInvalid()) return ExprError();
5293 Expr *NakedFn = Fn->IgnoreParens();
5295 bool CallingNDeclIndirectly = false;
5296 NamedDecl *NDecl = nullptr;
5297 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5298 if (UnOp->getOpcode() == UO_AddrOf) {
5299 CallingNDeclIndirectly = true;
5300 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5304 if (isa<DeclRefExpr>(NakedFn)) {
5305 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5307 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5308 if (FDecl && FDecl->getBuiltinID()) {
5309 // Rewrite the function decl for this builtin by replacing parameters
5310 // with no explicit address space with the address space of the arguments
5313 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5315 Fn = DeclRefExpr::Create(
5316 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5317 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5320 } else if (isa<MemberExpr>(NakedFn))
5321 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5323 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5324 if (CallingNDeclIndirectly &&
5325 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5329 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5332 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5335 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5336 ExecConfig, IsExecConfig);
5339 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5341 /// __builtin_astype( value, dst type )
5343 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5344 SourceLocation BuiltinLoc,
5345 SourceLocation RParenLoc) {
5346 ExprValueKind VK = VK_RValue;
5347 ExprObjectKind OK = OK_Ordinary;
5348 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5349 QualType SrcTy = E->getType();
5350 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5351 return ExprError(Diag(BuiltinLoc,
5352 diag::err_invalid_astype_of_different_size)
5355 << E->getSourceRange());
5356 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5359 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5360 /// provided arguments.
5362 /// __builtin_convertvector( value, dst type )
5364 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5365 SourceLocation BuiltinLoc,
5366 SourceLocation RParenLoc) {
5367 TypeSourceInfo *TInfo;
5368 GetTypeFromParser(ParsedDestTy, &TInfo);
5369 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5372 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5373 /// i.e. an expression not of \p OverloadTy. The expression should
5374 /// unary-convert to an expression of function-pointer or
5375 /// block-pointer type.
5377 /// \param NDecl the declaration being called, if available
5379 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5380 SourceLocation LParenLoc,
5381 ArrayRef<Expr *> Args,
5382 SourceLocation RParenLoc,
5383 Expr *Config, bool IsExecConfig) {
5384 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5385 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5387 // Functions with 'interrupt' attribute cannot be called directly.
5388 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5389 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5393 // Interrupt handlers don't save off the VFP regs automatically on ARM,
5394 // so there's some risk when calling out to non-interrupt handler functions
5395 // that the callee might not preserve them. This is easy to diagnose here,
5396 // but can be very challenging to debug.
5397 if (auto *Caller = getCurFunctionDecl())
5398 if (Caller->hasAttr<ARMInterruptAttr>())
5399 if (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())
5400 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5402 // Promote the function operand.
5403 // We special-case function promotion here because we only allow promoting
5404 // builtin functions to function pointers in the callee of a call.
5407 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5408 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5409 CK_BuiltinFnToFnPtr).get();
5411 Result = CallExprUnaryConversions(Fn);
5413 if (Result.isInvalid())
5417 // Make the call expr early, before semantic checks. This guarantees cleanup
5418 // of arguments and function on error.
5421 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5422 cast<CallExpr>(Config), Args,
5423 Context.BoolTy, VK_RValue,
5426 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5427 VK_RValue, RParenLoc);
5429 if (!getLangOpts().CPlusPlus) {
5430 // C cannot always handle TypoExpr nodes in builtin calls and direct
5431 // function calls as their argument checking don't necessarily handle
5432 // dependent types properly, so make sure any TypoExprs have been
5434 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5435 if (!Result.isUsable()) return ExprError();
5436 TheCall = dyn_cast<CallExpr>(Result.get());
5437 if (!TheCall) return Result;
5438 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5441 // Bail out early if calling a builtin with custom typechecking.
5442 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5443 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5446 const FunctionType *FuncT;
5447 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5448 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5449 // have type pointer to function".
5450 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5452 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5453 << Fn->getType() << Fn->getSourceRange());
5454 } else if (const BlockPointerType *BPT =
5455 Fn->getType()->getAs<BlockPointerType>()) {
5456 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5458 // Handle calls to expressions of unknown-any type.
5459 if (Fn->getType() == Context.UnknownAnyTy) {
5460 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5461 if (rewrite.isInvalid()) return ExprError();
5463 TheCall->setCallee(Fn);
5467 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5468 << Fn->getType() << Fn->getSourceRange());
5471 if (getLangOpts().CUDA) {
5473 // CUDA: Kernel calls must be to global functions
5474 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5475 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5476 << FDecl->getName() << Fn->getSourceRange());
5478 // CUDA: Kernel function must have 'void' return type
5479 if (!FuncT->getReturnType()->isVoidType())
5480 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5481 << Fn->getType() << Fn->getSourceRange());
5483 // CUDA: Calls to global functions must be configured
5484 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5485 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5486 << FDecl->getName() << Fn->getSourceRange());
5490 // Check for a valid return type
5491 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5495 // We know the result type of the call, set it.
5496 TheCall->setType(FuncT->getCallResultType(Context));
5497 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5499 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5501 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5505 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5508 // Check if we have too few/too many template arguments, based
5509 // on our knowledge of the function definition.
5510 const FunctionDecl *Def = nullptr;
5511 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5512 Proto = Def->getType()->getAs<FunctionProtoType>();
5513 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5514 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5515 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5518 // If the function we're calling isn't a function prototype, but we have
5519 // a function prototype from a prior declaratiom, use that prototype.
5520 if (!FDecl->hasPrototype())
5521 Proto = FDecl->getType()->getAs<FunctionProtoType>();
5524 // Promote the arguments (C99 6.5.2.2p6).
5525 for (unsigned i = 0, e = Args.size(); i != e; i++) {
5526 Expr *Arg = Args[i];
5528 if (Proto && i < Proto->getNumParams()) {
5529 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5530 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5532 PerformCopyInitialization(Entity, SourceLocation(), Arg);
5533 if (ArgE.isInvalid())
5536 Arg = ArgE.getAs<Expr>();
5539 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5541 if (ArgE.isInvalid())
5544 Arg = ArgE.getAs<Expr>();
5547 if (RequireCompleteType(Arg->getLocStart(),
5549 diag::err_call_incomplete_argument, Arg))
5552 TheCall->setArg(i, Arg);
5556 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5557 if (!Method->isStatic())
5558 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5559 << Fn->getSourceRange());
5561 // Check for sentinels
5563 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5565 // Do special checking on direct calls to functions.
5567 if (CheckFunctionCall(FDecl, TheCall, Proto))
5571 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5573 if (CheckPointerCall(NDecl, TheCall, Proto))
5576 if (CheckOtherCall(TheCall, Proto))
5580 return MaybeBindToTemporary(TheCall);
5584 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5585 SourceLocation RParenLoc, Expr *InitExpr) {
5586 assert(Ty && "ActOnCompoundLiteral(): missing type");
5587 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5589 TypeSourceInfo *TInfo;
5590 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5592 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5594 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5598 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5599 SourceLocation RParenLoc, Expr *LiteralExpr) {
5600 QualType literalType = TInfo->getType();
5602 if (literalType->isArrayType()) {
5603 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5604 diag::err_illegal_decl_array_incomplete_type,
5605 SourceRange(LParenLoc,
5606 LiteralExpr->getSourceRange().getEnd())))
5608 if (literalType->isVariableArrayType())
5609 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5610 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5611 } else if (!literalType->isDependentType() &&
5612 RequireCompleteType(LParenLoc, literalType,
5613 diag::err_typecheck_decl_incomplete_type,
5614 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5617 InitializedEntity Entity
5618 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5619 InitializationKind Kind
5620 = InitializationKind::CreateCStyleCast(LParenLoc,
5621 SourceRange(LParenLoc, RParenLoc),
5623 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5624 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5626 if (Result.isInvalid())
5628 LiteralExpr = Result.get();
5630 bool isFileScope = !CurContext->isFunctionOrMethod();
5632 !LiteralExpr->isTypeDependent() &&
5633 !LiteralExpr->isValueDependent() &&
5634 !literalType->isDependentType()) { // 6.5.2.5p3
5635 if (CheckForConstantInitializer(LiteralExpr, literalType))
5639 // In C, compound literals are l-values for some reason.
5640 // For GCC compatibility, in C++, file-scope array compound literals with
5641 // constant initializers are also l-values, and compound literals are
5642 // otherwise prvalues.
5644 // (GCC also treats C++ list-initialized file-scope array prvalues with
5645 // constant initializers as l-values, but that's non-conforming, so we don't
5646 // follow it there.)
5648 // FIXME: It would be better to handle the lvalue cases as materializing and
5649 // lifetime-extending a temporary object, but our materialized temporaries
5650 // representation only supports lifetime extension from a variable, not "out
5652 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5653 // is bound to the result of applying array-to-pointer decay to the compound
5655 // FIXME: GCC supports compound literals of reference type, which should
5656 // obviously have a value kind derived from the kind of reference involved.
5658 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5662 return MaybeBindToTemporary(
5663 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5664 VK, LiteralExpr, isFileScope));
5668 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5669 SourceLocation RBraceLoc) {
5670 // Immediately handle non-overload placeholders. Overloads can be
5671 // resolved contextually, but everything else here can't.
5672 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5673 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5674 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5676 // Ignore failures; dropping the entire initializer list because
5677 // of one failure would be terrible for indexing/etc.
5678 if (result.isInvalid()) continue;
5680 InitArgList[I] = result.get();
5684 // Semantic analysis for initializers is done by ActOnDeclarator() and
5685 // CheckInitializer() - it requires knowledge of the object being intialized.
5687 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5689 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5693 /// Do an explicit extend of the given block pointer if we're in ARC.
5694 void Sema::maybeExtendBlockObject(ExprResult &E) {
5695 assert(E.get()->getType()->isBlockPointerType());
5696 assert(E.get()->isRValue());
5698 // Only do this in an r-value context.
5699 if (!getLangOpts().ObjCAutoRefCount) return;
5701 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5702 CK_ARCExtendBlockObject, E.get(),
5703 /*base path*/ nullptr, VK_RValue);
5704 Cleanup.setExprNeedsCleanups(true);
5707 /// Prepare a conversion of the given expression to an ObjC object
5709 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5710 QualType type = E.get()->getType();
5711 if (type->isObjCObjectPointerType()) {
5713 } else if (type->isBlockPointerType()) {
5714 maybeExtendBlockObject(E);
5715 return CK_BlockPointerToObjCPointerCast;
5717 assert(type->isPointerType());
5718 return CK_CPointerToObjCPointerCast;
5722 /// Prepares for a scalar cast, performing all the necessary stages
5723 /// except the final cast and returning the kind required.
5724 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5725 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5726 // Also, callers should have filtered out the invalid cases with
5727 // pointers. Everything else should be possible.
5729 QualType SrcTy = Src.get()->getType();
5730 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5733 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5734 case Type::STK_MemberPointer:
5735 llvm_unreachable("member pointer type in C");
5737 case Type::STK_CPointer:
5738 case Type::STK_BlockPointer:
5739 case Type::STK_ObjCObjectPointer:
5740 switch (DestTy->getScalarTypeKind()) {
5741 case Type::STK_CPointer: {
5742 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5743 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5744 if (SrcAS != DestAS)
5745 return CK_AddressSpaceConversion;
5748 case Type::STK_BlockPointer:
5749 return (SrcKind == Type::STK_BlockPointer
5750 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5751 case Type::STK_ObjCObjectPointer:
5752 if (SrcKind == Type::STK_ObjCObjectPointer)
5754 if (SrcKind == Type::STK_CPointer)
5755 return CK_CPointerToObjCPointerCast;
5756 maybeExtendBlockObject(Src);
5757 return CK_BlockPointerToObjCPointerCast;
5758 case Type::STK_Bool:
5759 return CK_PointerToBoolean;
5760 case Type::STK_Integral:
5761 return CK_PointerToIntegral;
5762 case Type::STK_Floating:
5763 case Type::STK_FloatingComplex:
5764 case Type::STK_IntegralComplex:
5765 case Type::STK_MemberPointer:
5766 llvm_unreachable("illegal cast from pointer");
5768 llvm_unreachable("Should have returned before this");
5770 case Type::STK_Bool: // casting from bool is like casting from an integer
5771 case Type::STK_Integral:
5772 switch (DestTy->getScalarTypeKind()) {
5773 case Type::STK_CPointer:
5774 case Type::STK_ObjCObjectPointer:
5775 case Type::STK_BlockPointer:
5776 if (Src.get()->isNullPointerConstant(Context,
5777 Expr::NPC_ValueDependentIsNull))
5778 return CK_NullToPointer;
5779 return CK_IntegralToPointer;
5780 case Type::STK_Bool:
5781 return CK_IntegralToBoolean;
5782 case Type::STK_Integral:
5783 return CK_IntegralCast;
5784 case Type::STK_Floating:
5785 return CK_IntegralToFloating;
5786 case Type::STK_IntegralComplex:
5787 Src = ImpCastExprToType(Src.get(),
5788 DestTy->castAs<ComplexType>()->getElementType(),
5790 return CK_IntegralRealToComplex;
5791 case Type::STK_FloatingComplex:
5792 Src = ImpCastExprToType(Src.get(),
5793 DestTy->castAs<ComplexType>()->getElementType(),
5794 CK_IntegralToFloating);
5795 return CK_FloatingRealToComplex;
5796 case Type::STK_MemberPointer:
5797 llvm_unreachable("member pointer type in C");
5799 llvm_unreachable("Should have returned before this");
5801 case Type::STK_Floating:
5802 switch (DestTy->getScalarTypeKind()) {
5803 case Type::STK_Floating:
5804 return CK_FloatingCast;
5805 case Type::STK_Bool:
5806 return CK_FloatingToBoolean;
5807 case Type::STK_Integral:
5808 return CK_FloatingToIntegral;
5809 case Type::STK_FloatingComplex:
5810 Src = ImpCastExprToType(Src.get(),
5811 DestTy->castAs<ComplexType>()->getElementType(),
5813 return CK_FloatingRealToComplex;
5814 case Type::STK_IntegralComplex:
5815 Src = ImpCastExprToType(Src.get(),
5816 DestTy->castAs<ComplexType>()->getElementType(),
5817 CK_FloatingToIntegral);
5818 return CK_IntegralRealToComplex;
5819 case Type::STK_CPointer:
5820 case Type::STK_ObjCObjectPointer:
5821 case Type::STK_BlockPointer:
5822 llvm_unreachable("valid float->pointer cast?");
5823 case Type::STK_MemberPointer:
5824 llvm_unreachable("member pointer type in C");
5826 llvm_unreachable("Should have returned before this");
5828 case Type::STK_FloatingComplex:
5829 switch (DestTy->getScalarTypeKind()) {
5830 case Type::STK_FloatingComplex:
5831 return CK_FloatingComplexCast;
5832 case Type::STK_IntegralComplex:
5833 return CK_FloatingComplexToIntegralComplex;
5834 case Type::STK_Floating: {
5835 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5836 if (Context.hasSameType(ET, DestTy))
5837 return CK_FloatingComplexToReal;
5838 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5839 return CK_FloatingCast;
5841 case Type::STK_Bool:
5842 return CK_FloatingComplexToBoolean;
5843 case Type::STK_Integral:
5844 Src = ImpCastExprToType(Src.get(),
5845 SrcTy->castAs<ComplexType>()->getElementType(),
5846 CK_FloatingComplexToReal);
5847 return CK_FloatingToIntegral;
5848 case Type::STK_CPointer:
5849 case Type::STK_ObjCObjectPointer:
5850 case Type::STK_BlockPointer:
5851 llvm_unreachable("valid complex float->pointer cast?");
5852 case Type::STK_MemberPointer:
5853 llvm_unreachable("member pointer type in C");
5855 llvm_unreachable("Should have returned before this");
5857 case Type::STK_IntegralComplex:
5858 switch (DestTy->getScalarTypeKind()) {
5859 case Type::STK_FloatingComplex:
5860 return CK_IntegralComplexToFloatingComplex;
5861 case Type::STK_IntegralComplex:
5862 return CK_IntegralComplexCast;
5863 case Type::STK_Integral: {
5864 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5865 if (Context.hasSameType(ET, DestTy))
5866 return CK_IntegralComplexToReal;
5867 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5868 return CK_IntegralCast;
5870 case Type::STK_Bool:
5871 return CK_IntegralComplexToBoolean;
5872 case Type::STK_Floating:
5873 Src = ImpCastExprToType(Src.get(),
5874 SrcTy->castAs<ComplexType>()->getElementType(),
5875 CK_IntegralComplexToReal);
5876 return CK_IntegralToFloating;
5877 case Type::STK_CPointer:
5878 case Type::STK_ObjCObjectPointer:
5879 case Type::STK_BlockPointer:
5880 llvm_unreachable("valid complex int->pointer cast?");
5881 case Type::STK_MemberPointer:
5882 llvm_unreachable("member pointer type in C");
5884 llvm_unreachable("Should have returned before this");
5887 llvm_unreachable("Unhandled scalar cast");
5890 static bool breakDownVectorType(QualType type, uint64_t &len,
5891 QualType &eltType) {
5892 // Vectors are simple.
5893 if (const VectorType *vecType = type->getAs<VectorType>()) {
5894 len = vecType->getNumElements();
5895 eltType = vecType->getElementType();
5896 assert(eltType->isScalarType());
5900 // We allow lax conversion to and from non-vector types, but only if
5901 // they're real types (i.e. non-complex, non-pointer scalar types).
5902 if (!type->isRealType()) return false;
5909 /// Are the two types lax-compatible vector types? That is, given
5910 /// that one of them is a vector, do they have equal storage sizes,
5911 /// where the storage size is the number of elements times the element
5914 /// This will also return false if either of the types is neither a
5915 /// vector nor a real type.
5916 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5917 assert(destTy->isVectorType() || srcTy->isVectorType());
5919 // Disallow lax conversions between scalars and ExtVectors (these
5920 // conversions are allowed for other vector types because common headers
5921 // depend on them). Most scalar OP ExtVector cases are handled by the
5922 // splat path anyway, which does what we want (convert, not bitcast).
5923 // What this rules out for ExtVectors is crazy things like char4*float.
5924 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5925 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5927 uint64_t srcLen, destLen;
5928 QualType srcEltTy, destEltTy;
5929 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5930 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5932 // ASTContext::getTypeSize will return the size rounded up to a
5933 // power of 2, so instead of using that, we need to use the raw
5934 // element size multiplied by the element count.
5935 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5936 uint64_t destEltSize = Context.getTypeSize(destEltTy);
5938 return (srcLen * srcEltSize == destLen * destEltSize);
5941 /// Is this a legal conversion between two types, one of which is
5942 /// known to be a vector type?
5943 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5944 assert(destTy->isVectorType() || srcTy->isVectorType());
5946 if (!Context.getLangOpts().LaxVectorConversions)
5948 return areLaxCompatibleVectorTypes(srcTy, destTy);
5951 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5953 assert(VectorTy->isVectorType() && "Not a vector type!");
5955 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5956 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5957 return Diag(R.getBegin(),
5958 Ty->isVectorType() ?
5959 diag::err_invalid_conversion_between_vectors :
5960 diag::err_invalid_conversion_between_vector_and_integer)
5961 << VectorTy << Ty << R;
5963 return Diag(R.getBegin(),
5964 diag::err_invalid_conversion_between_vector_and_scalar)
5965 << VectorTy << Ty << R;
5971 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5972 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5974 if (DestElemTy == SplattedExpr->getType())
5975 return SplattedExpr;
5977 assert(DestElemTy->isFloatingType() ||
5978 DestElemTy->isIntegralOrEnumerationType());
5981 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5982 // OpenCL requires that we convert `true` boolean expressions to -1, but
5983 // only when splatting vectors.
5984 if (DestElemTy->isFloatingType()) {
5985 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5986 // in two steps: boolean to signed integral, then to floating.
5987 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5988 CK_BooleanToSignedIntegral);
5989 SplattedExpr = CastExprRes.get();
5990 CK = CK_IntegralToFloating;
5992 CK = CK_BooleanToSignedIntegral;
5995 ExprResult CastExprRes = SplattedExpr;
5996 CK = PrepareScalarCast(CastExprRes, DestElemTy);
5997 if (CastExprRes.isInvalid())
5999 SplattedExpr = CastExprRes.get();
6001 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6004 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6005 Expr *CastExpr, CastKind &Kind) {
6006 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6008 QualType SrcTy = CastExpr->getType();
6010 // If SrcTy is a VectorType, the total size must match to explicitly cast to
6011 // an ExtVectorType.
6012 // In OpenCL, casts between vectors of different types are not allowed.
6013 // (See OpenCL 6.2).
6014 if (SrcTy->isVectorType()) {
6015 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6016 || (getLangOpts().OpenCL &&
6017 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6018 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6019 << DestTy << SrcTy << R;
6026 // All non-pointer scalars can be cast to ExtVector type. The appropriate
6027 // conversion will take place first from scalar to elt type, and then
6028 // splat from elt type to vector.
6029 if (SrcTy->isPointerType())
6030 return Diag(R.getBegin(),
6031 diag::err_invalid_conversion_between_vector_and_scalar)
6032 << DestTy << SrcTy << R;
6034 Kind = CK_VectorSplat;
6035 return prepareVectorSplat(DestTy, CastExpr);
6039 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6040 Declarator &D, ParsedType &Ty,
6041 SourceLocation RParenLoc, Expr *CastExpr) {
6042 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6043 "ActOnCastExpr(): missing type or expr");
6045 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6046 if (D.isInvalidType())
6049 if (getLangOpts().CPlusPlus) {
6050 // Check that there are no default arguments (C++ only).
6051 CheckExtraCXXDefaultArguments(D);
6053 // Make sure any TypoExprs have been dealt with.
6054 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6055 if (!Res.isUsable())
6057 CastExpr = Res.get();
6060 checkUnusedDeclAttributes(D);
6062 QualType castType = castTInfo->getType();
6063 Ty = CreateParsedType(castType, castTInfo);
6065 bool isVectorLiteral = false;
6067 // Check for an altivec or OpenCL literal,
6068 // i.e. all the elements are integer constants.
6069 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6070 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6071 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6072 && castType->isVectorType() && (PE || PLE)) {
6073 if (PLE && PLE->getNumExprs() == 0) {
6074 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6077 if (PE || PLE->getNumExprs() == 1) {
6078 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6079 if (!E->getType()->isVectorType())
6080 isVectorLiteral = true;
6083 isVectorLiteral = true;
6086 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6087 // then handle it as such.
6088 if (isVectorLiteral)
6089 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6091 // If the Expr being casted is a ParenListExpr, handle it specially.
6092 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6093 // sequence of BinOp comma operators.
6094 if (isa<ParenListExpr>(CastExpr)) {
6095 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6096 if (Result.isInvalid()) return ExprError();
6097 CastExpr = Result.get();
6100 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6101 !getSourceManager().isInSystemMacro(LParenLoc))
6102 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6104 CheckTollFreeBridgeCast(castType, CastExpr);
6106 CheckObjCBridgeRelatedCast(castType, CastExpr);
6108 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6110 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6113 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6114 SourceLocation RParenLoc, Expr *E,
6115 TypeSourceInfo *TInfo) {
6116 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6117 "Expected paren or paren list expression");
6122 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6123 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6124 LiteralLParenLoc = PE->getLParenLoc();
6125 LiteralRParenLoc = PE->getRParenLoc();
6126 exprs = PE->getExprs();
6127 numExprs = PE->getNumExprs();
6128 } else { // isa<ParenExpr> by assertion at function entrance
6129 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6130 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6131 subExpr = cast<ParenExpr>(E)->getSubExpr();
6136 QualType Ty = TInfo->getType();
6137 assert(Ty->isVectorType() && "Expected vector type");
6139 SmallVector<Expr *, 8> initExprs;
6140 const VectorType *VTy = Ty->getAs<VectorType>();
6141 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6143 // '(...)' form of vector initialization in AltiVec: the number of
6144 // initializers must be one or must match the size of the vector.
6145 // If a single value is specified in the initializer then it will be
6146 // replicated to all the components of the vector
6147 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6148 // The number of initializers must be one or must match the size of the
6149 // vector. If a single value is specified in the initializer then it will
6150 // be replicated to all the components of the vector
6151 if (numExprs == 1) {
6152 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6153 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6154 if (Literal.isInvalid())
6156 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6157 PrepareScalarCast(Literal, ElemTy));
6158 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6160 else if (numExprs < numElems) {
6161 Diag(E->getExprLoc(),
6162 diag::err_incorrect_number_of_vector_initializers);
6166 initExprs.append(exprs, exprs + numExprs);
6169 // For OpenCL, when the number of initializers is a single value,
6170 // it will be replicated to all components of the vector.
6171 if (getLangOpts().OpenCL &&
6172 VTy->getVectorKind() == VectorType::GenericVector &&
6174 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6175 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6176 if (Literal.isInvalid())
6178 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6179 PrepareScalarCast(Literal, ElemTy));
6180 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6183 initExprs.append(exprs, exprs + numExprs);
6185 // FIXME: This means that pretty-printing the final AST will produce curly
6186 // braces instead of the original commas.
6187 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6188 initExprs, LiteralRParenLoc);
6190 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6193 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6194 /// the ParenListExpr into a sequence of comma binary operators.
6196 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6197 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6201 ExprResult Result(E->getExpr(0));
6203 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6204 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6207 if (Result.isInvalid()) return ExprError();
6209 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6212 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6215 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6219 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6220 /// constant and the other is not a pointer. Returns true if a diagnostic is
6222 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6223 SourceLocation QuestionLoc) {
6224 Expr *NullExpr = LHSExpr;
6225 Expr *NonPointerExpr = RHSExpr;
6226 Expr::NullPointerConstantKind NullKind =
6227 NullExpr->isNullPointerConstant(Context,
6228 Expr::NPC_ValueDependentIsNotNull);
6230 if (NullKind == Expr::NPCK_NotNull) {
6232 NonPointerExpr = LHSExpr;
6234 NullExpr->isNullPointerConstant(Context,
6235 Expr::NPC_ValueDependentIsNotNull);
6238 if (NullKind == Expr::NPCK_NotNull)
6241 if (NullKind == Expr::NPCK_ZeroExpression)
6244 if (NullKind == Expr::NPCK_ZeroLiteral) {
6245 // In this case, check to make sure that we got here from a "NULL"
6246 // string in the source code.
6247 NullExpr = NullExpr->IgnoreParenImpCasts();
6248 SourceLocation loc = NullExpr->getExprLoc();
6249 if (!findMacroSpelling(loc, "NULL"))
6253 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6254 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6255 << NonPointerExpr->getType() << DiagType
6256 << NonPointerExpr->getSourceRange();
6260 /// \brief Return false if the condition expression is valid, true otherwise.
6261 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6262 QualType CondTy = Cond->getType();
6264 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6265 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6266 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6267 << CondTy << Cond->getSourceRange();
6272 if (CondTy->isScalarType()) return false;
6274 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6275 << CondTy << Cond->getSourceRange();
6279 /// \brief Handle when one or both operands are void type.
6280 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6282 Expr *LHSExpr = LHS.get();
6283 Expr *RHSExpr = RHS.get();
6285 if (!LHSExpr->getType()->isVoidType())
6286 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6287 << RHSExpr->getSourceRange();
6288 if (!RHSExpr->getType()->isVoidType())
6289 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6290 << LHSExpr->getSourceRange();
6291 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6292 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6293 return S.Context.VoidTy;
6296 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6298 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6299 QualType PointerTy) {
6300 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6301 !NullExpr.get()->isNullPointerConstant(S.Context,
6302 Expr::NPC_ValueDependentIsNull))
6305 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6309 /// \brief Checks compatibility between two pointers and return the resulting
6311 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6313 SourceLocation Loc) {
6314 QualType LHSTy = LHS.get()->getType();
6315 QualType RHSTy = RHS.get()->getType();
6317 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6318 // Two identical pointers types are always compatible.
6322 QualType lhptee, rhptee;
6324 // Get the pointee types.
6325 bool IsBlockPointer = false;
6326 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6327 lhptee = LHSBTy->getPointeeType();
6328 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6329 IsBlockPointer = true;
6331 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6332 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6335 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6336 // differently qualified versions of compatible types, the result type is
6337 // a pointer to an appropriately qualified version of the composite
6340 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6341 // clause doesn't make sense for our extensions. E.g. address space 2 should
6342 // be incompatible with address space 3: they may live on different devices or
6344 Qualifiers lhQual = lhptee.getQualifiers();
6345 Qualifiers rhQual = rhptee.getQualifiers();
6347 unsigned ResultAddrSpace = 0;
6348 unsigned LAddrSpace = lhQual.getAddressSpace();
6349 unsigned RAddrSpace = rhQual.getAddressSpace();
6350 if (S.getLangOpts().OpenCL) {
6351 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6352 // spaces is disallowed.
6353 if (lhQual.isAddressSpaceSupersetOf(rhQual))
6354 ResultAddrSpace = LAddrSpace;
6355 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6356 ResultAddrSpace = RAddrSpace;
6359 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6360 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6361 << RHS.get()->getSourceRange();
6366 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6367 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6368 lhQual.removeCVRQualifiers();
6369 rhQual.removeCVRQualifiers();
6371 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6372 // (C99 6.7.3) for address spaces. We assume that the check should behave in
6373 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6374 // qual types are compatible iff
6375 // * corresponded types are compatible
6376 // * CVR qualifiers are equal
6377 // * address spaces are equal
6378 // Thus for conditional operator we merge CVR and address space unqualified
6379 // pointees and if there is a composite type we return a pointer to it with
6380 // merged qualifiers.
6381 if (S.getLangOpts().OpenCL) {
6382 LHSCastKind = LAddrSpace == ResultAddrSpace
6384 : CK_AddressSpaceConversion;
6385 RHSCastKind = RAddrSpace == ResultAddrSpace
6387 : CK_AddressSpaceConversion;
6388 lhQual.removeAddressSpace();
6389 rhQual.removeAddressSpace();
6392 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6393 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6395 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6397 if (CompositeTy.isNull()) {
6398 // In this situation, we assume void* type. No especially good
6399 // reason, but this is what gcc does, and we do have to pick
6400 // to get a consistent AST.
6401 QualType incompatTy;
6402 incompatTy = S.Context.getPointerType(
6403 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6404 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6405 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6406 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6407 // for casts between types with incompatible address space qualifiers.
6408 // For the following code the compiler produces casts between global and
6409 // local address spaces of the corresponded innermost pointees:
6410 // local int *global *a;
6411 // global int *global *b;
6412 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6413 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6414 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6415 << RHS.get()->getSourceRange();
6419 // The pointer types are compatible.
6420 // In case of OpenCL ResultTy should have the address space qualifier
6421 // which is a superset of address spaces of both the 2nd and the 3rd
6422 // operands of the conditional operator.
6423 QualType ResultTy = [&, ResultAddrSpace]() {
6424 if (S.getLangOpts().OpenCL) {
6425 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6426 CompositeQuals.setAddressSpace(ResultAddrSpace);
6428 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6429 .withCVRQualifiers(MergedCVRQual);
6431 return CompositeTy.withCVRQualifiers(MergedCVRQual);
6434 ResultTy = S.Context.getBlockPointerType(ResultTy);
6436 ResultTy = S.Context.getPointerType(ResultTy);
6439 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6440 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6444 /// \brief Return the resulting type when the operands are both block pointers.
6445 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6448 SourceLocation Loc) {
6449 QualType LHSTy = LHS.get()->getType();
6450 QualType RHSTy = RHS.get()->getType();
6452 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6453 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6454 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6455 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6456 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6459 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6460 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6461 << RHS.get()->getSourceRange();
6465 // We have 2 block pointer types.
6466 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6469 /// \brief Return the resulting type when the operands are both pointers.
6471 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6473 SourceLocation Loc) {
6474 // get the pointer types
6475 QualType LHSTy = LHS.get()->getType();
6476 QualType RHSTy = RHS.get()->getType();
6478 // get the "pointed to" types
6479 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6480 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6482 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6483 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6484 // Figure out necessary qualifiers (C99 6.5.15p6)
6485 QualType destPointee
6486 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6487 QualType destType = S.Context.getPointerType(destPointee);
6488 // Add qualifiers if necessary.
6489 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6490 // Promote to void*.
6491 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6494 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6495 QualType destPointee
6496 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6497 QualType destType = S.Context.getPointerType(destPointee);
6498 // Add qualifiers if necessary.
6499 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6500 // Promote to void*.
6501 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6505 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6508 /// \brief Return false if the first expression is not an integer and the second
6509 /// expression is not a pointer, true otherwise.
6510 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6511 Expr* PointerExpr, SourceLocation Loc,
6512 bool IsIntFirstExpr) {
6513 if (!PointerExpr->getType()->isPointerType() ||
6514 !Int.get()->getType()->isIntegerType())
6517 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6518 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6520 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6521 << Expr1->getType() << Expr2->getType()
6522 << Expr1->getSourceRange() << Expr2->getSourceRange();
6523 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6524 CK_IntegralToPointer);
6528 /// \brief Simple conversion between integer and floating point types.
6530 /// Used when handling the OpenCL conditional operator where the
6531 /// condition is a vector while the other operands are scalar.
6533 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6534 /// types are either integer or floating type. Between the two
6535 /// operands, the type with the higher rank is defined as the "result
6536 /// type". The other operand needs to be promoted to the same type. No
6537 /// other type promotion is allowed. We cannot use
6538 /// UsualArithmeticConversions() for this purpose, since it always
6539 /// promotes promotable types.
6540 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6542 SourceLocation QuestionLoc) {
6543 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6544 if (LHS.isInvalid())
6546 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6547 if (RHS.isInvalid())
6550 // For conversion purposes, we ignore any qualifiers.
6551 // For example, "const float" and "float" are equivalent.
6553 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6555 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6557 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6558 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6559 << LHSType << LHS.get()->getSourceRange();
6563 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6564 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6565 << RHSType << RHS.get()->getSourceRange();
6569 // If both types are identical, no conversion is needed.
6570 if (LHSType == RHSType)
6573 // Now handle "real" floating types (i.e. float, double, long double).
6574 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6575 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6576 /*IsCompAssign = */ false);
6578 // Finally, we have two differing integer types.
6579 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6580 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6583 /// \brief Convert scalar operands to a vector that matches the
6584 /// condition in length.
6586 /// Used when handling the OpenCL conditional operator where the
6587 /// condition is a vector while the other operands are scalar.
6589 /// We first compute the "result type" for the scalar operands
6590 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6591 /// into a vector of that type where the length matches the condition
6592 /// vector type. s6.11.6 requires that the element types of the result
6593 /// and the condition must have the same number of bits.
6595 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6596 QualType CondTy, SourceLocation QuestionLoc) {
6597 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6598 if (ResTy.isNull()) return QualType();
6600 const VectorType *CV = CondTy->getAs<VectorType>();
6603 // Determine the vector result type
6604 unsigned NumElements = CV->getNumElements();
6605 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6607 // Ensure that all types have the same number of bits
6608 if (S.Context.getTypeSize(CV->getElementType())
6609 != S.Context.getTypeSize(ResTy)) {
6610 // Since VectorTy is created internally, it does not pretty print
6611 // with an OpenCL name. Instead, we just print a description.
6612 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6613 SmallString<64> Str;
6614 llvm::raw_svector_ostream OS(Str);
6615 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6616 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6617 << CondTy << OS.str();
6621 // Convert operands to the vector result type
6622 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6623 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6628 /// \brief Return false if this is a valid OpenCL condition vector
6629 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6630 SourceLocation QuestionLoc) {
6631 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6633 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6635 QualType EleTy = CondTy->getElementType();
6636 if (EleTy->isIntegerType()) return false;
6638 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6639 << Cond->getType() << Cond->getSourceRange();
6643 /// \brief Return false if the vector condition type and the vector
6644 /// result type are compatible.
6646 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6647 /// number of elements, and their element types have the same number
6649 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6650 SourceLocation QuestionLoc) {
6651 const VectorType *CV = CondTy->getAs<VectorType>();
6652 const VectorType *RV = VecResTy->getAs<VectorType>();
6655 if (CV->getNumElements() != RV->getNumElements()) {
6656 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6657 << CondTy << VecResTy;
6661 QualType CVE = CV->getElementType();
6662 QualType RVE = RV->getElementType();
6664 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6665 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6666 << CondTy << VecResTy;
6673 /// \brief Return the resulting type for the conditional operator in
6674 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6675 /// s6.3.i) when the condition is a vector type.
6677 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6678 ExprResult &LHS, ExprResult &RHS,
6679 SourceLocation QuestionLoc) {
6680 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6681 if (Cond.isInvalid())
6683 QualType CondTy = Cond.get()->getType();
6685 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6688 // If either operand is a vector then find the vector type of the
6689 // result as specified in OpenCL v1.1 s6.3.i.
6690 if (LHS.get()->getType()->isVectorType() ||
6691 RHS.get()->getType()->isVectorType()) {
6692 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6693 /*isCompAssign*/false,
6694 /*AllowBothBool*/true,
6695 /*AllowBoolConversions*/false);
6696 if (VecResTy.isNull()) return QualType();
6697 // The result type must match the condition type as specified in
6698 // OpenCL v1.1 s6.11.6.
6699 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6704 // Both operands are scalar.
6705 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6708 /// \brief Return true if the Expr is block type
6709 static bool checkBlockType(Sema &S, const Expr *E) {
6710 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6711 QualType Ty = CE->getCallee()->getType();
6712 if (Ty->isBlockPointerType()) {
6713 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6720 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6721 /// In that case, LHS = cond.
6723 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6724 ExprResult &RHS, ExprValueKind &VK,
6726 SourceLocation QuestionLoc) {
6728 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6729 if (!LHSResult.isUsable()) return QualType();
6732 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6733 if (!RHSResult.isUsable()) return QualType();
6736 // C++ is sufficiently different to merit its own checker.
6737 if (getLangOpts().CPlusPlus)
6738 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6743 // The OpenCL operator with a vector condition is sufficiently
6744 // different to merit its own checker.
6745 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6746 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6748 // First, check the condition.
6749 Cond = UsualUnaryConversions(Cond.get());
6750 if (Cond.isInvalid())
6752 if (checkCondition(*this, Cond.get(), QuestionLoc))
6755 // Now check the two expressions.
6756 if (LHS.get()->getType()->isVectorType() ||
6757 RHS.get()->getType()->isVectorType())
6758 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6759 /*AllowBothBool*/true,
6760 /*AllowBoolConversions*/false);
6762 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6763 if (LHS.isInvalid() || RHS.isInvalid())
6766 QualType LHSTy = LHS.get()->getType();
6767 QualType RHSTy = RHS.get()->getType();
6769 // Diagnose attempts to convert between __float128 and long double where
6770 // such conversions currently can't be handled.
6771 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6773 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6774 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6778 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6779 // selection operator (?:).
6780 if (getLangOpts().OpenCL &&
6781 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6785 // If both operands have arithmetic type, do the usual arithmetic conversions
6786 // to find a common type: C99 6.5.15p3,5.
6787 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6788 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6789 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6794 // If both operands are the same structure or union type, the result is that
6796 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6797 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6798 if (LHSRT->getDecl() == RHSRT->getDecl())
6799 // "If both the operands have structure or union type, the result has
6800 // that type." This implies that CV qualifiers are dropped.
6801 return LHSTy.getUnqualifiedType();
6802 // FIXME: Type of conditional expression must be complete in C mode.
6805 // C99 6.5.15p5: "If both operands have void type, the result has void type."
6806 // The following || allows only one side to be void (a GCC-ism).
6807 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6808 return checkConditionalVoidType(*this, LHS, RHS);
6811 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6812 // the type of the other operand."
6813 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6814 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6816 // All objective-c pointer type analysis is done here.
6817 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6819 if (LHS.isInvalid() || RHS.isInvalid())
6821 if (!compositeType.isNull())
6822 return compositeType;
6825 // Handle block pointer types.
6826 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6827 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6830 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6831 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6832 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6835 // GCC compatibility: soften pointer/integer mismatch. Note that
6836 // null pointers have been filtered out by this point.
6837 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6838 /*isIntFirstExpr=*/true))
6840 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6841 /*isIntFirstExpr=*/false))
6844 // Emit a better diagnostic if one of the expressions is a null pointer
6845 // constant and the other is not a pointer type. In this case, the user most
6846 // likely forgot to take the address of the other expression.
6847 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6850 // Otherwise, the operands are not compatible.
6851 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6852 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6853 << RHS.get()->getSourceRange();
6857 /// FindCompositeObjCPointerType - Helper method to find composite type of
6858 /// two objective-c pointer types of the two input expressions.
6859 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6860 SourceLocation QuestionLoc) {
6861 QualType LHSTy = LHS.get()->getType();
6862 QualType RHSTy = RHS.get()->getType();
6864 // Handle things like Class and struct objc_class*. Here we case the result
6865 // to the pseudo-builtin, because that will be implicitly cast back to the
6866 // redefinition type if an attempt is made to access its fields.
6867 if (LHSTy->isObjCClassType() &&
6868 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6869 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6872 if (RHSTy->isObjCClassType() &&
6873 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6874 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6877 // And the same for struct objc_object* / id
6878 if (LHSTy->isObjCIdType() &&
6879 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6880 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6883 if (RHSTy->isObjCIdType() &&
6884 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6885 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6888 // And the same for struct objc_selector* / SEL
6889 if (Context.isObjCSelType(LHSTy) &&
6890 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6891 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6894 if (Context.isObjCSelType(RHSTy) &&
6895 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6896 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6899 // Check constraints for Objective-C object pointers types.
6900 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6902 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6903 // Two identical object pointer types are always compatible.
6906 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6907 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6908 QualType compositeType = LHSTy;
6910 // If both operands are interfaces and either operand can be
6911 // assigned to the other, use that type as the composite
6912 // type. This allows
6913 // xxx ? (A*) a : (B*) b
6914 // where B is a subclass of A.
6916 // Additionally, as for assignment, if either type is 'id'
6917 // allow silent coercion. Finally, if the types are
6918 // incompatible then make sure to use 'id' as the composite
6919 // type so the result is acceptable for sending messages to.
6921 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6922 // It could return the composite type.
6923 if (!(compositeType =
6924 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6925 // Nothing more to do.
6926 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6927 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6928 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6929 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6930 } else if ((LHSTy->isObjCQualifiedIdType() ||
6931 RHSTy->isObjCQualifiedIdType()) &&
6932 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6933 // Need to handle "id<xx>" explicitly.
6934 // GCC allows qualified id and any Objective-C type to devolve to
6935 // id. Currently localizing to here until clear this should be
6936 // part of ObjCQualifiedIdTypesAreCompatible.
6937 compositeType = Context.getObjCIdType();
6938 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6939 compositeType = Context.getObjCIdType();
6941 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6943 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6944 QualType incompatTy = Context.getObjCIdType();
6945 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6946 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6949 // The object pointer types are compatible.
6950 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6951 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6952 return compositeType;
6954 // Check Objective-C object pointer types and 'void *'
6955 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6956 if (getLangOpts().ObjCAutoRefCount) {
6957 // ARC forbids the implicit conversion of object pointers to 'void *',
6958 // so these types are not compatible.
6959 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6960 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6964 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6965 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6966 QualType destPointee
6967 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6968 QualType destType = Context.getPointerType(destPointee);
6969 // Add qualifiers if necessary.
6970 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6971 // Promote to void*.
6972 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6975 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6976 if (getLangOpts().ObjCAutoRefCount) {
6977 // ARC forbids the implicit conversion of object pointers to 'void *',
6978 // so these types are not compatible.
6979 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6980 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6984 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6985 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6986 QualType destPointee
6987 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6988 QualType destType = Context.getPointerType(destPointee);
6989 // Add qualifiers if necessary.
6990 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6991 // Promote to void*.
6992 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6998 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6999 /// ParenRange in parentheses.
7000 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7001 const PartialDiagnostic &Note,
7002 SourceRange ParenRange) {
7003 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7004 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7006 Self.Diag(Loc, Note)
7007 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7008 << FixItHint::CreateInsertion(EndLoc, ")");
7010 // We can't display the parentheses, so just show the bare note.
7011 Self.Diag(Loc, Note) << ParenRange;
7015 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7016 return BinaryOperator::isAdditiveOp(Opc) ||
7017 BinaryOperator::isMultiplicativeOp(Opc) ||
7018 BinaryOperator::isShiftOp(Opc);
7021 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7022 /// expression, either using a built-in or overloaded operator,
7023 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7025 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7027 // Don't strip parenthesis: we should not warn if E is in parenthesis.
7028 E = E->IgnoreImpCasts();
7029 E = E->IgnoreConversionOperator();
7030 E = E->IgnoreImpCasts();
7032 // Built-in binary operator.
7033 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7034 if (IsArithmeticOp(OP->getOpcode())) {
7035 *Opcode = OP->getOpcode();
7036 *RHSExprs = OP->getRHS();
7041 // Overloaded operator.
7042 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7043 if (Call->getNumArgs() != 2)
7046 // Make sure this is really a binary operator that is safe to pass into
7047 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7048 OverloadedOperatorKind OO = Call->getOperator();
7049 if (OO < OO_Plus || OO > OO_Arrow ||
7050 OO == OO_PlusPlus || OO == OO_MinusMinus)
7053 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7054 if (IsArithmeticOp(OpKind)) {
7056 *RHSExprs = Call->getArg(1);
7064 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7065 /// or is a logical expression such as (x==y) which has int type, but is
7066 /// commonly interpreted as boolean.
7067 static bool ExprLooksBoolean(Expr *E) {
7068 E = E->IgnoreParenImpCasts();
7070 if (E->getType()->isBooleanType())
7072 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7073 return OP->isComparisonOp() || OP->isLogicalOp();
7074 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7075 return OP->getOpcode() == UO_LNot;
7076 if (E->getType()->isPointerType())
7082 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7083 /// and binary operator are mixed in a way that suggests the programmer assumed
7084 /// the conditional operator has higher precedence, for example:
7085 /// "int x = a + someBinaryCondition ? 1 : 2".
7086 static void DiagnoseConditionalPrecedence(Sema &Self,
7087 SourceLocation OpLoc,
7091 BinaryOperatorKind CondOpcode;
7094 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7096 if (!ExprLooksBoolean(CondRHS))
7099 // The condition is an arithmetic binary expression, with a right-
7100 // hand side that looks boolean, so warn.
7102 Self.Diag(OpLoc, diag::warn_precedence_conditional)
7103 << Condition->getSourceRange()
7104 << BinaryOperator::getOpcodeStr(CondOpcode);
7106 SuggestParentheses(Self, OpLoc,
7107 Self.PDiag(diag::note_precedence_silence)
7108 << BinaryOperator::getOpcodeStr(CondOpcode),
7109 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7111 SuggestParentheses(Self, OpLoc,
7112 Self.PDiag(diag::note_precedence_conditional_first),
7113 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7116 /// Compute the nullability of a conditional expression.
7117 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7118 QualType LHSTy, QualType RHSTy,
7120 if (!ResTy->isAnyPointerType())
7123 auto GetNullability = [&Ctx](QualType Ty) {
7124 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7127 return NullabilityKind::Unspecified;
7130 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7131 NullabilityKind MergedKind;
7133 // Compute nullability of a binary conditional expression.
7135 if (LHSKind == NullabilityKind::NonNull)
7136 MergedKind = NullabilityKind::NonNull;
7138 MergedKind = RHSKind;
7139 // Compute nullability of a normal conditional expression.
7141 if (LHSKind == NullabilityKind::Nullable ||
7142 RHSKind == NullabilityKind::Nullable)
7143 MergedKind = NullabilityKind::Nullable;
7144 else if (LHSKind == NullabilityKind::NonNull)
7145 MergedKind = RHSKind;
7146 else if (RHSKind == NullabilityKind::NonNull)
7147 MergedKind = LHSKind;
7149 MergedKind = NullabilityKind::Unspecified;
7152 // Return if ResTy already has the correct nullability.
7153 if (GetNullability(ResTy) == MergedKind)
7156 // Strip all nullability from ResTy.
7157 while (ResTy->getNullability(Ctx))
7158 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7160 // Create a new AttributedType with the new nullability kind.
7161 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7162 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7165 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7166 /// in the case of a the GNU conditional expr extension.
7167 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7168 SourceLocation ColonLoc,
7169 Expr *CondExpr, Expr *LHSExpr,
7171 if (!getLangOpts().CPlusPlus) {
7172 // C cannot handle TypoExpr nodes in the condition because it
7173 // doesn't handle dependent types properly, so make sure any TypoExprs have
7174 // been dealt with before checking the operands.
7175 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7176 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7177 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7179 if (!CondResult.isUsable())
7183 if (!LHSResult.isUsable())
7187 if (!RHSResult.isUsable())
7190 CondExpr = CondResult.get();
7191 LHSExpr = LHSResult.get();
7192 RHSExpr = RHSResult.get();
7195 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7196 // was the condition.
7197 OpaqueValueExpr *opaqueValue = nullptr;
7198 Expr *commonExpr = nullptr;
7200 commonExpr = CondExpr;
7201 // Lower out placeholder types first. This is important so that we don't
7202 // try to capture a placeholder. This happens in few cases in C++; such
7203 // as Objective-C++'s dictionary subscripting syntax.
7204 if (commonExpr->hasPlaceholderType()) {
7205 ExprResult result = CheckPlaceholderExpr(commonExpr);
7206 if (!result.isUsable()) return ExprError();
7207 commonExpr = result.get();
7209 // We usually want to apply unary conversions *before* saving, except
7210 // in the special case of a C++ l-value conditional.
7211 if (!(getLangOpts().CPlusPlus
7212 && !commonExpr->isTypeDependent()
7213 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7214 && commonExpr->isGLValue()
7215 && commonExpr->isOrdinaryOrBitFieldObject()
7216 && RHSExpr->isOrdinaryOrBitFieldObject()
7217 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7218 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7219 if (commonRes.isInvalid())
7221 commonExpr = commonRes.get();
7224 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7225 commonExpr->getType(),
7226 commonExpr->getValueKind(),
7227 commonExpr->getObjectKind(),
7229 LHSExpr = CondExpr = opaqueValue;
7232 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7233 ExprValueKind VK = VK_RValue;
7234 ExprObjectKind OK = OK_Ordinary;
7235 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7236 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7237 VK, OK, QuestionLoc);
7238 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7242 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7245 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7247 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7251 return new (Context)
7252 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7253 RHS.get(), result, VK, OK);
7255 return new (Context) BinaryConditionalOperator(
7256 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7257 ColonLoc, result, VK, OK);
7260 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7261 // being closely modeled after the C99 spec:-). The odd characteristic of this
7262 // routine is it effectively iqnores the qualifiers on the top level pointee.
7263 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7264 // FIXME: add a couple examples in this comment.
7265 static Sema::AssignConvertType
7266 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7267 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7268 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7270 // get the "pointed to" type (ignoring qualifiers at the top level)
7271 const Type *lhptee, *rhptee;
7272 Qualifiers lhq, rhq;
7273 std::tie(lhptee, lhq) =
7274 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7275 std::tie(rhptee, rhq) =
7276 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7278 Sema::AssignConvertType ConvTy = Sema::Compatible;
7280 // C99 6.5.16.1p1: This following citation is common to constraints
7281 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7282 // qualifiers of the type *pointed to* by the right;
7284 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7285 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7286 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7287 // Ignore lifetime for further calculation.
7288 lhq.removeObjCLifetime();
7289 rhq.removeObjCLifetime();
7292 if (!lhq.compatiblyIncludes(rhq)) {
7293 // Treat address-space mismatches as fatal. TODO: address subspaces
7294 if (!lhq.isAddressSpaceSupersetOf(rhq))
7295 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7297 // It's okay to add or remove GC or lifetime qualifiers when converting to
7299 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7300 .compatiblyIncludes(
7301 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7302 && (lhptee->isVoidType() || rhptee->isVoidType()))
7305 // Treat lifetime mismatches as fatal.
7306 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7307 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7309 // For GCC/MS compatibility, other qualifier mismatches are treated
7310 // as still compatible in C.
7311 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7314 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7315 // incomplete type and the other is a pointer to a qualified or unqualified
7316 // version of void...
7317 if (lhptee->isVoidType()) {
7318 if (rhptee->isIncompleteOrObjectType())
7321 // As an extension, we allow cast to/from void* to function pointer.
7322 assert(rhptee->isFunctionType());
7323 return Sema::FunctionVoidPointer;
7326 if (rhptee->isVoidType()) {
7327 if (lhptee->isIncompleteOrObjectType())
7330 // As an extension, we allow cast to/from void* to function pointer.
7331 assert(lhptee->isFunctionType());
7332 return Sema::FunctionVoidPointer;
7335 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7336 // unqualified versions of compatible types, ...
7337 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7338 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7339 // Check if the pointee types are compatible ignoring the sign.
7340 // We explicitly check for char so that we catch "char" vs
7341 // "unsigned char" on systems where "char" is unsigned.
7342 if (lhptee->isCharType())
7343 ltrans = S.Context.UnsignedCharTy;
7344 else if (lhptee->hasSignedIntegerRepresentation())
7345 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7347 if (rhptee->isCharType())
7348 rtrans = S.Context.UnsignedCharTy;
7349 else if (rhptee->hasSignedIntegerRepresentation())
7350 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7352 if (ltrans == rtrans) {
7353 // Types are compatible ignoring the sign. Qualifier incompatibility
7354 // takes priority over sign incompatibility because the sign
7355 // warning can be disabled.
7356 if (ConvTy != Sema::Compatible)
7359 return Sema::IncompatiblePointerSign;
7362 // If we are a multi-level pointer, it's possible that our issue is simply
7363 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7364 // the eventual target type is the same and the pointers have the same
7365 // level of indirection, this must be the issue.
7366 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7368 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7369 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7370 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7372 if (lhptee == rhptee)
7373 return Sema::IncompatibleNestedPointerQualifiers;
7376 // General pointer incompatibility takes priority over qualifiers.
7377 return Sema::IncompatiblePointer;
7379 if (!S.getLangOpts().CPlusPlus &&
7380 S.IsFunctionConversion(ltrans, rtrans, ltrans))
7381 return Sema::IncompatiblePointer;
7385 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7386 /// block pointer types are compatible or whether a block and normal pointer
7387 /// are compatible. It is more restrict than comparing two function pointer
7389 static Sema::AssignConvertType
7390 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7392 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7393 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7395 QualType lhptee, rhptee;
7397 // get the "pointed to" type (ignoring qualifiers at the top level)
7398 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7399 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7401 // In C++, the types have to match exactly.
7402 if (S.getLangOpts().CPlusPlus)
7403 return Sema::IncompatibleBlockPointer;
7405 Sema::AssignConvertType ConvTy = Sema::Compatible;
7407 // For blocks we enforce that qualifiers are identical.
7408 Qualifiers LQuals = lhptee.getLocalQualifiers();
7409 Qualifiers RQuals = rhptee.getLocalQualifiers();
7410 if (S.getLangOpts().OpenCL) {
7411 LQuals.removeAddressSpace();
7412 RQuals.removeAddressSpace();
7414 if (LQuals != RQuals)
7415 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7417 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7419 // The current behavior is similar to C++ lambdas. A block might be
7420 // assigned to a variable iff its return type and parameters are compatible
7421 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7422 // an assignment. Presumably it should behave in way that a function pointer
7423 // assignment does in C, so for each parameter and return type:
7424 // * CVR and address space of LHS should be a superset of CVR and address
7426 // * unqualified types should be compatible.
7427 if (S.getLangOpts().OpenCL) {
7428 if (!S.Context.typesAreBlockPointerCompatible(
7429 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7430 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7431 return Sema::IncompatibleBlockPointer;
7432 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7433 return Sema::IncompatibleBlockPointer;
7438 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7439 /// for assignment compatibility.
7440 static Sema::AssignConvertType
7441 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7443 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7444 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7446 if (LHSType->isObjCBuiltinType()) {
7447 // Class is not compatible with ObjC object pointers.
7448 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7449 !RHSType->isObjCQualifiedClassType())
7450 return Sema::IncompatiblePointer;
7451 return Sema::Compatible;
7453 if (RHSType->isObjCBuiltinType()) {
7454 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7455 !LHSType->isObjCQualifiedClassType())
7456 return Sema::IncompatiblePointer;
7457 return Sema::Compatible;
7459 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7460 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7462 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7463 // make an exception for id<P>
7464 !LHSType->isObjCQualifiedIdType())
7465 return Sema::CompatiblePointerDiscardsQualifiers;
7467 if (S.Context.typesAreCompatible(LHSType, RHSType))
7468 return Sema::Compatible;
7469 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7470 return Sema::IncompatibleObjCQualifiedId;
7471 return Sema::IncompatiblePointer;
7474 Sema::AssignConvertType
7475 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7476 QualType LHSType, QualType RHSType) {
7477 // Fake up an opaque expression. We don't actually care about what
7478 // cast operations are required, so if CheckAssignmentConstraints
7479 // adds casts to this they'll be wasted, but fortunately that doesn't
7480 // usually happen on valid code.
7481 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7482 ExprResult RHSPtr = &RHSExpr;
7483 CastKind K = CK_Invalid;
7485 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7488 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7489 /// has code to accommodate several GCC extensions when type checking
7490 /// pointers. Here are some objectionable examples that GCC considers warnings:
7494 /// struct foo *pfoo;
7496 /// pint = pshort; // warning: assignment from incompatible pointer type
7497 /// a = pint; // warning: assignment makes integer from pointer without a cast
7498 /// pint = a; // warning: assignment makes pointer from integer without a cast
7499 /// pint = pfoo; // warning: assignment from incompatible pointer type
7501 /// As a result, the code for dealing with pointers is more complex than the
7502 /// C99 spec dictates.
7504 /// Sets 'Kind' for any result kind except Incompatible.
7505 Sema::AssignConvertType
7506 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7507 CastKind &Kind, bool ConvertRHS) {
7508 QualType RHSType = RHS.get()->getType();
7509 QualType OrigLHSType = LHSType;
7511 // Get canonical types. We're not formatting these types, just comparing
7513 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7514 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7516 // Common case: no conversion required.
7517 if (LHSType == RHSType) {
7522 // If we have an atomic type, try a non-atomic assignment, then just add an
7523 // atomic qualification step.
7524 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7525 Sema::AssignConvertType result =
7526 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7527 if (result != Compatible)
7529 if (Kind != CK_NoOp && ConvertRHS)
7530 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7531 Kind = CK_NonAtomicToAtomic;
7535 // If the left-hand side is a reference type, then we are in a
7536 // (rare!) case where we've allowed the use of references in C,
7537 // e.g., as a parameter type in a built-in function. In this case,
7538 // just make sure that the type referenced is compatible with the
7539 // right-hand side type. The caller is responsible for adjusting
7540 // LHSType so that the resulting expression does not have reference
7542 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7543 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7544 Kind = CK_LValueBitCast;
7547 return Incompatible;
7550 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7551 // to the same ExtVector type.
7552 if (LHSType->isExtVectorType()) {
7553 if (RHSType->isExtVectorType())
7554 return Incompatible;
7555 if (RHSType->isArithmeticType()) {
7556 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7558 RHS = prepareVectorSplat(LHSType, RHS.get());
7559 Kind = CK_VectorSplat;
7564 // Conversions to or from vector type.
7565 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7566 if (LHSType->isVectorType() && RHSType->isVectorType()) {
7567 // Allow assignments of an AltiVec vector type to an equivalent GCC
7568 // vector type and vice versa
7569 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7574 // If we are allowing lax vector conversions, and LHS and RHS are both
7575 // vectors, the total size only needs to be the same. This is a bitcast;
7576 // no bits are changed but the result type is different.
7577 if (isLaxVectorConversion(RHSType, LHSType)) {
7579 return IncompatibleVectors;
7583 // When the RHS comes from another lax conversion (e.g. binops between
7584 // scalars and vectors) the result is canonicalized as a vector. When the
7585 // LHS is also a vector, the lax is allowed by the condition above. Handle
7586 // the case where LHS is a scalar.
7587 if (LHSType->isScalarType()) {
7588 const VectorType *VecType = RHSType->getAs<VectorType>();
7589 if (VecType && VecType->getNumElements() == 1 &&
7590 isLaxVectorConversion(RHSType, LHSType)) {
7591 ExprResult *VecExpr = &RHS;
7592 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7598 return Incompatible;
7601 // Diagnose attempts to convert between __float128 and long double where
7602 // such conversions currently can't be handled.
7603 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7604 return Incompatible;
7606 // Arithmetic conversions.
7607 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7608 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7610 Kind = PrepareScalarCast(RHS, LHSType);
7614 // Conversions to normal pointers.
7615 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7617 if (isa<PointerType>(RHSType)) {
7618 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7619 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7620 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7621 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7625 if (RHSType->isIntegerType()) {
7626 Kind = CK_IntegralToPointer; // FIXME: null?
7627 return IntToPointer;
7630 // C pointers are not compatible with ObjC object pointers,
7631 // with two exceptions:
7632 if (isa<ObjCObjectPointerType>(RHSType)) {
7633 // - conversions to void*
7634 if (LHSPointer->getPointeeType()->isVoidType()) {
7639 // - conversions from 'Class' to the redefinition type
7640 if (RHSType->isObjCClassType() &&
7641 Context.hasSameType(LHSType,
7642 Context.getObjCClassRedefinitionType())) {
7648 return IncompatiblePointer;
7652 if (RHSType->getAs<BlockPointerType>()) {
7653 if (LHSPointer->getPointeeType()->isVoidType()) {
7654 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7655 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7659 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7664 return Incompatible;
7667 // Conversions to block pointers.
7668 if (isa<BlockPointerType>(LHSType)) {
7670 if (RHSType->isBlockPointerType()) {
7671 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7674 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7677 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7678 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7681 // int or null -> T^
7682 if (RHSType->isIntegerType()) {
7683 Kind = CK_IntegralToPointer; // FIXME: null
7684 return IntToBlockPointer;
7688 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7689 Kind = CK_AnyPointerToBlockPointerCast;
7694 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7695 if (RHSPT->getPointeeType()->isVoidType()) {
7696 Kind = CK_AnyPointerToBlockPointerCast;
7700 return Incompatible;
7703 // Conversions to Objective-C pointers.
7704 if (isa<ObjCObjectPointerType>(LHSType)) {
7706 if (RHSType->isObjCObjectPointerType()) {
7708 Sema::AssignConvertType result =
7709 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7710 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7711 result == Compatible &&
7712 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7713 result = IncompatibleObjCWeakRef;
7717 // int or null -> A*
7718 if (RHSType->isIntegerType()) {
7719 Kind = CK_IntegralToPointer; // FIXME: null
7720 return IntToPointer;
7723 // In general, C pointers are not compatible with ObjC object pointers,
7724 // with two exceptions:
7725 if (isa<PointerType>(RHSType)) {
7726 Kind = CK_CPointerToObjCPointerCast;
7728 // - conversions from 'void*'
7729 if (RHSType->isVoidPointerType()) {
7733 // - conversions to 'Class' from its redefinition type
7734 if (LHSType->isObjCClassType() &&
7735 Context.hasSameType(RHSType,
7736 Context.getObjCClassRedefinitionType())) {
7740 return IncompatiblePointer;
7743 // Only under strict condition T^ is compatible with an Objective-C pointer.
7744 if (RHSType->isBlockPointerType() &&
7745 LHSType->isBlockCompatibleObjCPointerType(Context)) {
7747 maybeExtendBlockObject(RHS);
7748 Kind = CK_BlockPointerToObjCPointerCast;
7752 return Incompatible;
7755 // Conversions from pointers that are not covered by the above.
7756 if (isa<PointerType>(RHSType)) {
7758 if (LHSType == Context.BoolTy) {
7759 Kind = CK_PointerToBoolean;
7764 if (LHSType->isIntegerType()) {
7765 Kind = CK_PointerToIntegral;
7766 return PointerToInt;
7769 return Incompatible;
7772 // Conversions from Objective-C pointers that are not covered by the above.
7773 if (isa<ObjCObjectPointerType>(RHSType)) {
7775 if (LHSType == Context.BoolTy) {
7776 Kind = CK_PointerToBoolean;
7781 if (LHSType->isIntegerType()) {
7782 Kind = CK_PointerToIntegral;
7783 return PointerToInt;
7786 return Incompatible;
7789 // struct A -> struct B
7790 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7791 if (Context.typesAreCompatible(LHSType, RHSType)) {
7797 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7798 Kind = CK_IntToOCLSampler;
7802 return Incompatible;
7805 /// \brief Constructs a transparent union from an expression that is
7806 /// used to initialize the transparent union.
7807 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7808 ExprResult &EResult, QualType UnionType,
7810 // Build an initializer list that designates the appropriate member
7811 // of the transparent union.
7812 Expr *E = EResult.get();
7813 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7814 E, SourceLocation());
7815 Initializer->setType(UnionType);
7816 Initializer->setInitializedFieldInUnion(Field);
7818 // Build a compound literal constructing a value of the transparent
7819 // union type from this initializer list.
7820 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7821 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7822 VK_RValue, Initializer, false);
7825 Sema::AssignConvertType
7826 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7828 QualType RHSType = RHS.get()->getType();
7830 // If the ArgType is a Union type, we want to handle a potential
7831 // transparent_union GCC extension.
7832 const RecordType *UT = ArgType->getAsUnionType();
7833 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7834 return Incompatible;
7836 // The field to initialize within the transparent union.
7837 RecordDecl *UD = UT->getDecl();
7838 FieldDecl *InitField = nullptr;
7839 // It's compatible if the expression matches any of the fields.
7840 for (auto *it : UD->fields()) {
7841 if (it->getType()->isPointerType()) {
7842 // If the transparent union contains a pointer type, we allow:
7844 // 2) null pointer constant
7845 if (RHSType->isPointerType())
7846 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7847 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7852 if (RHS.get()->isNullPointerConstant(Context,
7853 Expr::NPC_ValueDependentIsNull)) {
7854 RHS = ImpCastExprToType(RHS.get(), it->getType(),
7861 CastKind Kind = CK_Invalid;
7862 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7864 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7871 return Incompatible;
7873 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7877 Sema::AssignConvertType
7878 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7880 bool DiagnoseCFAudited,
7882 // We need to be able to tell the caller whether we diagnosed a problem, if
7883 // they ask us to issue diagnostics.
7884 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7886 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7887 // we can't avoid *all* modifications at the moment, so we need some somewhere
7888 // to put the updated value.
7889 ExprResult LocalRHS = CallerRHS;
7890 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7892 if (getLangOpts().CPlusPlus) {
7893 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7894 // C++ 5.17p3: If the left operand is not of class type, the
7895 // expression is implicitly converted (C++ 4) to the
7896 // cv-unqualified type of the left operand.
7897 QualType RHSType = RHS.get()->getType();
7899 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7902 ImplicitConversionSequence ICS =
7903 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7904 /*SuppressUserConversions=*/false,
7905 /*AllowExplicit=*/false,
7906 /*InOverloadResolution=*/false,
7908 /*AllowObjCWritebackConversion=*/false);
7909 if (ICS.isFailure())
7910 return Incompatible;
7911 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7914 if (RHS.isInvalid())
7915 return Incompatible;
7916 Sema::AssignConvertType result = Compatible;
7917 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7918 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7919 result = IncompatibleObjCWeakRef;
7923 // FIXME: Currently, we fall through and treat C++ classes like C
7925 // FIXME: We also fall through for atomics; not sure what should
7926 // happen there, though.
7927 } else if (RHS.get()->getType() == Context.OverloadTy) {
7928 // As a set of extensions to C, we support overloading on functions. These
7929 // functions need to be resolved here.
7931 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7932 RHS.get(), LHSType, /*Complain=*/false, DAP))
7933 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7935 return Incompatible;
7938 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7939 // a null pointer constant.
7940 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7941 LHSType->isBlockPointerType()) &&
7942 RHS.get()->isNullPointerConstant(Context,
7943 Expr::NPC_ValueDependentIsNull)) {
7944 if (Diagnose || ConvertRHS) {
7947 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7948 /*IgnoreBaseAccess=*/false, Diagnose);
7950 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7955 // This check seems unnatural, however it is necessary to ensure the proper
7956 // conversion of functions/arrays. If the conversion were done for all
7957 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7958 // expressions that suppress this implicit conversion (&, sizeof).
7960 // Suppress this for references: C++ 8.5.3p5.
7961 if (!LHSType->isReferenceType()) {
7962 // FIXME: We potentially allocate here even if ConvertRHS is false.
7963 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7964 if (RHS.isInvalid())
7965 return Incompatible;
7968 Expr *PRE = RHS.get()->IgnoreParenCasts();
7969 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7970 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7971 if (PDecl && !PDecl->hasDefinition()) {
7972 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7973 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7977 CastKind Kind = CK_Invalid;
7978 Sema::AssignConvertType result =
7979 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7981 // C99 6.5.16.1p2: The value of the right operand is converted to the
7982 // type of the assignment expression.
7983 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7984 // so that we can use references in built-in functions even in C.
7985 // The getNonReferenceType() call makes sure that the resulting expression
7986 // does not have reference type.
7987 if (result != Incompatible && RHS.get()->getType() != LHSType) {
7988 QualType Ty = LHSType.getNonLValueExprType(Context);
7989 Expr *E = RHS.get();
7991 // Check for various Objective-C errors. If we are not reporting
7992 // diagnostics and just checking for errors, e.g., during overload
7993 // resolution, return Incompatible to indicate the failure.
7994 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7995 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7996 Diagnose, DiagnoseCFAudited) != ACR_okay) {
7998 return Incompatible;
8000 if (getLangOpts().ObjC1 &&
8001 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8002 E->getType(), E, Diagnose) ||
8003 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8005 return Incompatible;
8006 // Replace the expression with a corrected version and continue so we
8007 // can find further errors.
8013 RHS = ImpCastExprToType(E, Ty, Kind);
8018 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8020 Diag(Loc, diag::err_typecheck_invalid_operands)
8021 << LHS.get()->getType() << RHS.get()->getType()
8022 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8026 /// Try to convert a value of non-vector type to a vector type by converting
8027 /// the type to the element type of the vector and then performing a splat.
8028 /// If the language is OpenCL, we only use conversions that promote scalar
8029 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8032 /// \param scalar - if non-null, actually perform the conversions
8033 /// \return true if the operation fails (but without diagnosing the failure)
8034 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8036 QualType vectorEltTy,
8037 QualType vectorTy) {
8038 // The conversion to apply to the scalar before splatting it,
8040 CastKind scalarCast = CK_Invalid;
8042 if (vectorEltTy->isIntegralType(S.Context)) {
8043 if (!scalarTy->isIntegralType(S.Context))
8045 if (S.getLangOpts().OpenCL &&
8046 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8048 scalarCast = CK_IntegralCast;
8049 } else if (vectorEltTy->isRealFloatingType()) {
8050 if (scalarTy->isRealFloatingType()) {
8051 if (S.getLangOpts().OpenCL &&
8052 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8054 scalarCast = CK_FloatingCast;
8056 else if (scalarTy->isIntegralType(S.Context))
8057 scalarCast = CK_IntegralToFloating;
8064 // Adjust scalar if desired.
8066 if (scalarCast != CK_Invalid)
8067 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8068 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8073 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8074 SourceLocation Loc, bool IsCompAssign,
8076 bool AllowBoolConversions) {
8077 if (!IsCompAssign) {
8078 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8079 if (LHS.isInvalid())
8082 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8083 if (RHS.isInvalid())
8086 // For conversion purposes, we ignore any qualifiers.
8087 // For example, "const float" and "float" are equivalent.
8088 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8089 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8091 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8092 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8093 assert(LHSVecType || RHSVecType);
8095 // AltiVec-style "vector bool op vector bool" combinations are allowed
8096 // for some operators but not others.
8097 if (!AllowBothBool &&
8098 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8099 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8100 return InvalidOperands(Loc, LHS, RHS);
8102 // If the vector types are identical, return.
8103 if (Context.hasSameType(LHSType, RHSType))
8106 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8107 if (LHSVecType && RHSVecType &&
8108 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8109 if (isa<ExtVectorType>(LHSVecType)) {
8110 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8115 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8119 // AllowBoolConversions says that bool and non-bool AltiVec vectors
8120 // can be mixed, with the result being the non-bool type. The non-bool
8121 // operand must have integer element type.
8122 if (AllowBoolConversions && LHSVecType && RHSVecType &&
8123 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8124 (Context.getTypeSize(LHSVecType->getElementType()) ==
8125 Context.getTypeSize(RHSVecType->getElementType()))) {
8126 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8127 LHSVecType->getElementType()->isIntegerType() &&
8128 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8129 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8132 if (!IsCompAssign &&
8133 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8134 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8135 RHSVecType->getElementType()->isIntegerType()) {
8136 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8141 // If there's an ext-vector type and a scalar, try to convert the scalar to
8142 // the vector element type and splat.
8143 // FIXME: this should also work for regular vector types as supported in GCC.
8144 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8145 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8146 LHSVecType->getElementType(), LHSType))
8149 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8150 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8151 LHSType, RHSVecType->getElementType(),
8156 // FIXME: The code below also handles conversion between vectors and
8157 // non-scalars, we should break this down into fine grained specific checks
8158 // and emit proper diagnostics.
8159 QualType VecType = LHSVecType ? LHSType : RHSType;
8160 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8161 QualType OtherType = LHSVecType ? RHSType : LHSType;
8162 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8163 if (isLaxVectorConversion(OtherType, VecType)) {
8164 // If we're allowing lax vector conversions, only the total (data) size
8165 // needs to be the same. For non compound assignment, if one of the types is
8166 // scalar, the result is always the vector type.
8167 if (!IsCompAssign) {
8168 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8170 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8171 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8172 // type. Note that this is already done by non-compound assignments in
8173 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8174 // <1 x T> -> T. The result is also a vector type.
8175 } else if (OtherType->isExtVectorType() ||
8176 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8177 ExprResult *RHSExpr = &RHS;
8178 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8183 // Okay, the expression is invalid.
8185 // If there's a non-vector, non-real operand, diagnose that.
8186 if ((!RHSVecType && !RHSType->isRealType()) ||
8187 (!LHSVecType && !LHSType->isRealType())) {
8188 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8189 << LHSType << RHSType
8190 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8194 // OpenCL V1.1 6.2.6.p1:
8195 // If the operands are of more than one vector type, then an error shall
8196 // occur. Implicit conversions between vector types are not permitted, per
8198 if (getLangOpts().OpenCL &&
8199 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8200 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8201 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8206 // Otherwise, use the generic diagnostic.
8207 Diag(Loc, diag::err_typecheck_vector_not_convertable)
8208 << LHSType << RHSType
8209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8213 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8214 // expression. These are mainly cases where the null pointer is used as an
8215 // integer instead of a pointer.
8216 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8217 SourceLocation Loc, bool IsCompare) {
8218 // The canonical way to check for a GNU null is with isNullPointerConstant,
8219 // but we use a bit of a hack here for speed; this is a relatively
8220 // hot path, and isNullPointerConstant is slow.
8221 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8222 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8224 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8226 // Avoid analyzing cases where the result will either be invalid (and
8227 // diagnosed as such) or entirely valid and not something to warn about.
8228 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8229 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8232 // Comparison operations would not make sense with a null pointer no matter
8233 // what the other expression is.
8235 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8236 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8237 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8241 // The rest of the operations only make sense with a null pointer
8242 // if the other expression is a pointer.
8243 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8244 NonNullType->canDecayToPointerType())
8247 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8248 << LHSNull /* LHS is NULL */ << NonNullType
8249 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8252 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8254 SourceLocation Loc, bool IsDiv) {
8255 // Check for division/remainder by zero.
8256 llvm::APSInt RHSValue;
8257 if (!RHS.get()->isValueDependent() &&
8258 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8259 S.DiagRuntimeBehavior(Loc, RHS.get(),
8260 S.PDiag(diag::warn_remainder_division_by_zero)
8261 << IsDiv << RHS.get()->getSourceRange());
8264 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8266 bool IsCompAssign, bool IsDiv) {
8267 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8269 if (LHS.get()->getType()->isVectorType() ||
8270 RHS.get()->getType()->isVectorType())
8271 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8272 /*AllowBothBool*/getLangOpts().AltiVec,
8273 /*AllowBoolConversions*/false);
8275 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8276 if (LHS.isInvalid() || RHS.isInvalid())
8280 if (compType.isNull() || !compType->isArithmeticType())
8281 return InvalidOperands(Loc, LHS, RHS);
8283 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8287 QualType Sema::CheckRemainderOperands(
8288 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8289 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8291 if (LHS.get()->getType()->isVectorType() ||
8292 RHS.get()->getType()->isVectorType()) {
8293 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8294 RHS.get()->getType()->hasIntegerRepresentation())
8295 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8296 /*AllowBothBool*/getLangOpts().AltiVec,
8297 /*AllowBoolConversions*/false);
8298 return InvalidOperands(Loc, LHS, RHS);
8301 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8302 if (LHS.isInvalid() || RHS.isInvalid())
8305 if (compType.isNull() || !compType->isIntegerType())
8306 return InvalidOperands(Loc, LHS, RHS);
8307 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8311 /// \brief Diagnose invalid arithmetic on two void pointers.
8312 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8313 Expr *LHSExpr, Expr *RHSExpr) {
8314 S.Diag(Loc, S.getLangOpts().CPlusPlus
8315 ? diag::err_typecheck_pointer_arith_void_type
8316 : diag::ext_gnu_void_ptr)
8317 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8318 << RHSExpr->getSourceRange();
8321 /// \brief Diagnose invalid arithmetic on a void pointer.
8322 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8324 S.Diag(Loc, S.getLangOpts().CPlusPlus
8325 ? diag::err_typecheck_pointer_arith_void_type
8326 : diag::ext_gnu_void_ptr)
8327 << 0 /* one pointer */ << Pointer->getSourceRange();
8330 /// \brief Diagnose invalid arithmetic on two function pointers.
8331 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8332 Expr *LHS, Expr *RHS) {
8333 assert(LHS->getType()->isAnyPointerType());
8334 assert(RHS->getType()->isAnyPointerType());
8335 S.Diag(Loc, S.getLangOpts().CPlusPlus
8336 ? diag::err_typecheck_pointer_arith_function_type
8337 : diag::ext_gnu_ptr_func_arith)
8338 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8339 // We only show the second type if it differs from the first.
8340 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8342 << RHS->getType()->getPointeeType()
8343 << LHS->getSourceRange() << RHS->getSourceRange();
8346 /// \brief Diagnose invalid arithmetic on a function pointer.
8347 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8349 assert(Pointer->getType()->isAnyPointerType());
8350 S.Diag(Loc, S.getLangOpts().CPlusPlus
8351 ? diag::err_typecheck_pointer_arith_function_type
8352 : diag::ext_gnu_ptr_func_arith)
8353 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8354 << 0 /* one pointer, so only one type */
8355 << Pointer->getSourceRange();
8358 /// \brief Emit error if Operand is incomplete pointer type
8360 /// \returns True if pointer has incomplete type
8361 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8363 QualType ResType = Operand->getType();
8364 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8365 ResType = ResAtomicType->getValueType();
8367 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8368 QualType PointeeTy = ResType->getPointeeType();
8369 return S.RequireCompleteType(Loc, PointeeTy,
8370 diag::err_typecheck_arithmetic_incomplete_type,
8371 PointeeTy, Operand->getSourceRange());
8374 /// \brief Check the validity of an arithmetic pointer operand.
8376 /// If the operand has pointer type, this code will check for pointer types
8377 /// which are invalid in arithmetic operations. These will be diagnosed
8378 /// appropriately, including whether or not the use is supported as an
8381 /// \returns True when the operand is valid to use (even if as an extension).
8382 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8384 QualType ResType = Operand->getType();
8385 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8386 ResType = ResAtomicType->getValueType();
8388 if (!ResType->isAnyPointerType()) return true;
8390 QualType PointeeTy = ResType->getPointeeType();
8391 if (PointeeTy->isVoidType()) {
8392 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8393 return !S.getLangOpts().CPlusPlus;
8395 if (PointeeTy->isFunctionType()) {
8396 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8397 return !S.getLangOpts().CPlusPlus;
8400 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8405 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8408 /// This routine will diagnose any invalid arithmetic on pointer operands much
8409 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8410 /// for emitting a single diagnostic even for operations where both LHS and RHS
8411 /// are (potentially problematic) pointers.
8413 /// \returns True when the operand is valid to use (even if as an extension).
8414 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8415 Expr *LHSExpr, Expr *RHSExpr) {
8416 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8417 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8418 if (!isLHSPointer && !isRHSPointer) return true;
8420 QualType LHSPointeeTy, RHSPointeeTy;
8421 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8422 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8424 // if both are pointers check if operation is valid wrt address spaces
8425 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8426 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8427 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8428 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8430 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8431 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8432 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8437 // Check for arithmetic on pointers to incomplete types.
8438 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8439 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8440 if (isLHSVoidPtr || isRHSVoidPtr) {
8441 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8442 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8443 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8445 return !S.getLangOpts().CPlusPlus;
8448 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8449 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8450 if (isLHSFuncPtr || isRHSFuncPtr) {
8451 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8452 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8454 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8456 return !S.getLangOpts().CPlusPlus;
8459 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8461 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8467 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8469 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8470 Expr *LHSExpr, Expr *RHSExpr) {
8471 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8472 Expr* IndexExpr = RHSExpr;
8474 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8475 IndexExpr = LHSExpr;
8478 bool IsStringPlusInt = StrExpr &&
8479 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8480 if (!IsStringPlusInt || IndexExpr->isValueDependent())
8484 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8485 unsigned StrLenWithNull = StrExpr->getLength() + 1;
8486 if (index.isNonNegative() &&
8487 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8488 index.isUnsigned()))
8492 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8493 Self.Diag(OpLoc, diag::warn_string_plus_int)
8494 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8496 // Only print a fixit for "str" + int, not for int + "str".
8497 if (IndexExpr == RHSExpr) {
8498 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8499 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8500 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8501 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8502 << FixItHint::CreateInsertion(EndLoc, "]");
8504 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8507 /// \brief Emit a warning when adding a char literal to a string.
8508 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8509 Expr *LHSExpr, Expr *RHSExpr) {
8510 const Expr *StringRefExpr = LHSExpr;
8511 const CharacterLiteral *CharExpr =
8512 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8515 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8516 StringRefExpr = RHSExpr;
8519 if (!CharExpr || !StringRefExpr)
8522 const QualType StringType = StringRefExpr->getType();
8524 // Return if not a PointerType.
8525 if (!StringType->isAnyPointerType())
8528 // Return if not a CharacterType.
8529 if (!StringType->getPointeeType()->isAnyCharacterType())
8532 ASTContext &Ctx = Self.getASTContext();
8533 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8535 const QualType CharType = CharExpr->getType();
8536 if (!CharType->isAnyCharacterType() &&
8537 CharType->isIntegerType() &&
8538 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8539 Self.Diag(OpLoc, diag::warn_string_plus_char)
8540 << DiagRange << Ctx.CharTy;
8542 Self.Diag(OpLoc, diag::warn_string_plus_char)
8543 << DiagRange << CharExpr->getType();
8546 // Only print a fixit for str + char, not for char + str.
8547 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8548 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8549 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8550 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8551 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8552 << FixItHint::CreateInsertion(EndLoc, "]");
8554 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8558 /// \brief Emit error when two pointers are incompatible.
8559 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8560 Expr *LHSExpr, Expr *RHSExpr) {
8561 assert(LHSExpr->getType()->isAnyPointerType());
8562 assert(RHSExpr->getType()->isAnyPointerType());
8563 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8564 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8565 << RHSExpr->getSourceRange();
8569 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8570 SourceLocation Loc, BinaryOperatorKind Opc,
8571 QualType* CompLHSTy) {
8572 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8574 if (LHS.get()->getType()->isVectorType() ||
8575 RHS.get()->getType()->isVectorType()) {
8576 QualType compType = CheckVectorOperands(
8577 LHS, RHS, Loc, CompLHSTy,
8578 /*AllowBothBool*/getLangOpts().AltiVec,
8579 /*AllowBoolConversions*/getLangOpts().ZVector);
8580 if (CompLHSTy) *CompLHSTy = compType;
8584 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8585 if (LHS.isInvalid() || RHS.isInvalid())
8588 // Diagnose "string literal" '+' int and string '+' "char literal".
8589 if (Opc == BO_Add) {
8590 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8591 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8594 // handle the common case first (both operands are arithmetic).
8595 if (!compType.isNull() && compType->isArithmeticType()) {
8596 if (CompLHSTy) *CompLHSTy = compType;
8600 // Type-checking. Ultimately the pointer's going to be in PExp;
8601 // note that we bias towards the LHS being the pointer.
8602 Expr *PExp = LHS.get(), *IExp = RHS.get();
8605 if (PExp->getType()->isPointerType()) {
8606 isObjCPointer = false;
8607 } else if (PExp->getType()->isObjCObjectPointerType()) {
8608 isObjCPointer = true;
8610 std::swap(PExp, IExp);
8611 if (PExp->getType()->isPointerType()) {
8612 isObjCPointer = false;
8613 } else if (PExp->getType()->isObjCObjectPointerType()) {
8614 isObjCPointer = true;
8616 return InvalidOperands(Loc, LHS, RHS);
8619 assert(PExp->getType()->isAnyPointerType());
8621 if (!IExp->getType()->isIntegerType())
8622 return InvalidOperands(Loc, LHS, RHS);
8624 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8627 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8630 // Check array bounds for pointer arithemtic
8631 CheckArrayAccess(PExp, IExp);
8634 QualType LHSTy = Context.isPromotableBitField(LHS.get());
8635 if (LHSTy.isNull()) {
8636 LHSTy = LHS.get()->getType();
8637 if (LHSTy->isPromotableIntegerType())
8638 LHSTy = Context.getPromotedIntegerType(LHSTy);
8643 return PExp->getType();
8647 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8649 QualType* CompLHSTy) {
8650 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8652 if (LHS.get()->getType()->isVectorType() ||
8653 RHS.get()->getType()->isVectorType()) {
8654 QualType compType = CheckVectorOperands(
8655 LHS, RHS, Loc, CompLHSTy,
8656 /*AllowBothBool*/getLangOpts().AltiVec,
8657 /*AllowBoolConversions*/getLangOpts().ZVector);
8658 if (CompLHSTy) *CompLHSTy = compType;
8662 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8663 if (LHS.isInvalid() || RHS.isInvalid())
8666 // Enforce type constraints: C99 6.5.6p3.
8668 // Handle the common case first (both operands are arithmetic).
8669 if (!compType.isNull() && compType->isArithmeticType()) {
8670 if (CompLHSTy) *CompLHSTy = compType;
8674 // Either ptr - int or ptr - ptr.
8675 if (LHS.get()->getType()->isAnyPointerType()) {
8676 QualType lpointee = LHS.get()->getType()->getPointeeType();
8678 // Diagnose bad cases where we step over interface counts.
8679 if (LHS.get()->getType()->isObjCObjectPointerType() &&
8680 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8683 // The result type of a pointer-int computation is the pointer type.
8684 if (RHS.get()->getType()->isIntegerType()) {
8685 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8688 // Check array bounds for pointer arithemtic
8689 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8690 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8692 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8693 return LHS.get()->getType();
8696 // Handle pointer-pointer subtractions.
8697 if (const PointerType *RHSPTy
8698 = RHS.get()->getType()->getAs<PointerType>()) {
8699 QualType rpointee = RHSPTy->getPointeeType();
8701 if (getLangOpts().CPlusPlus) {
8702 // Pointee types must be the same: C++ [expr.add]
8703 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8704 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8707 // Pointee types must be compatible C99 6.5.6p3
8708 if (!Context.typesAreCompatible(
8709 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8710 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8711 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8716 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8717 LHS.get(), RHS.get()))
8720 // The pointee type may have zero size. As an extension, a structure or
8721 // union may have zero size or an array may have zero length. In this
8722 // case subtraction does not make sense.
8723 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8724 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8725 if (ElementSize.isZero()) {
8726 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8727 << rpointee.getUnqualifiedType()
8728 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8732 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8733 return Context.getPointerDiffType();
8737 return InvalidOperands(Loc, LHS, RHS);
8740 static bool isScopedEnumerationType(QualType T) {
8741 if (const EnumType *ET = T->getAs<EnumType>())
8742 return ET->getDecl()->isScoped();
8746 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8747 SourceLocation Loc, BinaryOperatorKind Opc,
8749 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8750 // so skip remaining warnings as we don't want to modify values within Sema.
8751 if (S.getLangOpts().OpenCL)
8755 // Check right/shifter operand
8756 if (RHS.get()->isValueDependent() ||
8757 !RHS.get()->EvaluateAsInt(Right, S.Context))
8760 if (Right.isNegative()) {
8761 S.DiagRuntimeBehavior(Loc, RHS.get(),
8762 S.PDiag(diag::warn_shift_negative)
8763 << RHS.get()->getSourceRange());
8766 llvm::APInt LeftBits(Right.getBitWidth(),
8767 S.Context.getTypeSize(LHS.get()->getType()));
8768 if (Right.uge(LeftBits)) {
8769 S.DiagRuntimeBehavior(Loc, RHS.get(),
8770 S.PDiag(diag::warn_shift_gt_typewidth)
8771 << RHS.get()->getSourceRange());
8777 // When left shifting an ICE which is signed, we can check for overflow which
8778 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8779 // integers have defined behavior modulo one more than the maximum value
8780 // representable in the result type, so never warn for those.
8782 if (LHS.get()->isValueDependent() ||
8783 LHSType->hasUnsignedIntegerRepresentation() ||
8784 !LHS.get()->EvaluateAsInt(Left, S.Context))
8787 // If LHS does not have a signed type and non-negative value
8788 // then, the behavior is undefined. Warn about it.
8789 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8790 S.DiagRuntimeBehavior(Loc, LHS.get(),
8791 S.PDiag(diag::warn_shift_lhs_negative)
8792 << LHS.get()->getSourceRange());
8796 llvm::APInt ResultBits =
8797 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8798 if (LeftBits.uge(ResultBits))
8800 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8801 Result = Result.shl(Right);
8803 // Print the bit representation of the signed integer as an unsigned
8804 // hexadecimal number.
8805 SmallString<40> HexResult;
8806 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8808 // If we are only missing a sign bit, this is less likely to result in actual
8809 // bugs -- if the result is cast back to an unsigned type, it will have the
8810 // expected value. Thus we place this behind a different warning that can be
8811 // turned off separately if needed.
8812 if (LeftBits == ResultBits - 1) {
8813 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8814 << HexResult << LHSType
8815 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8819 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8820 << HexResult.str() << Result.getMinSignedBits() << LHSType
8821 << Left.getBitWidth() << LHS.get()->getSourceRange()
8822 << RHS.get()->getSourceRange();
8825 /// \brief Return the resulting type when a vector is shifted
8826 /// by a scalar or vector shift amount.
8827 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8828 SourceLocation Loc, bool IsCompAssign) {
8829 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8830 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8831 !LHS.get()->getType()->isVectorType()) {
8832 S.Diag(Loc, diag::err_shift_rhs_only_vector)
8833 << RHS.get()->getType() << LHS.get()->getType()
8834 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8838 if (!IsCompAssign) {
8839 LHS = S.UsualUnaryConversions(LHS.get());
8840 if (LHS.isInvalid()) return QualType();
8843 RHS = S.UsualUnaryConversions(RHS.get());
8844 if (RHS.isInvalid()) return QualType();
8846 QualType LHSType = LHS.get()->getType();
8847 // Note that LHS might be a scalar because the routine calls not only in
8849 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8850 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8852 // Note that RHS might not be a vector.
8853 QualType RHSType = RHS.get()->getType();
8854 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8855 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8857 // The operands need to be integers.
8858 if (!LHSEleType->isIntegerType()) {
8859 S.Diag(Loc, diag::err_typecheck_expect_int)
8860 << LHS.get()->getType() << LHS.get()->getSourceRange();
8864 if (!RHSEleType->isIntegerType()) {
8865 S.Diag(Loc, diag::err_typecheck_expect_int)
8866 << RHS.get()->getType() << RHS.get()->getSourceRange();
8874 if (LHSEleType != RHSEleType) {
8875 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8876 LHSEleType = RHSEleType;
8879 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8880 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8882 } else if (RHSVecTy) {
8883 // OpenCL v1.1 s6.3.j says that for vector types, the operators
8884 // are applied component-wise. So if RHS is a vector, then ensure
8885 // that the number of elements is the same as LHS...
8886 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8887 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8888 << LHS.get()->getType() << RHS.get()->getType()
8889 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8892 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8893 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8894 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8895 if (LHSBT != RHSBT &&
8896 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8897 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8898 << LHS.get()->getType() << RHS.get()->getType()
8899 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8903 // ...else expand RHS to match the number of elements in LHS.
8905 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8906 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8913 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8914 SourceLocation Loc, BinaryOperatorKind Opc,
8915 bool IsCompAssign) {
8916 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8918 // Vector shifts promote their scalar inputs to vector type.
8919 if (LHS.get()->getType()->isVectorType() ||
8920 RHS.get()->getType()->isVectorType()) {
8921 if (LangOpts.ZVector) {
8922 // The shift operators for the z vector extensions work basically
8923 // like general shifts, except that neither the LHS nor the RHS is
8924 // allowed to be a "vector bool".
8925 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8926 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8927 return InvalidOperands(Loc, LHS, RHS);
8928 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8929 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8930 return InvalidOperands(Loc, LHS, RHS);
8932 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8935 // Shifts don't perform usual arithmetic conversions, they just do integer
8936 // promotions on each operand. C99 6.5.7p3
8938 // For the LHS, do usual unary conversions, but then reset them away
8939 // if this is a compound assignment.
8940 ExprResult OldLHS = LHS;
8941 LHS = UsualUnaryConversions(LHS.get());
8942 if (LHS.isInvalid())
8944 QualType LHSType = LHS.get()->getType();
8945 if (IsCompAssign) LHS = OldLHS;
8947 // The RHS is simpler.
8948 RHS = UsualUnaryConversions(RHS.get());
8949 if (RHS.isInvalid())
8951 QualType RHSType = RHS.get()->getType();
8953 // C99 6.5.7p2: Each of the operands shall have integer type.
8954 if (!LHSType->hasIntegerRepresentation() ||
8955 !RHSType->hasIntegerRepresentation())
8956 return InvalidOperands(Loc, LHS, RHS);
8958 // C++0x: Don't allow scoped enums. FIXME: Use something better than
8959 // hasIntegerRepresentation() above instead of this.
8960 if (isScopedEnumerationType(LHSType) ||
8961 isScopedEnumerationType(RHSType)) {
8962 return InvalidOperands(Loc, LHS, RHS);
8964 // Sanity-check shift operands
8965 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8967 // "The type of the result is that of the promoted left operand."
8971 static bool IsWithinTemplateSpecialization(Decl *D) {
8972 if (DeclContext *DC = D->getDeclContext()) {
8973 if (isa<ClassTemplateSpecializationDecl>(DC))
8975 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8976 return FD->isFunctionTemplateSpecialization();
8981 /// If two different enums are compared, raise a warning.
8982 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8984 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8985 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8987 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8990 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8994 // Ignore anonymous enums.
8995 if (!LHSEnumType->getDecl()->getIdentifier())
8997 if (!RHSEnumType->getDecl()->getIdentifier())
9000 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9003 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9004 << LHSStrippedType << RHSStrippedType
9005 << LHS->getSourceRange() << RHS->getSourceRange();
9008 /// \brief Diagnose bad pointer comparisons.
9009 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9010 ExprResult &LHS, ExprResult &RHS,
9012 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9013 : diag::ext_typecheck_comparison_of_distinct_pointers)
9014 << LHS.get()->getType() << RHS.get()->getType()
9015 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9018 /// \brief Returns false if the pointers are converted to a composite type,
9020 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9021 ExprResult &LHS, ExprResult &RHS) {
9022 // C++ [expr.rel]p2:
9023 // [...] Pointer conversions (4.10) and qualification
9024 // conversions (4.4) are performed on pointer operands (or on
9025 // a pointer operand and a null pointer constant) to bring
9026 // them to their composite pointer type. [...]
9028 // C++ [expr.eq]p1 uses the same notion for (in)equality
9029 // comparisons of pointers.
9031 QualType LHSType = LHS.get()->getType();
9032 QualType RHSType = RHS.get()->getType();
9033 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9034 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9036 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9038 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9039 (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9040 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9042 S.InvalidOperands(Loc, LHS, RHS);
9046 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9047 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9051 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9055 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9056 : diag::ext_typecheck_comparison_of_fptr_to_void)
9057 << LHS.get()->getType() << RHS.get()->getType()
9058 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9061 static bool isObjCObjectLiteral(ExprResult &E) {
9062 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9063 case Stmt::ObjCArrayLiteralClass:
9064 case Stmt::ObjCDictionaryLiteralClass:
9065 case Stmt::ObjCStringLiteralClass:
9066 case Stmt::ObjCBoxedExprClass:
9069 // Note that ObjCBoolLiteral is NOT an object literal!
9074 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9075 const ObjCObjectPointerType *Type =
9076 LHS->getType()->getAs<ObjCObjectPointerType>();
9078 // If this is not actually an Objective-C object, bail out.
9082 // Get the LHS object's interface type.
9083 QualType InterfaceType = Type->getPointeeType();
9085 // If the RHS isn't an Objective-C object, bail out.
9086 if (!RHS->getType()->isObjCObjectPointerType())
9089 // Try to find the -isEqual: method.
9090 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9091 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9095 if (Type->isObjCIdType()) {
9096 // For 'id', just check the global pool.
9097 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9098 /*receiverId=*/true);
9101 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9109 QualType T = Method->parameters()[0]->getType();
9110 if (!T->isObjCObjectPointerType())
9113 QualType R = Method->getReturnType();
9114 if (!R->isScalarType())
9120 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9121 FromE = FromE->IgnoreParenImpCasts();
9122 switch (FromE->getStmtClass()) {
9125 case Stmt::ObjCStringLiteralClass:
9128 case Stmt::ObjCArrayLiteralClass:
9131 case Stmt::ObjCDictionaryLiteralClass:
9132 // "dictionary literal"
9133 return LK_Dictionary;
9134 case Stmt::BlockExprClass:
9136 case Stmt::ObjCBoxedExprClass: {
9137 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9138 switch (Inner->getStmtClass()) {
9139 case Stmt::IntegerLiteralClass:
9140 case Stmt::FloatingLiteralClass:
9141 case Stmt::CharacterLiteralClass:
9142 case Stmt::ObjCBoolLiteralExprClass:
9143 case Stmt::CXXBoolLiteralExprClass:
9144 // "numeric literal"
9146 case Stmt::ImplicitCastExprClass: {
9147 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9148 // Boolean literals can be represented by implicit casts.
9149 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9162 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9163 ExprResult &LHS, ExprResult &RHS,
9164 BinaryOperator::Opcode Opc){
9167 if (isObjCObjectLiteral(LHS)) {
9168 Literal = LHS.get();
9171 Literal = RHS.get();
9175 // Don't warn on comparisons against nil.
9176 Other = Other->IgnoreParenCasts();
9177 if (Other->isNullPointerConstant(S.getASTContext(),
9178 Expr::NPC_ValueDependentIsNotNull))
9181 // This should be kept in sync with warn_objc_literal_comparison.
9182 // LK_String should always be after the other literals, since it has its own
9184 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9185 assert(LiteralKind != Sema::LK_Block);
9186 if (LiteralKind == Sema::LK_None) {
9187 llvm_unreachable("Unknown Objective-C object literal kind");
9190 if (LiteralKind == Sema::LK_String)
9191 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9192 << Literal->getSourceRange();
9194 S.Diag(Loc, diag::warn_objc_literal_comparison)
9195 << LiteralKind << Literal->getSourceRange();
9197 if (BinaryOperator::isEqualityOp(Opc) &&
9198 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9199 SourceLocation Start = LHS.get()->getLocStart();
9200 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9201 CharSourceRange OpRange =
9202 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9204 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9205 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9206 << FixItHint::CreateReplacement(OpRange, " isEqual:")
9207 << FixItHint::CreateInsertion(End, "]");
9211 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9212 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9213 ExprResult &RHS, SourceLocation Loc,
9214 BinaryOperatorKind Opc) {
9215 // Check that left hand side is !something.
9216 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9217 if (!UO || UO->getOpcode() != UO_LNot) return;
9219 // Only check if the right hand side is non-bool arithmetic type.
9220 if (RHS.get()->isKnownToHaveBooleanValue()) return;
9222 // Make sure that the something in !something is not bool.
9223 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9224 if (SubExpr->isKnownToHaveBooleanValue()) return;
9227 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9228 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9229 << Loc << IsBitwiseOp;
9231 // First note suggest !(x < y)
9232 SourceLocation FirstOpen = SubExpr->getLocStart();
9233 SourceLocation FirstClose = RHS.get()->getLocEnd();
9234 FirstClose = S.getLocForEndOfToken(FirstClose);
9235 if (FirstClose.isInvalid())
9236 FirstOpen = SourceLocation();
9237 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9239 << FixItHint::CreateInsertion(FirstOpen, "(")
9240 << FixItHint::CreateInsertion(FirstClose, ")");
9242 // Second note suggests (!x) < y
9243 SourceLocation SecondOpen = LHS.get()->getLocStart();
9244 SourceLocation SecondClose = LHS.get()->getLocEnd();
9245 SecondClose = S.getLocForEndOfToken(SecondClose);
9246 if (SecondClose.isInvalid())
9247 SecondOpen = SourceLocation();
9248 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9249 << FixItHint::CreateInsertion(SecondOpen, "(")
9250 << FixItHint::CreateInsertion(SecondClose, ")");
9253 // Get the decl for a simple expression: a reference to a variable,
9254 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9255 static ValueDecl *getCompareDecl(Expr *E) {
9256 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9257 return DR->getDecl();
9258 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9259 if (Ivar->isFreeIvar())
9260 return Ivar->getDecl();
9262 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9263 if (Mem->isImplicitAccess())
9264 return Mem->getMemberDecl();
9269 // C99 6.5.8, C++ [expr.rel]
9270 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9271 SourceLocation Loc, BinaryOperatorKind Opc,
9272 bool IsRelational) {
9273 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9275 // Handle vector comparisons separately.
9276 if (LHS.get()->getType()->isVectorType() ||
9277 RHS.get()->getType()->isVectorType())
9278 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9280 QualType LHSType = LHS.get()->getType();
9281 QualType RHSType = RHS.get()->getType();
9283 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9284 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9286 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9287 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9289 if (!LHSType->hasFloatingRepresentation() &&
9290 !(LHSType->isBlockPointerType() && IsRelational) &&
9291 !LHS.get()->getLocStart().isMacroID() &&
9292 !RHS.get()->getLocStart().isMacroID() &&
9293 !inTemplateInstantiation()) {
9294 // For non-floating point types, check for self-comparisons of the form
9295 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9296 // often indicate logic errors in the program.
9298 // NOTE: Don't warn about comparison expressions resulting from macro
9299 // expansion. Also don't warn about comparisons which are only self
9300 // comparisons within a template specialization. The warnings should catch
9301 // obvious cases in the definition of the template anyways. The idea is to
9302 // warn when the typed comparison operator will always evaluate to the same
9304 ValueDecl *DL = getCompareDecl(LHSStripped);
9305 ValueDecl *DR = getCompareDecl(RHSStripped);
9306 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9307 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9312 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9313 !DL->getType()->isReferenceType() &&
9314 !DR->getType()->isReferenceType()) {
9315 // what is it always going to eval to?
9316 char always_evals_to;
9318 case BO_EQ: // e.g. array1 == array2
9319 always_evals_to = 0; // false
9321 case BO_NE: // e.g. array1 != array2
9322 always_evals_to = 1; // true
9325 // best we can say is 'a constant'
9326 always_evals_to = 2; // e.g. array1 <= array2
9329 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9331 << always_evals_to);
9334 if (isa<CastExpr>(LHSStripped))
9335 LHSStripped = LHSStripped->IgnoreParenCasts();
9336 if (isa<CastExpr>(RHSStripped))
9337 RHSStripped = RHSStripped->IgnoreParenCasts();
9339 // Warn about comparisons against a string constant (unless the other
9340 // operand is null), the user probably wants strcmp.
9341 Expr *literalString = nullptr;
9342 Expr *literalStringStripped = nullptr;
9343 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9344 !RHSStripped->isNullPointerConstant(Context,
9345 Expr::NPC_ValueDependentIsNull)) {
9346 literalString = LHS.get();
9347 literalStringStripped = LHSStripped;
9348 } else if ((isa<StringLiteral>(RHSStripped) ||
9349 isa<ObjCEncodeExpr>(RHSStripped)) &&
9350 !LHSStripped->isNullPointerConstant(Context,
9351 Expr::NPC_ValueDependentIsNull)) {
9352 literalString = RHS.get();
9353 literalStringStripped = RHSStripped;
9356 if (literalString) {
9357 DiagRuntimeBehavior(Loc, nullptr,
9358 PDiag(diag::warn_stringcompare)
9359 << isa<ObjCEncodeExpr>(literalStringStripped)
9360 << literalString->getSourceRange());
9364 // C99 6.5.8p3 / C99 6.5.9p4
9365 UsualArithmeticConversions(LHS, RHS);
9366 if (LHS.isInvalid() || RHS.isInvalid())
9369 LHSType = LHS.get()->getType();
9370 RHSType = RHS.get()->getType();
9372 // The result of comparisons is 'bool' in C++, 'int' in C.
9373 QualType ResultTy = Context.getLogicalOperationType();
9376 if (LHSType->isRealType() && RHSType->isRealType())
9379 // Check for comparisons of floating point operands using != and ==.
9380 if (LHSType->hasFloatingRepresentation())
9381 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9383 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9387 const Expr::NullPointerConstantKind LHSNullKind =
9388 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9389 const Expr::NullPointerConstantKind RHSNullKind =
9390 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9391 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9392 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9394 if (!IsRelational && LHSIsNull != RHSIsNull) {
9395 bool IsEquality = Opc == BO_EQ;
9397 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9398 RHS.get()->getSourceRange());
9400 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9401 LHS.get()->getSourceRange());
9404 if ((LHSType->isIntegerType() && !LHSIsNull) ||
9405 (RHSType->isIntegerType() && !RHSIsNull)) {
9406 // Skip normal pointer conversion checks in this case; we have better
9407 // diagnostics for this below.
9408 } else if (getLangOpts().CPlusPlus) {
9409 // Equality comparison of a function pointer to a void pointer is invalid,
9410 // but we allow it as an extension.
9411 // FIXME: If we really want to allow this, should it be part of composite
9412 // pointer type computation so it works in conditionals too?
9413 if (!IsRelational &&
9414 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9415 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9416 // This is a gcc extension compatibility comparison.
9417 // In a SFINAE context, we treat this as a hard error to maintain
9418 // conformance with the C++ standard.
9419 diagnoseFunctionPointerToVoidComparison(
9420 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9422 if (isSFINAEContext())
9425 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9430 // If at least one operand is a pointer [...] bring them to their
9431 // composite pointer type.
9432 // C++ [expr.rel]p2:
9433 // If both operands are pointers, [...] bring them to their composite
9435 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9436 (IsRelational ? 2 : 1) &&
9437 (!LangOpts.ObjCAutoRefCount ||
9438 !(LHSType->isObjCObjectPointerType() ||
9439 RHSType->isObjCObjectPointerType()))) {
9440 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9445 } else if (LHSType->isPointerType() &&
9446 RHSType->isPointerType()) { // C99 6.5.8p2
9447 // All of the following pointer-related warnings are GCC extensions, except
9448 // when handling null pointer constants.
9449 QualType LCanPointeeTy =
9450 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9451 QualType RCanPointeeTy =
9452 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9454 // C99 6.5.9p2 and C99 6.5.8p2
9455 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9456 RCanPointeeTy.getUnqualifiedType())) {
9457 // Valid unless a relational comparison of function pointers
9458 if (IsRelational && LCanPointeeTy->isFunctionType()) {
9459 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9460 << LHSType << RHSType << LHS.get()->getSourceRange()
9461 << RHS.get()->getSourceRange();
9463 } else if (!IsRelational &&
9464 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9465 // Valid unless comparison between non-null pointer and function pointer
9466 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9467 && !LHSIsNull && !RHSIsNull)
9468 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9472 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9474 if (LCanPointeeTy != RCanPointeeTy) {
9475 // Treat NULL constant as a special case in OpenCL.
9476 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9477 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9478 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9480 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9481 << LHSType << RHSType << 0 /* comparison */
9482 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9485 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9486 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9487 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9489 if (LHSIsNull && !RHSIsNull)
9490 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9492 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9497 if (getLangOpts().CPlusPlus) {
9499 // Two operands of type std::nullptr_t or one operand of type
9500 // std::nullptr_t and the other a null pointer constant compare equal.
9501 if (!IsRelational && LHSIsNull && RHSIsNull) {
9502 if (LHSType->isNullPtrType()) {
9503 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9506 if (RHSType->isNullPtrType()) {
9507 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9512 // Comparison of Objective-C pointers and block pointers against nullptr_t.
9513 // These aren't covered by the composite pointer type rules.
9514 if (!IsRelational && RHSType->isNullPtrType() &&
9515 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9516 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9519 if (!IsRelational && LHSType->isNullPtrType() &&
9520 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9521 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9526 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9527 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9528 // HACK: Relational comparison of nullptr_t against a pointer type is
9529 // invalid per DR583, but we allow it within std::less<> and friends,
9530 // since otherwise common uses of it break.
9531 // FIXME: Consider removing this hack once LWG fixes std::less<> and
9532 // friends to have std::nullptr_t overload candidates.
9533 DeclContext *DC = CurContext;
9534 if (isa<FunctionDecl>(DC))
9535 DC = DC->getParent();
9536 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9537 if (CTSD->isInStdNamespace() &&
9538 llvm::StringSwitch<bool>(CTSD->getName())
9539 .Cases("less", "less_equal", "greater", "greater_equal", true)
9541 if (RHSType->isNullPtrType())
9542 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9544 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9551 // If at least one operand is a pointer to member, [...] bring them to
9552 // their composite pointer type.
9553 if (!IsRelational &&
9554 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9555 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9561 // Handle scoped enumeration types specifically, since they don't promote
9563 if (LHS.get()->getType()->isEnumeralType() &&
9564 Context.hasSameUnqualifiedType(LHS.get()->getType(),
9565 RHS.get()->getType()))
9569 // Handle block pointer types.
9570 if (!IsRelational && LHSType->isBlockPointerType() &&
9571 RHSType->isBlockPointerType()) {
9572 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9573 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9575 if (!LHSIsNull && !RHSIsNull &&
9576 !Context.typesAreCompatible(lpointee, rpointee)) {
9577 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9578 << LHSType << RHSType << LHS.get()->getSourceRange()
9579 << RHS.get()->getSourceRange();
9581 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9585 // Allow block pointers to be compared with null pointer constants.
9587 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9588 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9589 if (!LHSIsNull && !RHSIsNull) {
9590 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9591 ->getPointeeType()->isVoidType())
9592 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9593 ->getPointeeType()->isVoidType())))
9594 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9595 << LHSType << RHSType << LHS.get()->getSourceRange()
9596 << RHS.get()->getSourceRange();
9598 if (LHSIsNull && !RHSIsNull)
9599 LHS = ImpCastExprToType(LHS.get(), RHSType,
9600 RHSType->isPointerType() ? CK_BitCast
9601 : CK_AnyPointerToBlockPointerCast);
9603 RHS = ImpCastExprToType(RHS.get(), LHSType,
9604 LHSType->isPointerType() ? CK_BitCast
9605 : CK_AnyPointerToBlockPointerCast);
9609 if (LHSType->isObjCObjectPointerType() ||
9610 RHSType->isObjCObjectPointerType()) {
9611 const PointerType *LPT = LHSType->getAs<PointerType>();
9612 const PointerType *RPT = RHSType->getAs<PointerType>();
9614 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9615 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9617 if (!LPtrToVoid && !RPtrToVoid &&
9618 !Context.typesAreCompatible(LHSType, RHSType)) {
9619 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9622 if (LHSIsNull && !RHSIsNull) {
9623 Expr *E = LHS.get();
9624 if (getLangOpts().ObjCAutoRefCount)
9625 CheckObjCConversion(SourceRange(), RHSType, E,
9626 CCK_ImplicitConversion);
9627 LHS = ImpCastExprToType(E, RHSType,
9628 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9631 Expr *E = RHS.get();
9632 if (getLangOpts().ObjCAutoRefCount)
9633 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9635 /*DiagnoseCFAudited=*/false, Opc);
9636 RHS = ImpCastExprToType(E, LHSType,
9637 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9641 if (LHSType->isObjCObjectPointerType() &&
9642 RHSType->isObjCObjectPointerType()) {
9643 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9644 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9646 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9647 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9649 if (LHSIsNull && !RHSIsNull)
9650 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9652 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9656 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9657 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9658 unsigned DiagID = 0;
9659 bool isError = false;
9660 if (LangOpts.DebuggerSupport) {
9661 // Under a debugger, allow the comparison of pointers to integers,
9662 // since users tend to want to compare addresses.
9663 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9664 (RHSIsNull && RHSType->isIntegerType())) {
9666 isError = getLangOpts().CPlusPlus;
9668 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9669 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9671 } else if (getLangOpts().CPlusPlus) {
9672 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9674 } else if (IsRelational)
9675 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9677 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9681 << LHSType << RHSType << LHS.get()->getSourceRange()
9682 << RHS.get()->getSourceRange();
9687 if (LHSType->isIntegerType())
9688 LHS = ImpCastExprToType(LHS.get(), RHSType,
9689 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9691 RHS = ImpCastExprToType(RHS.get(), LHSType,
9692 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9696 // Handle block pointers.
9697 if (!IsRelational && RHSIsNull
9698 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9699 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9702 if (!IsRelational && LHSIsNull
9703 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9704 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9708 if (getLangOpts().OpenCLVersion >= 200) {
9709 if (LHSIsNull && RHSType->isQueueT()) {
9710 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9714 if (LHSType->isQueueT() && RHSIsNull) {
9715 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9720 return InvalidOperands(Loc, LHS, RHS);
9723 // Return a signed ext_vector_type that is of identical size and number of
9724 // elements. For floating point vectors, return an integer type of identical
9725 // size and number of elements. In the non ext_vector_type case, search from
9726 // the largest type to the smallest type to avoid cases where long long == long,
9727 // where long gets picked over long long.
9728 QualType Sema::GetSignedVectorType(QualType V) {
9729 const VectorType *VTy = V->getAs<VectorType>();
9730 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9732 if (isa<ExtVectorType>(VTy)) {
9733 if (TypeSize == Context.getTypeSize(Context.CharTy))
9734 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9735 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9736 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9737 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9738 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9739 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9740 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9741 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9742 "Unhandled vector element size in vector compare");
9743 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9746 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9747 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9748 VectorType::GenericVector);
9749 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9750 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9751 VectorType::GenericVector);
9752 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9753 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9754 VectorType::GenericVector);
9755 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9756 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9757 VectorType::GenericVector);
9758 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9759 "Unhandled vector element size in vector compare");
9760 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9761 VectorType::GenericVector);
9764 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9765 /// operates on extended vector types. Instead of producing an IntTy result,
9766 /// like a scalar comparison, a vector comparison produces a vector of integer
9768 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9770 bool IsRelational) {
9771 // Check to make sure we're operating on vectors of the same type and width,
9772 // Allowing one side to be a scalar of element type.
9773 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9774 /*AllowBothBool*/true,
9775 /*AllowBoolConversions*/getLangOpts().ZVector);
9779 QualType LHSType = LHS.get()->getType();
9781 // If AltiVec, the comparison results in a numeric type, i.e.
9782 // bool for C++, int for C
9783 if (getLangOpts().AltiVec &&
9784 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9785 return Context.getLogicalOperationType();
9787 // For non-floating point types, check for self-comparisons of the form
9788 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9789 // often indicate logic errors in the program.
9790 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9791 if (DeclRefExpr* DRL
9792 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9793 if (DeclRefExpr* DRR
9794 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9795 if (DRL->getDecl() == DRR->getDecl())
9796 DiagRuntimeBehavior(Loc, nullptr,
9797 PDiag(diag::warn_comparison_always)
9799 << 2 // "a constant"
9803 // Check for comparisons of floating point operands using != and ==.
9804 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9805 assert (RHS.get()->getType()->hasFloatingRepresentation());
9806 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9809 // Return a signed type for the vector.
9810 return GetSignedVectorType(vType);
9813 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9814 SourceLocation Loc) {
9815 // Ensure that either both operands are of the same vector type, or
9816 // one operand is of a vector type and the other is of its element type.
9817 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9818 /*AllowBothBool*/true,
9819 /*AllowBoolConversions*/false);
9821 return InvalidOperands(Loc, LHS, RHS);
9822 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9823 vType->hasFloatingRepresentation())
9824 return InvalidOperands(Loc, LHS, RHS);
9826 return GetSignedVectorType(LHS.get()->getType());
9829 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9831 BinaryOperatorKind Opc) {
9832 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9835 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9837 if (LHS.get()->getType()->isVectorType() ||
9838 RHS.get()->getType()->isVectorType()) {
9839 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9840 RHS.get()->getType()->hasIntegerRepresentation())
9841 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9842 /*AllowBothBool*/true,
9843 /*AllowBoolConversions*/getLangOpts().ZVector);
9844 return InvalidOperands(Loc, LHS, RHS);
9848 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9850 ExprResult LHSResult = LHS, RHSResult = RHS;
9851 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9853 if (LHSResult.isInvalid() || RHSResult.isInvalid())
9855 LHS = LHSResult.get();
9856 RHS = RHSResult.get();
9858 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9860 return InvalidOperands(Loc, LHS, RHS);
9864 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9866 BinaryOperatorKind Opc) {
9867 // Check vector operands differently.
9868 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9869 return CheckVectorLogicalOperands(LHS, RHS, Loc);
9871 // Diagnose cases where the user write a logical and/or but probably meant a
9872 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
9874 if (LHS.get()->getType()->isIntegerType() &&
9875 !LHS.get()->getType()->isBooleanType() &&
9876 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9877 // Don't warn in macros or template instantiations.
9878 !Loc.isMacroID() && !inTemplateInstantiation()) {
9879 // If the RHS can be constant folded, and if it constant folds to something
9880 // that isn't 0 or 1 (which indicate a potential logical operation that
9881 // happened to fold to true/false) then warn.
9882 // Parens on the RHS are ignored.
9883 llvm::APSInt Result;
9884 if (RHS.get()->EvaluateAsInt(Result, Context))
9885 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9886 !RHS.get()->getExprLoc().isMacroID()) ||
9887 (Result != 0 && Result != 1)) {
9888 Diag(Loc, diag::warn_logical_instead_of_bitwise)
9889 << RHS.get()->getSourceRange()
9890 << (Opc == BO_LAnd ? "&&" : "||");
9891 // Suggest replacing the logical operator with the bitwise version
9892 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9893 << (Opc == BO_LAnd ? "&" : "|")
9894 << FixItHint::CreateReplacement(SourceRange(
9895 Loc, getLocForEndOfToken(Loc)),
9896 Opc == BO_LAnd ? "&" : "|");
9898 // Suggest replacing "Foo() && kNonZero" with "Foo()"
9899 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9900 << FixItHint::CreateRemoval(
9901 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9902 RHS.get()->getLocEnd()));
9906 if (!Context.getLangOpts().CPlusPlus) {
9907 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9908 // not operate on the built-in scalar and vector float types.
9909 if (Context.getLangOpts().OpenCL &&
9910 Context.getLangOpts().OpenCLVersion < 120) {
9911 if (LHS.get()->getType()->isFloatingType() ||
9912 RHS.get()->getType()->isFloatingType())
9913 return InvalidOperands(Loc, LHS, RHS);
9916 LHS = UsualUnaryConversions(LHS.get());
9917 if (LHS.isInvalid())
9920 RHS = UsualUnaryConversions(RHS.get());
9921 if (RHS.isInvalid())
9924 if (!LHS.get()->getType()->isScalarType() ||
9925 !RHS.get()->getType()->isScalarType())
9926 return InvalidOperands(Loc, LHS, RHS);
9928 return Context.IntTy;
9931 // The following is safe because we only use this method for
9932 // non-overloadable operands.
9934 // C++ [expr.log.and]p1
9935 // C++ [expr.log.or]p1
9936 // The operands are both contextually converted to type bool.
9937 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9938 if (LHSRes.isInvalid())
9939 return InvalidOperands(Loc, LHS, RHS);
9942 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9943 if (RHSRes.isInvalid())
9944 return InvalidOperands(Loc, LHS, RHS);
9947 // C++ [expr.log.and]p2
9948 // C++ [expr.log.or]p2
9949 // The result is a bool.
9950 return Context.BoolTy;
9953 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9954 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9955 if (!ME) return false;
9956 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9957 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9958 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9959 if (!Base) return false;
9960 return Base->getMethodDecl() != nullptr;
9963 /// Is the given expression (which must be 'const') a reference to a
9964 /// variable which was originally non-const, but which has become
9965 /// 'const' due to being captured within a block?
9966 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9967 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9968 assert(E->isLValue() && E->getType().isConstQualified());
9969 E = E->IgnoreParens();
9971 // Must be a reference to a declaration from an enclosing scope.
9972 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9973 if (!DRE) return NCCK_None;
9974 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9976 // The declaration must be a variable which is not declared 'const'.
9977 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9978 if (!var) return NCCK_None;
9979 if (var->getType().isConstQualified()) return NCCK_None;
9980 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9982 // Decide whether the first capture was for a block or a lambda.
9983 DeclContext *DC = S.CurContext, *Prev = nullptr;
9984 // Decide whether the first capture was for a block or a lambda.
9986 // For init-capture, it is possible that the variable belongs to the
9987 // template pattern of the current context.
9988 if (auto *FD = dyn_cast<FunctionDecl>(DC))
9989 if (var->isInitCapture() &&
9990 FD->getTemplateInstantiationPattern() == var->getDeclContext())
9992 if (DC == var->getDeclContext())
9995 DC = DC->getParent();
9997 // Unless we have an init-capture, we've gone one step too far.
9998 if (!var->isInitCapture())
10000 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10003 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10004 Ty = Ty.getNonReferenceType();
10005 if (IsDereference && Ty->isPointerType())
10006 Ty = Ty->getPointeeType();
10007 return !Ty.isConstQualified();
10010 /// Emit the "read-only variable not assignable" error and print notes to give
10011 /// more information about why the variable is not assignable, such as pointing
10012 /// to the declaration of a const variable, showing that a method is const, or
10013 /// that the function is returning a const reference.
10014 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10015 SourceLocation Loc) {
10016 // Update err_typecheck_assign_const and note_typecheck_assign_const
10017 // when this enum is changed.
10023 ConstUnknown, // Keep as last element
10026 SourceRange ExprRange = E->getSourceRange();
10028 // Only emit one error on the first const found. All other consts will emit
10029 // a note to the error.
10030 bool DiagnosticEmitted = false;
10032 // Track if the current expression is the result of a dereference, and if the
10033 // next checked expression is the result of a dereference.
10034 bool IsDereference = false;
10035 bool NextIsDereference = false;
10037 // Loop to process MemberExpr chains.
10039 IsDereference = NextIsDereference;
10041 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10042 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10043 NextIsDereference = ME->isArrow();
10044 const ValueDecl *VD = ME->getMemberDecl();
10045 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10046 // Mutable fields can be modified even if the class is const.
10047 if (Field->isMutable()) {
10048 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10052 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10053 if (!DiagnosticEmitted) {
10054 S.Diag(Loc, diag::err_typecheck_assign_const)
10055 << ExprRange << ConstMember << false /*static*/ << Field
10056 << Field->getType();
10057 DiagnosticEmitted = true;
10059 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10060 << ConstMember << false /*static*/ << Field << Field->getType()
10061 << Field->getSourceRange();
10065 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10066 if (VDecl->getType().isConstQualified()) {
10067 if (!DiagnosticEmitted) {
10068 S.Diag(Loc, diag::err_typecheck_assign_const)
10069 << ExprRange << ConstMember << true /*static*/ << VDecl
10070 << VDecl->getType();
10071 DiagnosticEmitted = true;
10073 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10074 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10075 << VDecl->getSourceRange();
10077 // Static fields do not inherit constness from parents.
10081 } // End MemberExpr
10085 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10087 const FunctionDecl *FD = CE->getDirectCallee();
10088 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10089 if (!DiagnosticEmitted) {
10090 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10091 << ConstFunction << FD;
10092 DiagnosticEmitted = true;
10094 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10095 diag::note_typecheck_assign_const)
10096 << ConstFunction << FD << FD->getReturnType()
10097 << FD->getReturnTypeSourceRange();
10099 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10100 // Point to variable declaration.
10101 if (const ValueDecl *VD = DRE->getDecl()) {
10102 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10103 if (!DiagnosticEmitted) {
10104 S.Diag(Loc, diag::err_typecheck_assign_const)
10105 << ExprRange << ConstVariable << VD << VD->getType();
10106 DiagnosticEmitted = true;
10108 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10109 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10112 } else if (isa<CXXThisExpr>(E)) {
10113 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10114 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10115 if (MD->isConst()) {
10116 if (!DiagnosticEmitted) {
10117 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10118 << ConstMethod << MD;
10119 DiagnosticEmitted = true;
10121 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10122 << ConstMethod << MD << MD->getSourceRange();
10128 if (DiagnosticEmitted)
10131 // Can't determine a more specific message, so display the generic error.
10132 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10135 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
10136 /// emit an error and return true. If so, return false.
10137 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10138 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10140 S.CheckShadowingDeclModification(E, Loc);
10142 SourceLocation OrigLoc = Loc;
10143 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10145 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10146 IsLV = Expr::MLV_InvalidMessageExpression;
10147 if (IsLV == Expr::MLV_Valid)
10150 unsigned DiagID = 0;
10151 bool NeedType = false;
10152 switch (IsLV) { // C99 6.5.16p2
10153 case Expr::MLV_ConstQualified:
10154 // Use a specialized diagnostic when we're assigning to an object
10155 // from an enclosing function or block.
10156 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10157 if (NCCK == NCCK_Block)
10158 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10160 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10164 // In ARC, use some specialized diagnostics for occasions where we
10165 // infer 'const'. These are always pseudo-strong variables.
10166 if (S.getLangOpts().ObjCAutoRefCount) {
10167 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10168 if (declRef && isa<VarDecl>(declRef->getDecl())) {
10169 VarDecl *var = cast<VarDecl>(declRef->getDecl());
10171 // Use the normal diagnostic if it's pseudo-__strong but the
10172 // user actually wrote 'const'.
10173 if (var->isARCPseudoStrong() &&
10174 (!var->getTypeSourceInfo() ||
10175 !var->getTypeSourceInfo()->getType().isConstQualified())) {
10176 // There are two pseudo-strong cases:
10178 ObjCMethodDecl *method = S.getCurMethodDecl();
10179 if (method && var == method->getSelfDecl())
10180 DiagID = method->isClassMethod()
10181 ? diag::err_typecheck_arc_assign_self_class_method
10182 : diag::err_typecheck_arc_assign_self;
10184 // - fast enumeration variables
10186 DiagID = diag::err_typecheck_arr_assign_enumeration;
10188 SourceRange Assign;
10189 if (Loc != OrigLoc)
10190 Assign = SourceRange(OrigLoc, OrigLoc);
10191 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10192 // We need to preserve the AST regardless, so migration tool
10199 // If none of the special cases above are triggered, then this is a
10200 // simple const assignment.
10202 DiagnoseConstAssignment(S, E, Loc);
10207 case Expr::MLV_ConstAddrSpace:
10208 DiagnoseConstAssignment(S, E, Loc);
10210 case Expr::MLV_ArrayType:
10211 case Expr::MLV_ArrayTemporary:
10212 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10215 case Expr::MLV_NotObjectType:
10216 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10219 case Expr::MLV_LValueCast:
10220 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10222 case Expr::MLV_Valid:
10223 llvm_unreachable("did not take early return for MLV_Valid");
10224 case Expr::MLV_InvalidExpression:
10225 case Expr::MLV_MemberFunction:
10226 case Expr::MLV_ClassTemporary:
10227 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10229 case Expr::MLV_IncompleteType:
10230 case Expr::MLV_IncompleteVoidType:
10231 return S.RequireCompleteType(Loc, E->getType(),
10232 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10233 case Expr::MLV_DuplicateVectorComponents:
10234 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10236 case Expr::MLV_NoSetterProperty:
10237 llvm_unreachable("readonly properties should be processed differently");
10238 case Expr::MLV_InvalidMessageExpression:
10239 DiagID = diag::err_readonly_message_assignment;
10241 case Expr::MLV_SubObjCPropertySetting:
10242 DiagID = diag::err_no_subobject_property_setting;
10246 SourceRange Assign;
10247 if (Loc != OrigLoc)
10248 Assign = SourceRange(OrigLoc, OrigLoc);
10250 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10252 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10256 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10257 SourceLocation Loc,
10260 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10261 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10262 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10263 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10264 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10267 // Objective-C instance variables
10268 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10269 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10270 if (OL && OR && OL->getDecl() == OR->getDecl()) {
10271 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10272 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10273 if (RL && RR && RL->getDecl() == RR->getDecl())
10274 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10279 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10280 SourceLocation Loc,
10281 QualType CompoundType) {
10282 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10284 // Verify that LHS is a modifiable lvalue, and emit error if not.
10285 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10288 QualType LHSType = LHSExpr->getType();
10289 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10291 // OpenCL v1.2 s6.1.1.1 p2:
10292 // The half data type can only be used to declare a pointer to a buffer that
10293 // contains half values
10294 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10295 LHSType->isHalfType()) {
10296 Diag(Loc, diag::err_opencl_half_load_store) << 1
10297 << LHSType.getUnqualifiedType();
10301 AssignConvertType ConvTy;
10302 if (CompoundType.isNull()) {
10303 Expr *RHSCheck = RHS.get();
10305 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10307 QualType LHSTy(LHSType);
10308 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10309 if (RHS.isInvalid())
10311 // Special case of NSObject attributes on c-style pointer types.
10312 if (ConvTy == IncompatiblePointer &&
10313 ((Context.isObjCNSObjectType(LHSType) &&
10314 RHSType->isObjCObjectPointerType()) ||
10315 (Context.isObjCNSObjectType(RHSType) &&
10316 LHSType->isObjCObjectPointerType())))
10317 ConvTy = Compatible;
10319 if (ConvTy == Compatible &&
10320 LHSType->isObjCObjectType())
10321 Diag(Loc, diag::err_objc_object_assignment)
10324 // If the RHS is a unary plus or minus, check to see if they = and + are
10325 // right next to each other. If so, the user may have typo'd "x =+ 4"
10326 // instead of "x += 4".
10327 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10328 RHSCheck = ICE->getSubExpr();
10329 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10330 if ((UO->getOpcode() == UO_Plus ||
10331 UO->getOpcode() == UO_Minus) &&
10332 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10333 // Only if the two operators are exactly adjacent.
10334 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10335 // And there is a space or other character before the subexpr of the
10336 // unary +/-. We don't want to warn on "x=-1".
10337 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10338 UO->getSubExpr()->getLocStart().isFileID()) {
10339 Diag(Loc, diag::warn_not_compound_assign)
10340 << (UO->getOpcode() == UO_Plus ? "+" : "-")
10341 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10345 if (ConvTy == Compatible) {
10346 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10347 // Warn about retain cycles where a block captures the LHS, but
10348 // not if the LHS is a simple variable into which the block is
10349 // being stored...unless that variable can be captured by reference!
10350 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10351 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10352 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10353 checkRetainCycles(LHSExpr, RHS.get());
10356 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10357 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10358 // It is safe to assign a weak reference into a strong variable.
10359 // Although this code can still have problems:
10360 // id x = self.weakProp;
10361 // id y = self.weakProp;
10362 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10363 // paths through the function. This should be revisited if
10364 // -Wrepeated-use-of-weak is made flow-sensitive.
10365 // For ObjCWeak only, we do not warn if the assign is to a non-weak
10366 // variable, which will be valid for the current autorelease scope.
10367 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10368 RHS.get()->getLocStart()))
10369 getCurFunction()->markSafeWeakUse(RHS.get());
10371 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10372 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10376 // Compound assignment "x += y"
10377 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10380 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10381 RHS.get(), AA_Assigning))
10384 CheckForNullPointerDereference(*this, LHSExpr);
10386 // C99 6.5.16p3: The type of an assignment expression is the type of the
10387 // left operand unless the left operand has qualified type, in which case
10388 // it is the unqualified version of the type of the left operand.
10389 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10390 // is converted to the type of the assignment expression (above).
10391 // C++ 5.17p1: the type of the assignment expression is that of its left
10393 return (getLangOpts().CPlusPlus
10394 ? LHSType : LHSType.getUnqualifiedType());
10397 // Only ignore explicit casts to void.
10398 static bool IgnoreCommaOperand(const Expr *E) {
10399 E = E->IgnoreParens();
10401 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10402 if (CE->getCastKind() == CK_ToVoid) {
10410 // Look for instances where it is likely the comma operator is confused with
10411 // another operator. There is a whitelist of acceptable expressions for the
10412 // left hand side of the comma operator, otherwise emit a warning.
10413 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10414 // No warnings in macros
10415 if (Loc.isMacroID())
10418 // Don't warn in template instantiations.
10419 if (inTemplateInstantiation())
10422 // Scope isn't fine-grained enough to whitelist the specific cases, so
10423 // instead, skip more than needed, then call back into here with the
10424 // CommaVisitor in SemaStmt.cpp.
10425 // The whitelisted locations are the initialization and increment portions
10426 // of a for loop. The additional checks are on the condition of
10427 // if statements, do/while loops, and for loops.
10428 const unsigned ForIncrementFlags =
10429 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10430 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10431 const unsigned ScopeFlags = getCurScope()->getFlags();
10432 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10433 (ScopeFlags & ForInitFlags) == ForInitFlags)
10436 // If there are multiple comma operators used together, get the RHS of the
10437 // of the comma operator as the LHS.
10438 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10439 if (BO->getOpcode() != BO_Comma)
10441 LHS = BO->getRHS();
10444 // Only allow some expressions on LHS to not warn.
10445 if (IgnoreCommaOperand(LHS))
10448 Diag(Loc, diag::warn_comma_operator);
10449 Diag(LHS->getLocStart(), diag::note_cast_to_void)
10450 << LHS->getSourceRange()
10451 << FixItHint::CreateInsertion(LHS->getLocStart(),
10452 LangOpts.CPlusPlus ? "static_cast<void>("
10454 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10459 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10460 SourceLocation Loc) {
10461 LHS = S.CheckPlaceholderExpr(LHS.get());
10462 RHS = S.CheckPlaceholderExpr(RHS.get());
10463 if (LHS.isInvalid() || RHS.isInvalid())
10466 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10467 // operands, but not unary promotions.
10468 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10470 // So we treat the LHS as a ignored value, and in C++ we allow the
10471 // containing site to determine what should be done with the RHS.
10472 LHS = S.IgnoredValueConversions(LHS.get());
10473 if (LHS.isInvalid())
10476 S.DiagnoseUnusedExprResult(LHS.get());
10478 if (!S.getLangOpts().CPlusPlus) {
10479 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10480 if (RHS.isInvalid())
10482 if (!RHS.get()->getType()->isVoidType())
10483 S.RequireCompleteType(Loc, RHS.get()->getType(),
10484 diag::err_incomplete_type);
10487 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10488 S.DiagnoseCommaOperator(LHS.get(), Loc);
10490 return RHS.get()->getType();
10493 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10494 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10495 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10497 ExprObjectKind &OK,
10498 SourceLocation OpLoc,
10499 bool IsInc, bool IsPrefix) {
10500 if (Op->isTypeDependent())
10501 return S.Context.DependentTy;
10503 QualType ResType = Op->getType();
10504 // Atomic types can be used for increment / decrement where the non-atomic
10505 // versions can, so ignore the _Atomic() specifier for the purpose of
10507 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10508 ResType = ResAtomicType->getValueType();
10510 assert(!ResType.isNull() && "no type for increment/decrement expression");
10512 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10513 // Decrement of bool is not allowed.
10515 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10518 // Increment of bool sets it to true, but is deprecated.
10519 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10520 : diag::warn_increment_bool)
10521 << Op->getSourceRange();
10522 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10523 // Error on enum increments and decrements in C++ mode
10524 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10526 } else if (ResType->isRealType()) {
10528 } else if (ResType->isPointerType()) {
10529 // C99 6.5.2.4p2, 6.5.6p2
10530 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10532 } else if (ResType->isObjCObjectPointerType()) {
10533 // On modern runtimes, ObjC pointer arithmetic is forbidden.
10534 // Otherwise, we just need a complete type.
10535 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10536 checkArithmeticOnObjCPointer(S, OpLoc, Op))
10538 } else if (ResType->isAnyComplexType()) {
10539 // C99 does not support ++/-- on complex types, we allow as an extension.
10540 S.Diag(OpLoc, diag::ext_integer_increment_complex)
10541 << ResType << Op->getSourceRange();
10542 } else if (ResType->isPlaceholderType()) {
10543 ExprResult PR = S.CheckPlaceholderExpr(Op);
10544 if (PR.isInvalid()) return QualType();
10545 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10547 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10548 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10549 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10550 (ResType->getAs<VectorType>()->getVectorKind() !=
10551 VectorType::AltiVecBool)) {
10552 // The z vector extensions allow ++ and -- for non-bool vectors.
10553 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10554 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10555 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10557 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10558 << ResType << int(IsInc) << Op->getSourceRange();
10561 // At this point, we know we have a real, complex or pointer type.
10562 // Now make sure the operand is a modifiable lvalue.
10563 if (CheckForModifiableLvalue(Op, OpLoc, S))
10565 // In C++, a prefix increment is the same type as the operand. Otherwise
10566 // (in C or with postfix), the increment is the unqualified type of the
10568 if (IsPrefix && S.getLangOpts().CPlusPlus) {
10570 OK = Op->getObjectKind();
10574 return ResType.getUnqualifiedType();
10579 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10580 /// This routine allows us to typecheck complex/recursive expressions
10581 /// where the declaration is needed for type checking. We only need to
10582 /// handle cases when the expression references a function designator
10583 /// or is an lvalue. Here are some examples:
10585 /// - &*****f => f for f a function designator.
10587 /// - &s.zz[1].yy -> s, if zz is an array
10588 /// - *(x + 1) -> x, if x is an array
10589 /// - &"123"[2] -> 0
10590 /// - & __real__ x -> x
10591 static ValueDecl *getPrimaryDecl(Expr *E) {
10592 switch (E->getStmtClass()) {
10593 case Stmt::DeclRefExprClass:
10594 return cast<DeclRefExpr>(E)->getDecl();
10595 case Stmt::MemberExprClass:
10596 // If this is an arrow operator, the address is an offset from
10597 // the base's value, so the object the base refers to is
10599 if (cast<MemberExpr>(E)->isArrow())
10601 // Otherwise, the expression refers to a part of the base
10602 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10603 case Stmt::ArraySubscriptExprClass: {
10604 // FIXME: This code shouldn't be necessary! We should catch the implicit
10605 // promotion of register arrays earlier.
10606 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10607 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10608 if (ICE->getSubExpr()->getType()->isArrayType())
10609 return getPrimaryDecl(ICE->getSubExpr());
10613 case Stmt::UnaryOperatorClass: {
10614 UnaryOperator *UO = cast<UnaryOperator>(E);
10616 switch(UO->getOpcode()) {
10620 return getPrimaryDecl(UO->getSubExpr());
10625 case Stmt::ParenExprClass:
10626 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10627 case Stmt::ImplicitCastExprClass:
10628 // If the result of an implicit cast is an l-value, we care about
10629 // the sub-expression; otherwise, the result here doesn't matter.
10630 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10639 AO_Vector_Element = 1,
10640 AO_Property_Expansion = 2,
10641 AO_Register_Variable = 3,
10645 /// \brief Diagnose invalid operand for address of operations.
10647 /// \param Type The type of operand which cannot have its address taken.
10648 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10649 Expr *E, unsigned Type) {
10650 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10653 /// CheckAddressOfOperand - The operand of & must be either a function
10654 /// designator or an lvalue designating an object. If it is an lvalue, the
10655 /// object cannot be declared with storage class register or be a bit field.
10656 /// Note: The usual conversions are *not* applied to the operand of the &
10657 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10658 /// In C++, the operand might be an overloaded function name, in which case
10659 /// we allow the '&' but retain the overloaded-function type.
10660 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10661 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10662 if (PTy->getKind() == BuiltinType::Overload) {
10663 Expr *E = OrigOp.get()->IgnoreParens();
10664 if (!isa<OverloadExpr>(E)) {
10665 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10666 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10667 << OrigOp.get()->getSourceRange();
10671 OverloadExpr *Ovl = cast<OverloadExpr>(E);
10672 if (isa<UnresolvedMemberExpr>(Ovl))
10673 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10674 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10675 << OrigOp.get()->getSourceRange();
10679 return Context.OverloadTy;
10682 if (PTy->getKind() == BuiltinType::UnknownAny)
10683 return Context.UnknownAnyTy;
10685 if (PTy->getKind() == BuiltinType::BoundMember) {
10686 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10687 << OrigOp.get()->getSourceRange();
10691 OrigOp = CheckPlaceholderExpr(OrigOp.get());
10692 if (OrigOp.isInvalid()) return QualType();
10695 if (OrigOp.get()->isTypeDependent())
10696 return Context.DependentTy;
10698 assert(!OrigOp.get()->getType()->isPlaceholderType());
10700 // Make sure to ignore parentheses in subsequent checks
10701 Expr *op = OrigOp.get()->IgnoreParens();
10703 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10704 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10705 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10709 if (getLangOpts().C99) {
10710 // Implement C99-only parts of addressof rules.
10711 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10712 if (uOp->getOpcode() == UO_Deref)
10713 // Per C99 6.5.3.2, the address of a deref always returns a valid result
10714 // (assuming the deref expression is valid).
10715 return uOp->getSubExpr()->getType();
10717 // Technically, there should be a check for array subscript
10718 // expressions here, but the result of one is always an lvalue anyway.
10720 ValueDecl *dcl = getPrimaryDecl(op);
10722 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10723 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10724 op->getLocStart()))
10727 Expr::LValueClassification lval = op->ClassifyLValue(Context);
10728 unsigned AddressOfError = AO_No_Error;
10730 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10731 bool sfinae = (bool)isSFINAEContext();
10732 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10733 : diag::ext_typecheck_addrof_temporary)
10734 << op->getType() << op->getSourceRange();
10737 // Materialize the temporary as an lvalue so that we can take its address.
10739 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10740 } else if (isa<ObjCSelectorExpr>(op)) {
10741 return Context.getPointerType(op->getType());
10742 } else if (lval == Expr::LV_MemberFunction) {
10743 // If it's an instance method, make a member pointer.
10744 // The expression must have exactly the form &A::foo.
10746 // If the underlying expression isn't a decl ref, give up.
10747 if (!isa<DeclRefExpr>(op)) {
10748 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10749 << OrigOp.get()->getSourceRange();
10752 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10753 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10755 // The id-expression was parenthesized.
10756 if (OrigOp.get() != DRE) {
10757 Diag(OpLoc, diag::err_parens_pointer_member_function)
10758 << OrigOp.get()->getSourceRange();
10760 // The method was named without a qualifier.
10761 } else if (!DRE->getQualifier()) {
10762 if (MD->getParent()->getName().empty())
10763 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10764 << op->getSourceRange();
10766 SmallString<32> Str;
10767 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10768 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10769 << op->getSourceRange()
10770 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10774 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10775 if (isa<CXXDestructorDecl>(MD))
10776 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10778 QualType MPTy = Context.getMemberPointerType(
10779 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10780 // Under the MS ABI, lock down the inheritance model now.
10781 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10782 (void)isCompleteType(OpLoc, MPTy);
10784 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10786 // The operand must be either an l-value or a function designator
10787 if (!op->getType()->isFunctionType()) {
10788 // Use a special diagnostic for loads from property references.
10789 if (isa<PseudoObjectExpr>(op)) {
10790 AddressOfError = AO_Property_Expansion;
10792 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10793 << op->getType() << op->getSourceRange();
10797 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10798 // The operand cannot be a bit-field
10799 AddressOfError = AO_Bit_Field;
10800 } else if (op->getObjectKind() == OK_VectorComponent) {
10801 // The operand cannot be an element of a vector
10802 AddressOfError = AO_Vector_Element;
10803 } else if (dcl) { // C99 6.5.3.2p1
10804 // We have an lvalue with a decl. Make sure the decl is not declared
10805 // with the register storage-class specifier.
10806 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10807 // in C++ it is not error to take address of a register
10808 // variable (c++03 7.1.1P3)
10809 if (vd->getStorageClass() == SC_Register &&
10810 !getLangOpts().CPlusPlus) {
10811 AddressOfError = AO_Register_Variable;
10813 } else if (isa<MSPropertyDecl>(dcl)) {
10814 AddressOfError = AO_Property_Expansion;
10815 } else if (isa<FunctionTemplateDecl>(dcl)) {
10816 return Context.OverloadTy;
10817 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10818 // Okay: we can take the address of a field.
10819 // Could be a pointer to member, though, if there is an explicit
10820 // scope qualifier for the class.
10821 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10822 DeclContext *Ctx = dcl->getDeclContext();
10823 if (Ctx && Ctx->isRecord()) {
10824 if (dcl->getType()->isReferenceType()) {
10826 diag::err_cannot_form_pointer_to_member_of_reference_type)
10827 << dcl->getDeclName() << dcl->getType();
10831 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10832 Ctx = Ctx->getParent();
10834 QualType MPTy = Context.getMemberPointerType(
10836 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10837 // Under the MS ABI, lock down the inheritance model now.
10838 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10839 (void)isCompleteType(OpLoc, MPTy);
10843 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10844 !isa<BindingDecl>(dcl))
10845 llvm_unreachable("Unknown/unexpected decl type");
10848 if (AddressOfError != AO_No_Error) {
10849 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10853 if (lval == Expr::LV_IncompleteVoidType) {
10854 // Taking the address of a void variable is technically illegal, but we
10855 // allow it in cases which are otherwise valid.
10856 // Example: "extern void x; void* y = &x;".
10857 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10860 // If the operand has type "type", the result has type "pointer to type".
10861 if (op->getType()->isObjCObjectType())
10862 return Context.getObjCObjectPointerType(op->getType());
10864 CheckAddressOfPackedMember(op);
10866 return Context.getPointerType(op->getType());
10869 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10870 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10873 const Decl *D = DRE->getDecl();
10876 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10879 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10880 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10882 if (FunctionScopeInfo *FD = S.getCurFunction())
10883 if (!FD->ModifiedNonNullParams.count(Param))
10884 FD->ModifiedNonNullParams.insert(Param);
10887 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10888 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10889 SourceLocation OpLoc) {
10890 if (Op->isTypeDependent())
10891 return S.Context.DependentTy;
10893 ExprResult ConvResult = S.UsualUnaryConversions(Op);
10894 if (ConvResult.isInvalid())
10896 Op = ConvResult.get();
10897 QualType OpTy = Op->getType();
10900 if (isa<CXXReinterpretCastExpr>(Op)) {
10901 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10902 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10903 Op->getSourceRange());
10906 if (const PointerType *PT = OpTy->getAs<PointerType>())
10908 Result = PT->getPointeeType();
10910 else if (const ObjCObjectPointerType *OPT =
10911 OpTy->getAs<ObjCObjectPointerType>())
10912 Result = OPT->getPointeeType();
10914 ExprResult PR = S.CheckPlaceholderExpr(Op);
10915 if (PR.isInvalid()) return QualType();
10916 if (PR.get() != Op)
10917 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10920 if (Result.isNull()) {
10921 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10922 << OpTy << Op->getSourceRange();
10926 // Note that per both C89 and C99, indirection is always legal, even if Result
10927 // is an incomplete type or void. It would be possible to warn about
10928 // dereferencing a void pointer, but it's completely well-defined, and such a
10929 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10930 // for pointers to 'void' but is fine for any other pointer type:
10932 // C++ [expr.unary.op]p1:
10933 // [...] the expression to which [the unary * operator] is applied shall
10934 // be a pointer to an object type, or a pointer to a function type
10935 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10936 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10937 << OpTy << Op->getSourceRange();
10939 // Dereferences are usually l-values...
10942 // ...except that certain expressions are never l-values in C.
10943 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10949 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10950 BinaryOperatorKind Opc;
10952 default: llvm_unreachable("Unknown binop!");
10953 case tok::periodstar: Opc = BO_PtrMemD; break;
10954 case tok::arrowstar: Opc = BO_PtrMemI; break;
10955 case tok::star: Opc = BO_Mul; break;
10956 case tok::slash: Opc = BO_Div; break;
10957 case tok::percent: Opc = BO_Rem; break;
10958 case tok::plus: Opc = BO_Add; break;
10959 case tok::minus: Opc = BO_Sub; break;
10960 case tok::lessless: Opc = BO_Shl; break;
10961 case tok::greatergreater: Opc = BO_Shr; break;
10962 case tok::lessequal: Opc = BO_LE; break;
10963 case tok::less: Opc = BO_LT; break;
10964 case tok::greaterequal: Opc = BO_GE; break;
10965 case tok::greater: Opc = BO_GT; break;
10966 case tok::exclaimequal: Opc = BO_NE; break;
10967 case tok::equalequal: Opc = BO_EQ; break;
10968 case tok::amp: Opc = BO_And; break;
10969 case tok::caret: Opc = BO_Xor; break;
10970 case tok::pipe: Opc = BO_Or; break;
10971 case tok::ampamp: Opc = BO_LAnd; break;
10972 case tok::pipepipe: Opc = BO_LOr; break;
10973 case tok::equal: Opc = BO_Assign; break;
10974 case tok::starequal: Opc = BO_MulAssign; break;
10975 case tok::slashequal: Opc = BO_DivAssign; break;
10976 case tok::percentequal: Opc = BO_RemAssign; break;
10977 case tok::plusequal: Opc = BO_AddAssign; break;
10978 case tok::minusequal: Opc = BO_SubAssign; break;
10979 case tok::lesslessequal: Opc = BO_ShlAssign; break;
10980 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
10981 case tok::ampequal: Opc = BO_AndAssign; break;
10982 case tok::caretequal: Opc = BO_XorAssign; break;
10983 case tok::pipeequal: Opc = BO_OrAssign; break;
10984 case tok::comma: Opc = BO_Comma; break;
10989 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10990 tok::TokenKind Kind) {
10991 UnaryOperatorKind Opc;
10993 default: llvm_unreachable("Unknown unary op!");
10994 case tok::plusplus: Opc = UO_PreInc; break;
10995 case tok::minusminus: Opc = UO_PreDec; break;
10996 case tok::amp: Opc = UO_AddrOf; break;
10997 case tok::star: Opc = UO_Deref; break;
10998 case tok::plus: Opc = UO_Plus; break;
10999 case tok::minus: Opc = UO_Minus; break;
11000 case tok::tilde: Opc = UO_Not; break;
11001 case tok::exclaim: Opc = UO_LNot; break;
11002 case tok::kw___real: Opc = UO_Real; break;
11003 case tok::kw___imag: Opc = UO_Imag; break;
11004 case tok::kw___extension__: Opc = UO_Extension; break;
11009 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11010 /// This warning is only emitted for builtin assignment operations. It is also
11011 /// suppressed in the event of macro expansions.
11012 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11013 SourceLocation OpLoc) {
11014 if (S.inTemplateInstantiation())
11016 if (OpLoc.isInvalid() || OpLoc.isMacroID())
11018 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11019 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11020 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11021 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11022 if (!LHSDeclRef || !RHSDeclRef ||
11023 LHSDeclRef->getLocation().isMacroID() ||
11024 RHSDeclRef->getLocation().isMacroID())
11026 const ValueDecl *LHSDecl =
11027 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11028 const ValueDecl *RHSDecl =
11029 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11030 if (LHSDecl != RHSDecl)
11032 if (LHSDecl->getType().isVolatileQualified())
11034 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11035 if (RefTy->getPointeeType().isVolatileQualified())
11038 S.Diag(OpLoc, diag::warn_self_assignment)
11039 << LHSDeclRef->getType()
11040 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11043 /// Check if a bitwise-& is performed on an Objective-C pointer. This
11044 /// is usually indicative of introspection within the Objective-C pointer.
11045 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11046 SourceLocation OpLoc) {
11047 if (!S.getLangOpts().ObjC1)
11050 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11051 const Expr *LHS = L.get();
11052 const Expr *RHS = R.get();
11054 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11055 ObjCPointerExpr = LHS;
11058 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11059 ObjCPointerExpr = RHS;
11063 // This warning is deliberately made very specific to reduce false
11064 // positives with logic that uses '&' for hashing. This logic mainly
11065 // looks for code trying to introspect into tagged pointers, which
11066 // code should generally never do.
11067 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11068 unsigned Diag = diag::warn_objc_pointer_masking;
11069 // Determine if we are introspecting the result of performSelectorXXX.
11070 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11071 // Special case messages to -performSelector and friends, which
11072 // can return non-pointer values boxed in a pointer value.
11073 // Some clients may wish to silence warnings in this subcase.
11074 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11075 Selector S = ME->getSelector();
11076 StringRef SelArg0 = S.getNameForSlot(0);
11077 if (SelArg0.startswith("performSelector"))
11078 Diag = diag::warn_objc_pointer_masking_performSelector;
11081 S.Diag(OpLoc, Diag)
11082 << ObjCPointerExpr->getSourceRange();
11086 static NamedDecl *getDeclFromExpr(Expr *E) {
11089 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11090 return DRE->getDecl();
11091 if (auto *ME = dyn_cast<MemberExpr>(E))
11092 return ME->getMemberDecl();
11093 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11094 return IRE->getDecl();
11098 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11099 /// operator @p Opc at location @c TokLoc. This routine only supports
11100 /// built-in operations; ActOnBinOp handles overloaded operators.
11101 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11102 BinaryOperatorKind Opc,
11103 Expr *LHSExpr, Expr *RHSExpr) {
11104 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11105 // The syntax only allows initializer lists on the RHS of assignment,
11106 // so we don't need to worry about accepting invalid code for
11107 // non-assignment operators.
11109 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11110 // of x = {} is x = T().
11111 InitializationKind Kind =
11112 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11113 InitializedEntity Entity =
11114 InitializedEntity::InitializeTemporary(LHSExpr->getType());
11115 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11116 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11117 if (Init.isInvalid())
11119 RHSExpr = Init.get();
11122 ExprResult LHS = LHSExpr, RHS = RHSExpr;
11123 QualType ResultTy; // Result type of the binary operator.
11124 // The following two variables are used for compound assignment operators
11125 QualType CompLHSTy; // Type of LHS after promotions for computation
11126 QualType CompResultTy; // Type of computation result
11127 ExprValueKind VK = VK_RValue;
11128 ExprObjectKind OK = OK_Ordinary;
11130 if (!getLangOpts().CPlusPlus) {
11131 // C cannot handle TypoExpr nodes on either side of a binop because it
11132 // doesn't handle dependent types properly, so make sure any TypoExprs have
11133 // been dealt with before checking the operands.
11134 LHS = CorrectDelayedTyposInExpr(LHSExpr);
11135 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11136 if (Opc != BO_Assign)
11137 return ExprResult(E);
11138 // Avoid correcting the RHS to the same Expr as the LHS.
11139 Decl *D = getDeclFromExpr(E);
11140 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11142 if (!LHS.isUsable() || !RHS.isUsable())
11143 return ExprError();
11146 if (getLangOpts().OpenCL) {
11147 QualType LHSTy = LHSExpr->getType();
11148 QualType RHSTy = RHSExpr->getType();
11149 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11150 // the ATOMIC_VAR_INIT macro.
11151 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11152 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11153 if (BO_Assign == Opc)
11154 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11156 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11157 return ExprError();
11160 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11161 // only with a builtin functions and therefore should be disallowed here.
11162 if (LHSTy->isImageType() || RHSTy->isImageType() ||
11163 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11164 LHSTy->isPipeType() || RHSTy->isPipeType() ||
11165 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11166 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11167 return ExprError();
11173 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11174 if (getLangOpts().CPlusPlus &&
11175 LHS.get()->getObjectKind() != OK_ObjCProperty) {
11176 VK = LHS.get()->getValueKind();
11177 OK = LHS.get()->getObjectKind();
11179 if (!ResultTy.isNull()) {
11180 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11181 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11183 RecordModifiableNonNullParam(*this, LHS.get());
11187 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11188 Opc == BO_PtrMemI);
11192 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11196 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11199 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11202 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11206 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11212 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11216 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11219 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11222 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11226 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11230 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11231 Opc == BO_DivAssign);
11232 CompLHSTy = CompResultTy;
11233 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11234 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11237 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11238 CompLHSTy = CompResultTy;
11239 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11240 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11243 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11244 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11245 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11248 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11249 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11250 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11254 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11255 CompLHSTy = CompResultTy;
11256 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11257 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11260 case BO_OrAssign: // fallthrough
11261 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11263 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11264 CompLHSTy = CompResultTy;
11265 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11266 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11269 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11270 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11271 VK = RHS.get()->getValueKind();
11272 OK = RHS.get()->getObjectKind();
11276 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11277 return ExprError();
11279 // Check for array bounds violations for both sides of the BinaryOperator
11280 CheckArrayAccess(LHS.get());
11281 CheckArrayAccess(RHS.get());
11283 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11284 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11285 &Context.Idents.get("object_setClass"),
11286 SourceLocation(), LookupOrdinaryName);
11287 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11288 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11289 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11290 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11291 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11292 FixItHint::CreateInsertion(RHSLocEnd, ")");
11295 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11297 else if (const ObjCIvarRefExpr *OIRE =
11298 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11299 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11301 if (CompResultTy.isNull())
11302 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11303 OK, OpLoc, FPFeatures);
11304 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11307 OK = LHS.get()->getObjectKind();
11309 return new (Context) CompoundAssignOperator(
11310 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11311 OpLoc, FPFeatures);
11314 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11315 /// operators are mixed in a way that suggests that the programmer forgot that
11316 /// comparison operators have higher precedence. The most typical example of
11317 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11318 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11319 SourceLocation OpLoc, Expr *LHSExpr,
11321 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11322 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11324 // Check that one of the sides is a comparison operator and the other isn't.
11325 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11326 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11327 if (isLeftComp == isRightComp)
11330 // Bitwise operations are sometimes used as eager logical ops.
11331 // Don't diagnose this.
11332 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11333 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11334 if (isLeftBitwise || isRightBitwise)
11337 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11339 : SourceRange(OpLoc, RHSExpr->getLocEnd());
11340 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11341 SourceRange ParensRange = isLeftComp ?
11342 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11343 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11345 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11346 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11347 SuggestParentheses(Self, OpLoc,
11348 Self.PDiag(diag::note_precedence_silence) << OpStr,
11349 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11350 SuggestParentheses(Self, OpLoc,
11351 Self.PDiag(diag::note_precedence_bitwise_first)
11352 << BinaryOperator::getOpcodeStr(Opc),
11356 /// \brief It accepts a '&&' expr that is inside a '||' one.
11357 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11358 /// in parentheses.
11360 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11361 BinaryOperator *Bop) {
11362 assert(Bop->getOpcode() == BO_LAnd);
11363 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11364 << Bop->getSourceRange() << OpLoc;
11365 SuggestParentheses(Self, Bop->getOperatorLoc(),
11366 Self.PDiag(diag::note_precedence_silence)
11367 << Bop->getOpcodeStr(),
11368 Bop->getSourceRange());
11371 /// \brief Returns true if the given expression can be evaluated as a constant
11373 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11375 return !E->isValueDependent() &&
11376 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11379 /// \brief Returns true if the given expression can be evaluated as a constant
11381 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11383 return !E->isValueDependent() &&
11384 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11387 /// \brief Look for '&&' in the left hand of a '||' expr.
11388 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11389 Expr *LHSExpr, Expr *RHSExpr) {
11390 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11391 if (Bop->getOpcode() == BO_LAnd) {
11392 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11393 if (EvaluatesAsFalse(S, RHSExpr))
11395 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11396 if (!EvaluatesAsTrue(S, Bop->getLHS()))
11397 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11398 } else if (Bop->getOpcode() == BO_LOr) {
11399 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11400 // If it's "a || b && 1 || c" we didn't warn earlier for
11401 // "a || b && 1", but warn now.
11402 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11403 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11409 /// \brief Look for '&&' in the right hand of a '||' expr.
11410 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11411 Expr *LHSExpr, Expr *RHSExpr) {
11412 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11413 if (Bop->getOpcode() == BO_LAnd) {
11414 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11415 if (EvaluatesAsFalse(S, LHSExpr))
11417 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11418 if (!EvaluatesAsTrue(S, Bop->getRHS()))
11419 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11424 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11425 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11426 /// the '&' expression in parentheses.
11427 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11428 SourceLocation OpLoc, Expr *SubExpr) {
11429 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11430 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11431 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11432 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11433 << Bop->getSourceRange() << OpLoc;
11434 SuggestParentheses(S, Bop->getOperatorLoc(),
11435 S.PDiag(diag::note_precedence_silence)
11436 << Bop->getOpcodeStr(),
11437 Bop->getSourceRange());
11442 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11443 Expr *SubExpr, StringRef Shift) {
11444 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11445 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11446 StringRef Op = Bop->getOpcodeStr();
11447 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11448 << Bop->getSourceRange() << OpLoc << Shift << Op;
11449 SuggestParentheses(S, Bop->getOperatorLoc(),
11450 S.PDiag(diag::note_precedence_silence) << Op,
11451 Bop->getSourceRange());
11456 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11457 Expr *LHSExpr, Expr *RHSExpr) {
11458 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11462 FunctionDecl *FD = OCE->getDirectCallee();
11463 if (!FD || !FD->isOverloadedOperator())
11466 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11467 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11470 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11471 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11472 << (Kind == OO_LessLess);
11473 SuggestParentheses(S, OCE->getOperatorLoc(),
11474 S.PDiag(diag::note_precedence_silence)
11475 << (Kind == OO_LessLess ? "<<" : ">>"),
11476 OCE->getSourceRange());
11477 SuggestParentheses(S, OpLoc,
11478 S.PDiag(diag::note_evaluate_comparison_first),
11479 SourceRange(OCE->getArg(1)->getLocStart(),
11480 RHSExpr->getLocEnd()));
11483 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11485 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11486 SourceLocation OpLoc, Expr *LHSExpr,
11488 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11489 if (BinaryOperator::isBitwiseOp(Opc))
11490 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11492 // Diagnose "arg1 & arg2 | arg3"
11493 if ((Opc == BO_Or || Opc == BO_Xor) &&
11494 !OpLoc.isMacroID()/* Don't warn in macros. */) {
11495 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11496 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11499 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11500 // We don't warn for 'assert(a || b && "bad")' since this is safe.
11501 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11502 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11503 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11506 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11507 || Opc == BO_Shr) {
11508 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11509 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11510 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11513 // Warn on overloaded shift operators and comparisons, such as:
11515 if (BinaryOperator::isComparisonOp(Opc))
11516 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11519 // Binary Operators. 'Tok' is the token for the operator.
11520 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11521 tok::TokenKind Kind,
11522 Expr *LHSExpr, Expr *RHSExpr) {
11523 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11524 assert(LHSExpr && "ActOnBinOp(): missing left expression");
11525 assert(RHSExpr && "ActOnBinOp(): missing right expression");
11527 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11528 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11530 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11533 /// Build an overloaded binary operator expression in the given scope.
11534 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11535 BinaryOperatorKind Opc,
11536 Expr *LHS, Expr *RHS) {
11537 // Find all of the overloaded operators visible from this
11538 // point. We perform both an operator-name lookup from the local
11539 // scope and an argument-dependent lookup based on the types of
11541 UnresolvedSet<16> Functions;
11542 OverloadedOperatorKind OverOp
11543 = BinaryOperator::getOverloadedOperator(Opc);
11544 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11545 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11546 RHS->getType(), Functions);
11548 // Build the (potentially-overloaded, potentially-dependent)
11549 // binary operation.
11550 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11553 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11554 BinaryOperatorKind Opc,
11555 Expr *LHSExpr, Expr *RHSExpr) {
11556 // We want to end up calling one of checkPseudoObjectAssignment
11557 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11558 // both expressions are overloadable or either is type-dependent),
11559 // or CreateBuiltinBinOp (in any other case). We also want to get
11560 // any placeholder types out of the way.
11562 // Handle pseudo-objects in the LHS.
11563 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11564 // Assignments with a pseudo-object l-value need special analysis.
11565 if (pty->getKind() == BuiltinType::PseudoObject &&
11566 BinaryOperator::isAssignmentOp(Opc))
11567 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11569 // Don't resolve overloads if the other type is overloadable.
11570 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11571 // We can't actually test that if we still have a placeholder,
11572 // though. Fortunately, none of the exceptions we see in that
11573 // code below are valid when the LHS is an overload set. Note
11574 // that an overload set can be dependently-typed, but it never
11575 // instantiates to having an overloadable type.
11576 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11577 if (resolvedRHS.isInvalid()) return ExprError();
11578 RHSExpr = resolvedRHS.get();
11580 if (RHSExpr->isTypeDependent() ||
11581 RHSExpr->getType()->isOverloadableType())
11582 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11585 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11586 if (LHS.isInvalid()) return ExprError();
11587 LHSExpr = LHS.get();
11590 // Handle pseudo-objects in the RHS.
11591 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11592 // An overload in the RHS can potentially be resolved by the type
11593 // being assigned to.
11594 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11595 if (getLangOpts().CPlusPlus &&
11596 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11597 LHSExpr->getType()->isOverloadableType()))
11598 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11600 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11603 // Don't resolve overloads if the other type is overloadable.
11604 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11605 LHSExpr->getType()->isOverloadableType())
11606 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11608 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11609 if (!resolvedRHS.isUsable()) return ExprError();
11610 RHSExpr = resolvedRHS.get();
11613 if (getLangOpts().CPlusPlus) {
11614 // If either expression is type-dependent, always build an
11616 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11617 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11619 // Otherwise, build an overloaded op if either expression has an
11620 // overloadable type.
11621 if (LHSExpr->getType()->isOverloadableType() ||
11622 RHSExpr->getType()->isOverloadableType())
11623 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11626 // Build a built-in binary operation.
11627 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11630 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11631 UnaryOperatorKind Opc,
11633 ExprResult Input = InputExpr;
11634 ExprValueKind VK = VK_RValue;
11635 ExprObjectKind OK = OK_Ordinary;
11636 QualType resultType;
11637 if (getLangOpts().OpenCL) {
11638 QualType Ty = InputExpr->getType();
11639 // The only legal unary operation for atomics is '&'.
11640 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11641 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11642 // only with a builtin functions and therefore should be disallowed here.
11643 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11644 || Ty->isBlockPointerType())) {
11645 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11646 << InputExpr->getType()
11647 << Input.get()->getSourceRange());
11655 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11657 Opc == UO_PreInc ||
11659 Opc == UO_PreInc ||
11663 resultType = CheckAddressOfOperand(Input, OpLoc);
11664 RecordModifiableNonNullParam(*this, InputExpr);
11667 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11668 if (Input.isInvalid()) return ExprError();
11669 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11674 Input = UsualUnaryConversions(Input.get());
11675 if (Input.isInvalid()) return ExprError();
11676 resultType = Input.get()->getType();
11677 if (resultType->isDependentType())
11679 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11681 else if (resultType->isVectorType() &&
11682 // The z vector extensions don't allow + or - with bool vectors.
11683 (!Context.getLangOpts().ZVector ||
11684 resultType->getAs<VectorType>()->getVectorKind() !=
11685 VectorType::AltiVecBool))
11687 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11689 resultType->isPointerType())
11692 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11693 << resultType << Input.get()->getSourceRange());
11695 case UO_Not: // bitwise complement
11696 Input = UsualUnaryConversions(Input.get());
11697 if (Input.isInvalid())
11698 return ExprError();
11699 resultType = Input.get()->getType();
11700 if (resultType->isDependentType())
11702 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11703 if (resultType->isComplexType() || resultType->isComplexIntegerType())
11704 // C99 does not support '~' for complex conjugation.
11705 Diag(OpLoc, diag::ext_integer_complement_complex)
11706 << resultType << Input.get()->getSourceRange();
11707 else if (resultType->hasIntegerRepresentation())
11709 else if (resultType->isExtVectorType()) {
11710 if (Context.getLangOpts().OpenCL) {
11711 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11712 // on vector float types.
11713 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11714 if (!T->isIntegerType())
11715 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11716 << resultType << Input.get()->getSourceRange());
11720 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11721 << resultType << Input.get()->getSourceRange());
11725 case UO_LNot: // logical negation
11726 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11727 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11728 if (Input.isInvalid()) return ExprError();
11729 resultType = Input.get()->getType();
11731 // Though we still have to promote half FP to float...
11732 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11733 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11734 resultType = Context.FloatTy;
11737 if (resultType->isDependentType())
11739 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11740 // C99 6.5.3.3p1: ok, fallthrough;
11741 if (Context.getLangOpts().CPlusPlus) {
11742 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11743 // operand contextually converted to bool.
11744 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11745 ScalarTypeToBooleanCastKind(resultType));
11746 } else if (Context.getLangOpts().OpenCL &&
11747 Context.getLangOpts().OpenCLVersion < 120) {
11748 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11749 // operate on scalar float types.
11750 if (!resultType->isIntegerType() && !resultType->isPointerType())
11751 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11752 << resultType << Input.get()->getSourceRange());
11754 } else if (resultType->isExtVectorType()) {
11755 if (Context.getLangOpts().OpenCL &&
11756 Context.getLangOpts().OpenCLVersion < 120) {
11757 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11758 // operate on vector float types.
11759 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11760 if (!T->isIntegerType())
11761 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11762 << resultType << Input.get()->getSourceRange());
11764 // Vector logical not returns the signed variant of the operand type.
11765 resultType = GetSignedVectorType(resultType);
11768 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11769 << resultType << Input.get()->getSourceRange());
11772 // LNot always has type int. C99 6.5.3.3p5.
11773 // In C++, it's bool. C++ 5.3.1p8
11774 resultType = Context.getLogicalOperationType();
11778 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11779 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11780 // complex l-values to ordinary l-values and all other values to r-values.
11781 if (Input.isInvalid()) return ExprError();
11782 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11783 if (Input.get()->getValueKind() != VK_RValue &&
11784 Input.get()->getObjectKind() == OK_Ordinary)
11785 VK = Input.get()->getValueKind();
11786 } else if (!getLangOpts().CPlusPlus) {
11787 // In C, a volatile scalar is read by __imag. In C++, it is not.
11788 Input = DefaultLvalueConversion(Input.get());
11793 resultType = Input.get()->getType();
11794 VK = Input.get()->getValueKind();
11795 OK = Input.get()->getObjectKind();
11798 if (resultType.isNull() || Input.isInvalid())
11799 return ExprError();
11801 // Check for array bounds violations in the operand of the UnaryOperator,
11802 // except for the '*' and '&' operators that have to be handled specially
11803 // by CheckArrayAccess (as there are special cases like &array[arraysize]
11804 // that are explicitly defined as valid by the standard).
11805 if (Opc != UO_AddrOf && Opc != UO_Deref)
11806 CheckArrayAccess(Input.get());
11808 return new (Context)
11809 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11812 /// \brief Determine whether the given expression is a qualified member
11813 /// access expression, of a form that could be turned into a pointer to member
11814 /// with the address-of operator.
11815 static bool isQualifiedMemberAccess(Expr *E) {
11816 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11817 if (!DRE->getQualifier())
11820 ValueDecl *VD = DRE->getDecl();
11821 if (!VD->isCXXClassMember())
11824 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11826 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11827 return Method->isInstance();
11832 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11833 if (!ULE->getQualifier())
11836 for (NamedDecl *D : ULE->decls()) {
11837 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11838 if (Method->isInstance())
11841 // Overload set does not contain methods.
11852 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11853 UnaryOperatorKind Opc, Expr *Input) {
11854 // First things first: handle placeholders so that the
11855 // overloaded-operator check considers the right type.
11856 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11857 // Increment and decrement of pseudo-object references.
11858 if (pty->getKind() == BuiltinType::PseudoObject &&
11859 UnaryOperator::isIncrementDecrementOp(Opc))
11860 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11862 // extension is always a builtin operator.
11863 if (Opc == UO_Extension)
11864 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11866 // & gets special logic for several kinds of placeholder.
11867 // The builtin code knows what to do.
11868 if (Opc == UO_AddrOf &&
11869 (pty->getKind() == BuiltinType::Overload ||
11870 pty->getKind() == BuiltinType::UnknownAny ||
11871 pty->getKind() == BuiltinType::BoundMember))
11872 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11874 // Anything else needs to be handled now.
11875 ExprResult Result = CheckPlaceholderExpr(Input);
11876 if (Result.isInvalid()) return ExprError();
11877 Input = Result.get();
11880 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11881 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11882 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11883 // Find all of the overloaded operators visible from this
11884 // point. We perform both an operator-name lookup from the local
11885 // scope and an argument-dependent lookup based on the types of
11887 UnresolvedSet<16> Functions;
11888 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11889 if (S && OverOp != OO_None)
11890 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11893 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11896 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11899 // Unary Operators. 'Tok' is the token for the operator.
11900 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11901 tok::TokenKind Op, Expr *Input) {
11902 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11905 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11906 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11907 LabelDecl *TheDecl) {
11908 TheDecl->markUsed(Context);
11909 // Create the AST node. The address of a label always has type 'void*'.
11910 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11911 Context.getPointerType(Context.VoidTy));
11914 /// Given the last statement in a statement-expression, check whether
11915 /// the result is a producing expression (like a call to an
11916 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11917 /// release out of the full-expression. Otherwise, return null.
11919 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11920 // Should always be wrapped with one of these.
11921 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11922 if (!cleanups) return nullptr;
11924 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11925 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11928 // Splice out the cast. This shouldn't modify any interesting
11929 // features of the statement.
11930 Expr *producer = cast->getSubExpr();
11931 assert(producer->getType() == cast->getType());
11932 assert(producer->getValueKind() == cast->getValueKind());
11933 cleanups->setSubExpr(producer);
11937 void Sema::ActOnStartStmtExpr() {
11938 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11941 void Sema::ActOnStmtExprError() {
11942 // Note that function is also called by TreeTransform when leaving a
11943 // StmtExpr scope without rebuilding anything.
11945 DiscardCleanupsInEvaluationContext();
11946 PopExpressionEvaluationContext();
11950 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11951 SourceLocation RPLoc) { // "({..})"
11952 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11953 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11955 if (hasAnyUnrecoverableErrorsInThisFunction())
11956 DiscardCleanupsInEvaluationContext();
11957 assert(!Cleanup.exprNeedsCleanups() &&
11958 "cleanups within StmtExpr not correctly bound!");
11959 PopExpressionEvaluationContext();
11961 // FIXME: there are a variety of strange constraints to enforce here, for
11962 // example, it is not possible to goto into a stmt expression apparently.
11963 // More semantic analysis is needed.
11965 // If there are sub-stmts in the compound stmt, take the type of the last one
11966 // as the type of the stmtexpr.
11967 QualType Ty = Context.VoidTy;
11968 bool StmtExprMayBindToTemp = false;
11969 if (!Compound->body_empty()) {
11970 Stmt *LastStmt = Compound->body_back();
11971 LabelStmt *LastLabelStmt = nullptr;
11972 // If LastStmt is a label, skip down through into the body.
11973 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11974 LastLabelStmt = Label;
11975 LastStmt = Label->getSubStmt();
11978 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11979 // Do function/array conversion on the last expression, but not
11980 // lvalue-to-rvalue. However, initialize an unqualified type.
11981 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11982 if (LastExpr.isInvalid())
11983 return ExprError();
11984 Ty = LastExpr.get()->getType().getUnqualifiedType();
11986 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11987 // In ARC, if the final expression ends in a consume, splice
11988 // the consume out and bind it later. In the alternate case
11989 // (when dealing with a retainable type), the result
11990 // initialization will create a produce. In both cases the
11991 // result will be +1, and we'll need to balance that out with
11993 if (Expr *rebuiltLastStmt
11994 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11995 LastExpr = rebuiltLastStmt;
11997 LastExpr = PerformCopyInitialization(
11998 InitializedEntity::InitializeResult(LPLoc,
12005 if (LastExpr.isInvalid())
12006 return ExprError();
12007 if (LastExpr.get() != nullptr) {
12008 if (!LastLabelStmt)
12009 Compound->setLastStmt(LastExpr.get());
12011 LastLabelStmt->setSubStmt(LastExpr.get());
12012 StmtExprMayBindToTemp = true;
12018 // FIXME: Check that expression type is complete/non-abstract; statement
12019 // expressions are not lvalues.
12020 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12021 if (StmtExprMayBindToTemp)
12022 return MaybeBindToTemporary(ResStmtExpr);
12023 return ResStmtExpr;
12026 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12027 TypeSourceInfo *TInfo,
12028 ArrayRef<OffsetOfComponent> Components,
12029 SourceLocation RParenLoc) {
12030 QualType ArgTy = TInfo->getType();
12031 bool Dependent = ArgTy->isDependentType();
12032 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12034 // We must have at least one component that refers to the type, and the first
12035 // one is known to be a field designator. Verify that the ArgTy represents
12036 // a struct/union/class.
12037 if (!Dependent && !ArgTy->isRecordType())
12038 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12039 << ArgTy << TypeRange);
12041 // Type must be complete per C99 7.17p3 because a declaring a variable
12042 // with an incomplete type would be ill-formed.
12044 && RequireCompleteType(BuiltinLoc, ArgTy,
12045 diag::err_offsetof_incomplete_type, TypeRange))
12046 return ExprError();
12048 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12049 // GCC extension, diagnose them.
12050 // FIXME: This diagnostic isn't actually visible because the location is in
12051 // a system header!
12052 if (Components.size() != 1)
12053 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12054 << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12056 bool DidWarnAboutNonPOD = false;
12057 QualType CurrentType = ArgTy;
12058 SmallVector<OffsetOfNode, 4> Comps;
12059 SmallVector<Expr*, 4> Exprs;
12060 for (const OffsetOfComponent &OC : Components) {
12061 if (OC.isBrackets) {
12062 // Offset of an array sub-field. TODO: Should we allow vector elements?
12063 if (!CurrentType->isDependentType()) {
12064 const ArrayType *AT = Context.getAsArrayType(CurrentType);
12066 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12068 CurrentType = AT->getElementType();
12070 CurrentType = Context.DependentTy;
12072 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12073 if (IdxRval.isInvalid())
12074 return ExprError();
12075 Expr *Idx = IdxRval.get();
12077 // The expression must be an integral expression.
12078 // FIXME: An integral constant expression?
12079 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12080 !Idx->getType()->isIntegerType())
12081 return ExprError(Diag(Idx->getLocStart(),
12082 diag::err_typecheck_subscript_not_integer)
12083 << Idx->getSourceRange());
12085 // Record this array index.
12086 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12087 Exprs.push_back(Idx);
12091 // Offset of a field.
12092 if (CurrentType->isDependentType()) {
12093 // We have the offset of a field, but we can't look into the dependent
12094 // type. Just record the identifier of the field.
12095 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12096 CurrentType = Context.DependentTy;
12100 // We need to have a complete type to look into.
12101 if (RequireCompleteType(OC.LocStart, CurrentType,
12102 diag::err_offsetof_incomplete_type))
12103 return ExprError();
12105 // Look for the designated field.
12106 const RecordType *RC = CurrentType->getAs<RecordType>();
12108 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12110 RecordDecl *RD = RC->getDecl();
12112 // C++ [lib.support.types]p5:
12113 // The macro offsetof accepts a restricted set of type arguments in this
12114 // International Standard. type shall be a POD structure or a POD union
12116 // C++11 [support.types]p4:
12117 // If type is not a standard-layout class (Clause 9), the results are
12119 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12120 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12122 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12123 : diag::ext_offsetof_non_pod_type;
12125 if (!IsSafe && !DidWarnAboutNonPOD &&
12126 DiagRuntimeBehavior(BuiltinLoc, nullptr,
12128 << SourceRange(Components[0].LocStart, OC.LocEnd)
12130 DidWarnAboutNonPOD = true;
12133 // Look for the field.
12134 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12135 LookupQualifiedName(R, RD);
12136 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12137 IndirectFieldDecl *IndirectMemberDecl = nullptr;
12139 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12140 MemberDecl = IndirectMemberDecl->getAnonField();
12144 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12145 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12149 // (If the specified member is a bit-field, the behavior is undefined.)
12151 // We diagnose this as an error.
12152 if (MemberDecl->isBitField()) {
12153 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12154 << MemberDecl->getDeclName()
12155 << SourceRange(BuiltinLoc, RParenLoc);
12156 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12157 return ExprError();
12160 RecordDecl *Parent = MemberDecl->getParent();
12161 if (IndirectMemberDecl)
12162 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12164 // If the member was found in a base class, introduce OffsetOfNodes for
12165 // the base class indirections.
12166 CXXBasePaths Paths;
12167 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12169 if (Paths.getDetectedVirtual()) {
12170 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12171 << MemberDecl->getDeclName()
12172 << SourceRange(BuiltinLoc, RParenLoc);
12173 return ExprError();
12176 CXXBasePath &Path = Paths.front();
12177 for (const CXXBasePathElement &B : Path)
12178 Comps.push_back(OffsetOfNode(B.Base));
12181 if (IndirectMemberDecl) {
12182 for (auto *FI : IndirectMemberDecl->chain()) {
12183 assert(isa<FieldDecl>(FI));
12184 Comps.push_back(OffsetOfNode(OC.LocStart,
12185 cast<FieldDecl>(FI), OC.LocEnd));
12188 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12190 CurrentType = MemberDecl->getType().getNonReferenceType();
12193 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12194 Comps, Exprs, RParenLoc);
12197 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12198 SourceLocation BuiltinLoc,
12199 SourceLocation TypeLoc,
12200 ParsedType ParsedArgTy,
12201 ArrayRef<OffsetOfComponent> Components,
12202 SourceLocation RParenLoc) {
12204 TypeSourceInfo *ArgTInfo;
12205 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12206 if (ArgTy.isNull())
12207 return ExprError();
12210 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12212 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12216 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12218 Expr *LHSExpr, Expr *RHSExpr,
12219 SourceLocation RPLoc) {
12220 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12222 ExprValueKind VK = VK_RValue;
12223 ExprObjectKind OK = OK_Ordinary;
12225 bool ValueDependent = false;
12226 bool CondIsTrue = false;
12227 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12228 resType = Context.DependentTy;
12229 ValueDependent = true;
12231 // The conditional expression is required to be a constant expression.
12232 llvm::APSInt condEval(32);
12234 = VerifyIntegerConstantExpression(CondExpr, &condEval,
12235 diag::err_typecheck_choose_expr_requires_constant, false);
12236 if (CondICE.isInvalid())
12237 return ExprError();
12238 CondExpr = CondICE.get();
12239 CondIsTrue = condEval.getZExtValue();
12241 // If the condition is > zero, then the AST type is the same as the LSHExpr.
12242 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12244 resType = ActiveExpr->getType();
12245 ValueDependent = ActiveExpr->isValueDependent();
12246 VK = ActiveExpr->getValueKind();
12247 OK = ActiveExpr->getObjectKind();
12250 return new (Context)
12251 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12252 CondIsTrue, resType->isDependentType(), ValueDependent);
12255 //===----------------------------------------------------------------------===//
12256 // Clang Extensions.
12257 //===----------------------------------------------------------------------===//
12259 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12260 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12261 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12263 if (LangOpts.CPlusPlus) {
12264 Decl *ManglingContextDecl;
12265 if (MangleNumberingContext *MCtx =
12266 getCurrentMangleNumberContext(Block->getDeclContext(),
12267 ManglingContextDecl)) {
12268 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12269 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12273 PushBlockScope(CurScope, Block);
12274 CurContext->addDecl(Block);
12276 PushDeclContext(CurScope, Block);
12278 CurContext = Block;
12280 getCurBlock()->HasImplicitReturnType = true;
12282 // Enter a new evaluation context to insulate the block from any
12283 // cleanups from the enclosing full-expression.
12284 PushExpressionEvaluationContext(
12285 ExpressionEvaluationContext::PotentiallyEvaluated);
12288 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12290 assert(ParamInfo.getIdentifier() == nullptr &&
12291 "block-id should have no identifier!");
12292 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12293 BlockScopeInfo *CurBlock = getCurBlock();
12295 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12296 QualType T = Sig->getType();
12298 // FIXME: We should allow unexpanded parameter packs here, but that would,
12299 // in turn, make the block expression contain unexpanded parameter packs.
12300 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12301 // Drop the parameters.
12302 FunctionProtoType::ExtProtoInfo EPI;
12303 EPI.HasTrailingReturn = false;
12304 EPI.TypeQuals |= DeclSpec::TQ_const;
12305 T = Context.getFunctionType(Context.DependentTy, None, EPI);
12306 Sig = Context.getTrivialTypeSourceInfo(T);
12309 // GetTypeForDeclarator always produces a function type for a block
12310 // literal signature. Furthermore, it is always a FunctionProtoType
12311 // unless the function was written with a typedef.
12312 assert(T->isFunctionType() &&
12313 "GetTypeForDeclarator made a non-function block signature");
12315 // Look for an explicit signature in that function type.
12316 FunctionProtoTypeLoc ExplicitSignature;
12318 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12319 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12321 // Check whether that explicit signature was synthesized by
12322 // GetTypeForDeclarator. If so, don't save that as part of the
12323 // written signature.
12324 if (ExplicitSignature.getLocalRangeBegin() ==
12325 ExplicitSignature.getLocalRangeEnd()) {
12326 // This would be much cheaper if we stored TypeLocs instead of
12327 // TypeSourceInfos.
12328 TypeLoc Result = ExplicitSignature.getReturnLoc();
12329 unsigned Size = Result.getFullDataSize();
12330 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12331 Sig->getTypeLoc().initializeFullCopy(Result, Size);
12333 ExplicitSignature = FunctionProtoTypeLoc();
12337 CurBlock->TheDecl->setSignatureAsWritten(Sig);
12338 CurBlock->FunctionType = T;
12340 const FunctionType *Fn = T->getAs<FunctionType>();
12341 QualType RetTy = Fn->getReturnType();
12343 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12345 CurBlock->TheDecl->setIsVariadic(isVariadic);
12347 // Context.DependentTy is used as a placeholder for a missing block
12348 // return type. TODO: what should we do with declarators like:
12350 // If the answer is "apply template argument deduction"....
12351 if (RetTy != Context.DependentTy) {
12352 CurBlock->ReturnType = RetTy;
12353 CurBlock->TheDecl->setBlockMissingReturnType(false);
12354 CurBlock->HasImplicitReturnType = false;
12357 // Push block parameters from the declarator if we had them.
12358 SmallVector<ParmVarDecl*, 8> Params;
12359 if (ExplicitSignature) {
12360 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12361 ParmVarDecl *Param = ExplicitSignature.getParam(I);
12362 if (Param->getIdentifier() == nullptr &&
12363 !Param->isImplicit() &&
12364 !Param->isInvalidDecl() &&
12365 !getLangOpts().CPlusPlus)
12366 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12367 Params.push_back(Param);
12370 // Fake up parameter variables if we have a typedef, like
12371 // ^ fntype { ... }
12372 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12373 for (const auto &I : Fn->param_types()) {
12374 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12375 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12376 Params.push_back(Param);
12380 // Set the parameters on the block decl.
12381 if (!Params.empty()) {
12382 CurBlock->TheDecl->setParams(Params);
12383 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12384 /*CheckParameterNames=*/false);
12387 // Finally we can process decl attributes.
12388 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12390 // Put the parameter variables in scope.
12391 for (auto AI : CurBlock->TheDecl->parameters()) {
12392 AI->setOwningFunction(CurBlock->TheDecl);
12394 // If this has an identifier, add it to the scope stack.
12395 if (AI->getIdentifier()) {
12396 CheckShadow(CurBlock->TheScope, AI);
12398 PushOnScopeChains(AI, CurBlock->TheScope);
12403 /// ActOnBlockError - If there is an error parsing a block, this callback
12404 /// is invoked to pop the information about the block from the action impl.
12405 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12406 // Leave the expression-evaluation context.
12407 DiscardCleanupsInEvaluationContext();
12408 PopExpressionEvaluationContext();
12410 // Pop off CurBlock, handle nested blocks.
12412 PopFunctionScopeInfo();
12415 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12416 /// literal was successfully completed. ^(int x){...}
12417 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12418 Stmt *Body, Scope *CurScope) {
12419 // If blocks are disabled, emit an error.
12420 if (!LangOpts.Blocks)
12421 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12423 // Leave the expression-evaluation context.
12424 if (hasAnyUnrecoverableErrorsInThisFunction())
12425 DiscardCleanupsInEvaluationContext();
12426 assert(!Cleanup.exprNeedsCleanups() &&
12427 "cleanups within block not correctly bound!");
12428 PopExpressionEvaluationContext();
12430 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12432 if (BSI->HasImplicitReturnType)
12433 deduceClosureReturnType(*BSI);
12437 QualType RetTy = Context.VoidTy;
12438 if (!BSI->ReturnType.isNull())
12439 RetTy = BSI->ReturnType;
12441 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12444 // Set the captured variables on the block.
12445 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12446 SmallVector<BlockDecl::Capture, 4> Captures;
12447 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12448 if (Cap.isThisCapture())
12450 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12451 Cap.isNested(), Cap.getInitExpr());
12452 Captures.push_back(NewCap);
12454 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12456 // If the user wrote a function type in some form, try to use that.
12457 if (!BSI->FunctionType.isNull()) {
12458 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12460 FunctionType::ExtInfo Ext = FTy->getExtInfo();
12461 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12463 // Turn protoless block types into nullary block types.
12464 if (isa<FunctionNoProtoType>(FTy)) {
12465 FunctionProtoType::ExtProtoInfo EPI;
12467 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12469 // Otherwise, if we don't need to change anything about the function type,
12470 // preserve its sugar structure.
12471 } else if (FTy->getReturnType() == RetTy &&
12472 (!NoReturn || FTy->getNoReturnAttr())) {
12473 BlockTy = BSI->FunctionType;
12475 // Otherwise, make the minimal modifications to the function type.
12477 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12478 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12479 EPI.TypeQuals = 0; // FIXME: silently?
12481 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12484 // If we don't have a function type, just build one from nothing.
12486 FunctionProtoType::ExtProtoInfo EPI;
12487 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12488 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12491 DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12492 BlockTy = Context.getBlockPointerType(BlockTy);
12494 // If needed, diagnose invalid gotos and switches in the block.
12495 if (getCurFunction()->NeedsScopeChecking() &&
12496 !PP.isCodeCompletionEnabled())
12497 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12499 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12501 // Try to apply the named return value optimization. We have to check again
12502 // if we can do this, though, because blocks keep return statements around
12503 // to deduce an implicit return type.
12504 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12505 !BSI->TheDecl->isDependentContext())
12506 computeNRVO(Body, BSI);
12508 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12509 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12510 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12512 // If the block isn't obviously global, i.e. it captures anything at
12513 // all, then we need to do a few things in the surrounding context:
12514 if (Result->getBlockDecl()->hasCaptures()) {
12515 // First, this expression has a new cleanup object.
12516 ExprCleanupObjects.push_back(Result->getBlockDecl());
12517 Cleanup.setExprNeedsCleanups(true);
12519 // It also gets a branch-protected scope if any of the captured
12520 // variables needs destruction.
12521 for (const auto &CI : Result->getBlockDecl()->captures()) {
12522 const VarDecl *var = CI.getVariable();
12523 if (var->getType().isDestructedType() != QualType::DK_none) {
12524 getCurFunction()->setHasBranchProtectedScope();
12533 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12534 SourceLocation RPLoc) {
12535 TypeSourceInfo *TInfo;
12536 GetTypeFromParser(Ty, &TInfo);
12537 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12540 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12541 Expr *E, TypeSourceInfo *TInfo,
12542 SourceLocation RPLoc) {
12543 Expr *OrigExpr = E;
12546 // CUDA device code does not support varargs.
12547 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12548 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12549 CUDAFunctionTarget T = IdentifyCUDATarget(F);
12550 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12551 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12555 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12556 // as Microsoft ABI on an actual Microsoft platform, where
12557 // __builtin_ms_va_list and __builtin_va_list are the same.)
12558 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12559 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12560 QualType MSVaListType = Context.getBuiltinMSVaListType();
12561 if (Context.hasSameType(MSVaListType, E->getType())) {
12562 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12563 return ExprError();
12568 // Get the va_list type
12569 QualType VaListType = Context.getBuiltinVaListType();
12571 if (VaListType->isArrayType()) {
12572 // Deal with implicit array decay; for example, on x86-64,
12573 // va_list is an array, but it's supposed to decay to
12574 // a pointer for va_arg.
12575 VaListType = Context.getArrayDecayedType(VaListType);
12576 // Make sure the input expression also decays appropriately.
12577 ExprResult Result = UsualUnaryConversions(E);
12578 if (Result.isInvalid())
12579 return ExprError();
12581 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12582 // If va_list is a record type and we are compiling in C++ mode,
12583 // check the argument using reference binding.
12584 InitializedEntity Entity = InitializedEntity::InitializeParameter(
12585 Context, Context.getLValueReferenceType(VaListType), false);
12586 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12587 if (Init.isInvalid())
12588 return ExprError();
12589 E = Init.getAs<Expr>();
12591 // Otherwise, the va_list argument must be an l-value because
12592 // it is modified by va_arg.
12593 if (!E->isTypeDependent() &&
12594 CheckForModifiableLvalue(E, BuiltinLoc, *this))
12595 return ExprError();
12599 if (!IsMS && !E->isTypeDependent() &&
12600 !Context.hasSameType(VaListType, E->getType()))
12601 return ExprError(Diag(E->getLocStart(),
12602 diag::err_first_argument_to_va_arg_not_of_type_va_list)
12603 << OrigExpr->getType() << E->getSourceRange());
12605 if (!TInfo->getType()->isDependentType()) {
12606 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12607 diag::err_second_parameter_to_va_arg_incomplete,
12608 TInfo->getTypeLoc()))
12609 return ExprError();
12611 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12613 diag::err_second_parameter_to_va_arg_abstract,
12614 TInfo->getTypeLoc()))
12615 return ExprError();
12617 if (!TInfo->getType().isPODType(Context)) {
12618 Diag(TInfo->getTypeLoc().getBeginLoc(),
12619 TInfo->getType()->isObjCLifetimeType()
12620 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12621 : diag::warn_second_parameter_to_va_arg_not_pod)
12622 << TInfo->getType()
12623 << TInfo->getTypeLoc().getSourceRange();
12626 // Check for va_arg where arguments of the given type will be promoted
12627 // (i.e. this va_arg is guaranteed to have undefined behavior).
12628 QualType PromoteType;
12629 if (TInfo->getType()->isPromotableIntegerType()) {
12630 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12631 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12632 PromoteType = QualType();
12634 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12635 PromoteType = Context.DoubleTy;
12636 if (!PromoteType.isNull())
12637 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12638 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12639 << TInfo->getType()
12641 << TInfo->getTypeLoc().getSourceRange());
12644 QualType T = TInfo->getType().getNonLValueExprType(Context);
12645 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12648 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12649 // The type of __null will be int or long, depending on the size of
12650 // pointers on the target.
12652 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12653 if (pw == Context.getTargetInfo().getIntWidth())
12654 Ty = Context.IntTy;
12655 else if (pw == Context.getTargetInfo().getLongWidth())
12656 Ty = Context.LongTy;
12657 else if (pw == Context.getTargetInfo().getLongLongWidth())
12658 Ty = Context.LongLongTy;
12660 llvm_unreachable("I don't know size of pointer!");
12663 return new (Context) GNUNullExpr(Ty, TokenLoc);
12666 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12668 if (!getLangOpts().ObjC1)
12671 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12675 if (!PT->isObjCIdType()) {
12676 // Check if the destination is the 'NSString' interface.
12677 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12678 if (!ID || !ID->getIdentifier()->isStr("NSString"))
12682 // Ignore any parens, implicit casts (should only be
12683 // array-to-pointer decays), and not-so-opaque values. The last is
12684 // important for making this trigger for property assignments.
12685 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12686 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12687 if (OV->getSourceExpr())
12688 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12690 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12691 if (!SL || !SL->isAscii())
12694 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12695 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12696 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12701 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12702 const Expr *SrcExpr) {
12703 if (!DstType->isFunctionPointerType() ||
12704 !SrcExpr->getType()->isFunctionType())
12707 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12711 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12715 return !S.checkAddressOfFunctionIsAvailable(FD,
12717 SrcExpr->getLocStart());
12720 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12721 SourceLocation Loc,
12722 QualType DstType, QualType SrcType,
12723 Expr *SrcExpr, AssignmentAction Action,
12724 bool *Complained) {
12726 *Complained = false;
12728 // Decode the result (notice that AST's are still created for extensions).
12729 bool CheckInferredResultType = false;
12730 bool isInvalid = false;
12731 unsigned DiagKind = 0;
12733 ConversionFixItGenerator ConvHints;
12734 bool MayHaveConvFixit = false;
12735 bool MayHaveFunctionDiff = false;
12736 const ObjCInterfaceDecl *IFace = nullptr;
12737 const ObjCProtocolDecl *PDecl = nullptr;
12741 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12745 DiagKind = diag::ext_typecheck_convert_pointer_int;
12746 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12747 MayHaveConvFixit = true;
12750 DiagKind = diag::ext_typecheck_convert_int_pointer;
12751 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12752 MayHaveConvFixit = true;
12754 case IncompatiblePointer:
12755 if (Action == AA_Passing_CFAudited)
12756 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12757 else if (SrcType->isFunctionPointerType() &&
12758 DstType->isFunctionPointerType())
12759 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12761 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12763 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12764 SrcType->isObjCObjectPointerType();
12765 if (Hint.isNull() && !CheckInferredResultType) {
12766 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12768 else if (CheckInferredResultType) {
12769 SrcType = SrcType.getUnqualifiedType();
12770 DstType = DstType.getUnqualifiedType();
12772 MayHaveConvFixit = true;
12774 case IncompatiblePointerSign:
12775 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12777 case FunctionVoidPointer:
12778 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12780 case IncompatiblePointerDiscardsQualifiers: {
12781 // Perform array-to-pointer decay if necessary.
12782 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12784 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12785 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12786 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12787 DiagKind = diag::err_typecheck_incompatible_address_space;
12791 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12792 DiagKind = diag::err_typecheck_incompatible_ownership;
12796 llvm_unreachable("unknown error case for discarding qualifiers!");
12799 case CompatiblePointerDiscardsQualifiers:
12800 // If the qualifiers lost were because we were applying the
12801 // (deprecated) C++ conversion from a string literal to a char*
12802 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
12803 // Ideally, this check would be performed in
12804 // checkPointerTypesForAssignment. However, that would require a
12805 // bit of refactoring (so that the second argument is an
12806 // expression, rather than a type), which should be done as part
12807 // of a larger effort to fix checkPointerTypesForAssignment for
12809 if (getLangOpts().CPlusPlus &&
12810 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12812 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12814 case IncompatibleNestedPointerQualifiers:
12815 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12817 case IntToBlockPointer:
12818 DiagKind = diag::err_int_to_block_pointer;
12820 case IncompatibleBlockPointer:
12821 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12823 case IncompatibleObjCQualifiedId: {
12824 if (SrcType->isObjCQualifiedIdType()) {
12825 const ObjCObjectPointerType *srcOPT =
12826 SrcType->getAs<ObjCObjectPointerType>();
12827 for (auto *srcProto : srcOPT->quals()) {
12831 if (const ObjCInterfaceType *IFaceT =
12832 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12833 IFace = IFaceT->getDecl();
12835 else if (DstType->isObjCQualifiedIdType()) {
12836 const ObjCObjectPointerType *dstOPT =
12837 DstType->getAs<ObjCObjectPointerType>();
12838 for (auto *dstProto : dstOPT->quals()) {
12842 if (const ObjCInterfaceType *IFaceT =
12843 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12844 IFace = IFaceT->getDecl();
12846 DiagKind = diag::warn_incompatible_qualified_id;
12849 case IncompatibleVectors:
12850 DiagKind = diag::warn_incompatible_vectors;
12852 case IncompatibleObjCWeakRef:
12853 DiagKind = diag::err_arc_weak_unavailable_assign;
12856 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12858 *Complained = true;
12862 DiagKind = diag::err_typecheck_convert_incompatible;
12863 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12864 MayHaveConvFixit = true;
12866 MayHaveFunctionDiff = true;
12870 QualType FirstType, SecondType;
12873 case AA_Initializing:
12874 // The destination type comes first.
12875 FirstType = DstType;
12876 SecondType = SrcType;
12881 case AA_Passing_CFAudited:
12882 case AA_Converting:
12885 // The source type comes first.
12886 FirstType = SrcType;
12887 SecondType = DstType;
12891 PartialDiagnostic FDiag = PDiag(DiagKind);
12892 if (Action == AA_Passing_CFAudited)
12893 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12895 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12897 // If we can fix the conversion, suggest the FixIts.
12898 assert(ConvHints.isNull() || Hint.isNull());
12899 if (!ConvHints.isNull()) {
12900 for (FixItHint &H : ConvHints.Hints)
12905 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12907 if (MayHaveFunctionDiff)
12908 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12911 if (DiagKind == diag::warn_incompatible_qualified_id &&
12912 PDecl && IFace && !IFace->hasDefinition())
12913 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12914 << IFace->getName() << PDecl->getName();
12916 if (SecondType == Context.OverloadTy)
12917 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12918 FirstType, /*TakingAddress=*/true);
12920 if (CheckInferredResultType)
12921 EmitRelatedResultTypeNote(SrcExpr);
12923 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12924 EmitRelatedResultTypeNoteForReturn(DstType);
12927 *Complained = true;
12931 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12932 llvm::APSInt *Result) {
12933 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12935 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12936 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12940 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12943 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12944 llvm::APSInt *Result,
12947 class IDDiagnoser : public VerifyICEDiagnoser {
12951 IDDiagnoser(unsigned DiagID)
12952 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12954 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12955 S.Diag(Loc, DiagID) << SR;
12957 } Diagnoser(DiagID);
12959 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12962 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12964 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12968 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12969 VerifyICEDiagnoser &Diagnoser,
12971 SourceLocation DiagLoc = E->getLocStart();
12973 if (getLangOpts().CPlusPlus11) {
12974 // C++11 [expr.const]p5:
12975 // If an expression of literal class type is used in a context where an
12976 // integral constant expression is required, then that class type shall
12977 // have a single non-explicit conversion function to an integral or
12978 // unscoped enumeration type
12979 ExprResult Converted;
12980 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12982 CXX11ConvertDiagnoser(bool Silent)
12983 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12986 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12987 QualType T) override {
12988 return S.Diag(Loc, diag::err_ice_not_integral) << T;
12991 SemaDiagnosticBuilder diagnoseIncomplete(
12992 Sema &S, SourceLocation Loc, QualType T) override {
12993 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12996 SemaDiagnosticBuilder diagnoseExplicitConv(
12997 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12998 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13001 SemaDiagnosticBuilder noteExplicitConv(
13002 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13003 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13004 << ConvTy->isEnumeralType() << ConvTy;
13007 SemaDiagnosticBuilder diagnoseAmbiguous(
13008 Sema &S, SourceLocation Loc, QualType T) override {
13009 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13012 SemaDiagnosticBuilder noteAmbiguous(
13013 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13014 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13015 << ConvTy->isEnumeralType() << ConvTy;
13018 SemaDiagnosticBuilder diagnoseConversion(
13019 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13020 llvm_unreachable("conversion functions are permitted");
13022 } ConvertDiagnoser(Diagnoser.Suppress);
13024 Converted = PerformContextualImplicitConversion(DiagLoc, E,
13026 if (Converted.isInvalid())
13028 E = Converted.get();
13029 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13030 return ExprError();
13031 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13032 // An ICE must be of integral or unscoped enumeration type.
13033 if (!Diagnoser.Suppress)
13034 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13035 return ExprError();
13038 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13039 // in the non-ICE case.
13040 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13042 *Result = E->EvaluateKnownConstInt(Context);
13046 Expr::EvalResult EvalResult;
13047 SmallVector<PartialDiagnosticAt, 8> Notes;
13048 EvalResult.Diag = &Notes;
13050 // Try to evaluate the expression, and produce diagnostics explaining why it's
13051 // not a constant expression as a side-effect.
13052 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13053 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13055 // In C++11, we can rely on diagnostics being produced for any expression
13056 // which is not a constant expression. If no diagnostics were produced, then
13057 // this is a constant expression.
13058 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13060 *Result = EvalResult.Val.getInt();
13064 // If our only note is the usual "invalid subexpression" note, just point
13065 // the caret at its location rather than producing an essentially
13067 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13068 diag::note_invalid_subexpr_in_const_expr) {
13069 DiagLoc = Notes[0].first;
13073 if (!Folded || !AllowFold) {
13074 if (!Diagnoser.Suppress) {
13075 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13076 for (const PartialDiagnosticAt &Note : Notes)
13077 Diag(Note.first, Note.second);
13080 return ExprError();
13083 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13084 for (const PartialDiagnosticAt &Note : Notes)
13085 Diag(Note.first, Note.second);
13088 *Result = EvalResult.Val.getInt();
13093 // Handle the case where we conclude a expression which we speculatively
13094 // considered to be unevaluated is actually evaluated.
13095 class TransformToPE : public TreeTransform<TransformToPE> {
13096 typedef TreeTransform<TransformToPE> BaseTransform;
13099 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13101 // Make sure we redo semantic analysis
13102 bool AlwaysRebuild() { return true; }
13104 // Make sure we handle LabelStmts correctly.
13105 // FIXME: This does the right thing, but maybe we need a more general
13106 // fix to TreeTransform?
13107 StmtResult TransformLabelStmt(LabelStmt *S) {
13108 S->getDecl()->setStmt(nullptr);
13109 return BaseTransform::TransformLabelStmt(S);
13112 // We need to special-case DeclRefExprs referring to FieldDecls which
13113 // are not part of a member pointer formation; normal TreeTransforming
13114 // doesn't catch this case because of the way we represent them in the AST.
13115 // FIXME: This is a bit ugly; is it really the best way to handle this
13118 // Error on DeclRefExprs referring to FieldDecls.
13119 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13120 if (isa<FieldDecl>(E->getDecl()) &&
13121 !SemaRef.isUnevaluatedContext())
13122 return SemaRef.Diag(E->getLocation(),
13123 diag::err_invalid_non_static_member_use)
13124 << E->getDecl() << E->getSourceRange();
13126 return BaseTransform::TransformDeclRefExpr(E);
13129 // Exception: filter out member pointer formation
13130 ExprResult TransformUnaryOperator(UnaryOperator *E) {
13131 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13134 return BaseTransform::TransformUnaryOperator(E);
13137 ExprResult TransformLambdaExpr(LambdaExpr *E) {
13138 // Lambdas never need to be transformed.
13144 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13145 assert(isUnevaluatedContext() &&
13146 "Should only transform unevaluated expressions");
13147 ExprEvalContexts.back().Context =
13148 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13149 if (isUnevaluatedContext())
13151 return TransformToPE(*this).TransformExpr(E);
13155 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13156 Decl *LambdaContextDecl,
13158 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13159 LambdaContextDecl, IsDecltype);
13161 if (!MaybeODRUseExprs.empty())
13162 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13166 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13167 ReuseLambdaContextDecl_t,
13169 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13170 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13173 void Sema::PopExpressionEvaluationContext() {
13174 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13175 unsigned NumTypos = Rec.NumTypos;
13177 if (!Rec.Lambdas.empty()) {
13178 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13180 if (Rec.isUnevaluated()) {
13181 // C++11 [expr.prim.lambda]p2:
13182 // A lambda-expression shall not appear in an unevaluated operand
13184 D = diag::err_lambda_unevaluated_operand;
13186 // C++1y [expr.const]p2:
13187 // A conditional-expression e is a core constant expression unless the
13188 // evaluation of e, following the rules of the abstract machine, would
13189 // evaluate [...] a lambda-expression.
13190 D = diag::err_lambda_in_constant_expression;
13193 // C++1z allows lambda expressions as core constant expressions.
13194 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13195 // 1607) from appearing within template-arguments and array-bounds that
13196 // are part of function-signatures. Be mindful that P0315 (Lambdas in
13197 // unevaluated contexts) might lift some of these restrictions in a
13199 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13200 for (const auto *L : Rec.Lambdas)
13201 Diag(L->getLocStart(), D);
13203 // Mark the capture expressions odr-used. This was deferred
13204 // during lambda expression creation.
13205 for (auto *Lambda : Rec.Lambdas) {
13206 for (auto *C : Lambda->capture_inits())
13207 MarkDeclarationsReferencedInExpr(C);
13212 // When are coming out of an unevaluated context, clear out any
13213 // temporaries that we may have created as part of the evaluation of
13214 // the expression in that context: they aren't relevant because they
13215 // will never be constructed.
13216 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13217 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13218 ExprCleanupObjects.end());
13219 Cleanup = Rec.ParentCleanup;
13220 CleanupVarDeclMarking();
13221 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13222 // Otherwise, merge the contexts together.
13224 Cleanup.mergeFrom(Rec.ParentCleanup);
13225 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13226 Rec.SavedMaybeODRUseExprs.end());
13229 // Pop the current expression evaluation context off the stack.
13230 ExprEvalContexts.pop_back();
13232 if (!ExprEvalContexts.empty())
13233 ExprEvalContexts.back().NumTypos += NumTypos;
13235 assert(NumTypos == 0 && "There are outstanding typos after popping the "
13236 "last ExpressionEvaluationContextRecord");
13239 void Sema::DiscardCleanupsInEvaluationContext() {
13240 ExprCleanupObjects.erase(
13241 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13242 ExprCleanupObjects.end());
13244 MaybeODRUseExprs.clear();
13247 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13248 if (!E->getType()->isVariablyModifiedType())
13250 return TransformToPotentiallyEvaluated(E);
13253 /// Are we within a context in which some evaluation could be performed (be it
13254 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13255 /// captured by C++'s idea of an "unevaluated context".
13256 static bool isEvaluatableContext(Sema &SemaRef) {
13257 switch (SemaRef.ExprEvalContexts.back().Context) {
13258 case Sema::ExpressionEvaluationContext::Unevaluated:
13259 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13260 case Sema::ExpressionEvaluationContext::DiscardedStatement:
13261 // Expressions in this context are never evaluated.
13264 case Sema::ExpressionEvaluationContext::UnevaluatedList:
13265 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13266 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13267 // Expressions in this context could be evaluated.
13270 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13271 // Referenced declarations will only be used if the construct in the
13272 // containing expression is used, at which point we'll be given another
13273 // turn to mark them.
13276 llvm_unreachable("Invalid context");
13279 /// Are we within a context in which references to resolved functions or to
13280 /// variables result in odr-use?
13281 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13282 // An expression in a template is not really an expression until it's been
13283 // instantiated, so it doesn't trigger odr-use.
13284 if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13287 switch (SemaRef.ExprEvalContexts.back().Context) {
13288 case Sema::ExpressionEvaluationContext::Unevaluated:
13289 case Sema::ExpressionEvaluationContext::UnevaluatedList:
13290 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13291 case Sema::ExpressionEvaluationContext::DiscardedStatement:
13294 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13295 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13298 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13301 llvm_unreachable("Invalid context");
13304 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13305 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13306 return Func->isConstexpr() &&
13307 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13310 /// \brief Mark a function referenced, and check whether it is odr-used
13311 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13312 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13313 bool MightBeOdrUse) {
13314 assert(Func && "No function?");
13316 Func->setReferenced();
13318 // C++11 [basic.def.odr]p3:
13319 // A function whose name appears as a potentially-evaluated expression is
13320 // odr-used if it is the unique lookup result or the selected member of a
13321 // set of overloaded functions [...].
13323 // We (incorrectly) mark overload resolution as an unevaluated context, so we
13324 // can just check that here.
13325 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13327 // Determine whether we require a function definition to exist, per
13328 // C++11 [temp.inst]p3:
13329 // Unless a function template specialization has been explicitly
13330 // instantiated or explicitly specialized, the function template
13331 // specialization is implicitly instantiated when the specialization is
13332 // referenced in a context that requires a function definition to exist.
13334 // That is either when this is an odr-use, or when a usage of a constexpr
13335 // function occurs within an evaluatable context.
13336 bool NeedDefinition =
13337 OdrUse || (isEvaluatableContext(*this) &&
13338 isImplicitlyDefinableConstexprFunction(Func));
13340 // C++14 [temp.expl.spec]p6:
13341 // If a template [...] is explicitly specialized then that specialization
13342 // shall be declared before the first use of that specialization that would
13343 // cause an implicit instantiation to take place, in every translation unit
13344 // in which such a use occurs
13345 if (NeedDefinition &&
13346 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13347 Func->getMemberSpecializationInfo()))
13348 checkSpecializationVisibility(Loc, Func);
13350 // C++14 [except.spec]p17:
13351 // An exception-specification is considered to be needed when:
13352 // - the function is odr-used or, if it appears in an unevaluated operand,
13353 // would be odr-used if the expression were potentially-evaluated;
13355 // Note, we do this even if MightBeOdrUse is false. That indicates that the
13356 // function is a pure virtual function we're calling, and in that case the
13357 // function was selected by overload resolution and we need to resolve its
13358 // exception specification for a different reason.
13359 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13360 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13361 ResolveExceptionSpec(Loc, FPT);
13363 // If we don't need to mark the function as used, and we don't need to
13364 // try to provide a definition, there's nothing more to do.
13365 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13366 (!NeedDefinition || Func->getBody()))
13369 // Note that this declaration has been used.
13370 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13371 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13372 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13373 if (Constructor->isDefaultConstructor()) {
13374 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13376 DefineImplicitDefaultConstructor(Loc, Constructor);
13377 } else if (Constructor->isCopyConstructor()) {
13378 DefineImplicitCopyConstructor(Loc, Constructor);
13379 } else if (Constructor->isMoveConstructor()) {
13380 DefineImplicitMoveConstructor(Loc, Constructor);
13382 } else if (Constructor->getInheritedConstructor()) {
13383 DefineInheritingConstructor(Loc, Constructor);
13385 } else if (CXXDestructorDecl *Destructor =
13386 dyn_cast<CXXDestructorDecl>(Func)) {
13387 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13388 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13389 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13391 DefineImplicitDestructor(Loc, Destructor);
13393 if (Destructor->isVirtual() && getLangOpts().AppleKext)
13394 MarkVTableUsed(Loc, Destructor->getParent());
13395 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13396 if (MethodDecl->isOverloadedOperator() &&
13397 MethodDecl->getOverloadedOperator() == OO_Equal) {
13398 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13399 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13400 if (MethodDecl->isCopyAssignmentOperator())
13401 DefineImplicitCopyAssignment(Loc, MethodDecl);
13402 else if (MethodDecl->isMoveAssignmentOperator())
13403 DefineImplicitMoveAssignment(Loc, MethodDecl);
13405 } else if (isa<CXXConversionDecl>(MethodDecl) &&
13406 MethodDecl->getParent()->isLambda()) {
13407 CXXConversionDecl *Conversion =
13408 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13409 if (Conversion->isLambdaToBlockPointerConversion())
13410 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13412 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13413 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13414 MarkVTableUsed(Loc, MethodDecl->getParent());
13417 // Recursive functions should be marked when used from another function.
13418 // FIXME: Is this really right?
13419 if (CurContext == Func) return;
13421 // Implicit instantiation of function templates and member functions of
13422 // class templates.
13423 if (Func->isImplicitlyInstantiable()) {
13424 bool AlreadyInstantiated = false;
13425 SourceLocation PointOfInstantiation = Loc;
13426 if (FunctionTemplateSpecializationInfo *SpecInfo
13427 = Func->getTemplateSpecializationInfo()) {
13428 if (SpecInfo->getPointOfInstantiation().isInvalid())
13429 SpecInfo->setPointOfInstantiation(Loc);
13430 else if (SpecInfo->getTemplateSpecializationKind()
13431 == TSK_ImplicitInstantiation) {
13432 AlreadyInstantiated = true;
13433 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13435 } else if (MemberSpecializationInfo *MSInfo
13436 = Func->getMemberSpecializationInfo()) {
13437 if (MSInfo->getPointOfInstantiation().isInvalid())
13438 MSInfo->setPointOfInstantiation(Loc);
13439 else if (MSInfo->getTemplateSpecializationKind()
13440 == TSK_ImplicitInstantiation) {
13441 AlreadyInstantiated = true;
13442 PointOfInstantiation = MSInfo->getPointOfInstantiation();
13446 if (!AlreadyInstantiated || Func->isConstexpr()) {
13447 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13448 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13449 CodeSynthesisContexts.size())
13450 PendingLocalImplicitInstantiations.push_back(
13451 std::make_pair(Func, PointOfInstantiation));
13452 else if (Func->isConstexpr())
13453 // Do not defer instantiations of constexpr functions, to avoid the
13454 // expression evaluator needing to call back into Sema if it sees a
13455 // call to such a function.
13456 InstantiateFunctionDefinition(PointOfInstantiation, Func);
13458 PendingInstantiations.push_back(std::make_pair(Func,
13459 PointOfInstantiation));
13460 // Notify the consumer that a function was implicitly instantiated.
13461 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13465 // Walk redefinitions, as some of them may be instantiable.
13466 for (auto i : Func->redecls()) {
13467 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13468 MarkFunctionReferenced(Loc, i, OdrUse);
13472 if (!OdrUse) return;
13474 // Keep track of used but undefined functions.
13475 if (!Func->isDefined()) {
13476 if (mightHaveNonExternalLinkage(Func))
13477 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13478 else if (Func->getMostRecentDecl()->isInlined() &&
13479 !LangOpts.GNUInline &&
13480 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13481 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13484 Func->markUsed(Context);
13488 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13489 ValueDecl *var, DeclContext *DC) {
13490 DeclContext *VarDC = var->getDeclContext();
13492 // If the parameter still belongs to the translation unit, then
13493 // we're actually just using one parameter in the declaration of
13495 if (isa<ParmVarDecl>(var) &&
13496 isa<TranslationUnitDecl>(VarDC))
13499 // For C code, don't diagnose about capture if we're not actually in code
13500 // right now; it's impossible to write a non-constant expression outside of
13501 // function context, so we'll get other (more useful) diagnostics later.
13503 // For C++, things get a bit more nasty... it would be nice to suppress this
13504 // diagnostic for certain cases like using a local variable in an array bound
13505 // for a member of a local class, but the correct predicate is not obvious.
13506 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13509 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13510 unsigned ContextKind = 3; // unknown
13511 if (isa<CXXMethodDecl>(VarDC) &&
13512 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13514 } else if (isa<FunctionDecl>(VarDC)) {
13516 } else if (isa<BlockDecl>(VarDC)) {
13520 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13521 << var << ValueKind << ContextKind << VarDC;
13522 S.Diag(var->getLocation(), diag::note_entity_declared_at)
13525 // FIXME: Add additional diagnostic info about class etc. which prevents
13530 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13531 bool &SubCapturesAreNested,
13532 QualType &CaptureType,
13533 QualType &DeclRefType) {
13534 // Check whether we've already captured it.
13535 if (CSI->CaptureMap.count(Var)) {
13536 // If we found a capture, any subcaptures are nested.
13537 SubCapturesAreNested = true;
13539 // Retrieve the capture type for this variable.
13540 CaptureType = CSI->getCapture(Var).getCaptureType();
13542 // Compute the type of an expression that refers to this variable.
13543 DeclRefType = CaptureType.getNonReferenceType();
13545 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13546 // are mutable in the sense that user can change their value - they are
13547 // private instances of the captured declarations.
13548 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13549 if (Cap.isCopyCapture() &&
13550 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13551 !(isa<CapturedRegionScopeInfo>(CSI) &&
13552 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13553 DeclRefType.addConst();
13559 // Only block literals, captured statements, and lambda expressions can
13560 // capture; other scopes don't work.
13561 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13562 SourceLocation Loc,
13563 const bool Diagnose, Sema &S) {
13564 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13565 return getLambdaAwareParentOfDeclContext(DC);
13566 else if (Var->hasLocalStorage()) {
13568 diagnoseUncapturableValueReference(S, Loc, Var, DC);
13573 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13574 // certain types of variables (unnamed, variably modified types etc.)
13575 // so check for eligibility.
13576 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13577 SourceLocation Loc,
13578 const bool Diagnose, Sema &S) {
13580 bool IsBlock = isa<BlockScopeInfo>(CSI);
13581 bool IsLambda = isa<LambdaScopeInfo>(CSI);
13583 // Lambdas are not allowed to capture unnamed variables
13584 // (e.g. anonymous unions).
13585 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13586 // assuming that's the intent.
13587 if (IsLambda && !Var->getDeclName()) {
13589 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13590 S.Diag(Var->getLocation(), diag::note_declared_at);
13595 // Prohibit variably-modified types in blocks; they're difficult to deal with.
13596 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13598 S.Diag(Loc, diag::err_ref_vm_type);
13599 S.Diag(Var->getLocation(), diag::note_previous_decl)
13600 << Var->getDeclName();
13604 // Prohibit structs with flexible array members too.
13605 // We cannot capture what is in the tail end of the struct.
13606 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13607 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13610 S.Diag(Loc, diag::err_ref_flexarray_type);
13612 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13613 << Var->getDeclName();
13614 S.Diag(Var->getLocation(), diag::note_previous_decl)
13615 << Var->getDeclName();
13620 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13621 // Lambdas and captured statements are not allowed to capture __block
13622 // variables; they don't support the expected semantics.
13623 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13625 S.Diag(Loc, diag::err_capture_block_variable)
13626 << Var->getDeclName() << !IsLambda;
13627 S.Diag(Var->getLocation(), diag::note_previous_decl)
13628 << Var->getDeclName();
13632 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13633 if (S.getLangOpts().OpenCL && IsBlock &&
13634 Var->getType()->isBlockPointerType()) {
13636 S.Diag(Loc, diag::err_opencl_block_ref_block);
13643 // Returns true if the capture by block was successful.
13644 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13645 SourceLocation Loc,
13646 const bool BuildAndDiagnose,
13647 QualType &CaptureType,
13648 QualType &DeclRefType,
13651 Expr *CopyExpr = nullptr;
13652 bool ByRef = false;
13654 // Blocks are not allowed to capture arrays.
13655 if (CaptureType->isArrayType()) {
13656 if (BuildAndDiagnose) {
13657 S.Diag(Loc, diag::err_ref_array_type);
13658 S.Diag(Var->getLocation(), diag::note_previous_decl)
13659 << Var->getDeclName();
13664 // Forbid the block-capture of autoreleasing variables.
13665 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13666 if (BuildAndDiagnose) {
13667 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13669 S.Diag(Var->getLocation(), diag::note_previous_decl)
13670 << Var->getDeclName();
13675 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13676 if (const auto *PT = CaptureType->getAs<PointerType>()) {
13677 // This function finds out whether there is an AttributedType of kind
13678 // attr_objc_ownership in Ty. The existence of AttributedType of kind
13679 // attr_objc_ownership implies __autoreleasing was explicitly specified
13680 // rather than being added implicitly by the compiler.
13681 auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13682 while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13683 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13686 // Peel off AttributedTypes that are not of kind objc_ownership.
13687 Ty = AttrTy->getModifiedType();
13693 QualType PointeeTy = PT->getPointeeType();
13695 if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13696 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13697 !IsObjCOwnershipAttributedType(PointeeTy)) {
13698 if (BuildAndDiagnose) {
13699 SourceLocation VarLoc = Var->getLocation();
13700 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13702 auto AddAutoreleaseNote =
13703 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13704 // Provide a fix-it for the '__autoreleasing' keyword at the
13705 // appropriate location in the variable's type.
13706 if (const auto *TSI = Var->getTypeSourceInfo()) {
13707 PointerTypeLoc PTL =
13708 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13710 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13711 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13713 if (Loc.isValid()) {
13714 StringRef CharAtLoc = Lexer::getSourceText(
13715 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13716 S.getSourceManager(), S.getLangOpts());
13717 AddAutoreleaseNote << FixItHint::CreateInsertion(
13718 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13719 ? " __autoreleasing "
13720 : " __autoreleasing");
13725 S.Diag(VarLoc, diag::note_declare_parameter_strong);
13730 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13731 if (HasBlocksAttr || CaptureType->isReferenceType() ||
13732 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13733 // Block capture by reference does not change the capture or
13734 // declaration reference types.
13737 // Block capture by copy introduces 'const'.
13738 CaptureType = CaptureType.getNonReferenceType().withConst();
13739 DeclRefType = CaptureType;
13741 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13742 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13743 // The capture logic needs the destructor, so make sure we mark it.
13744 // Usually this is unnecessary because most local variables have
13745 // their destructors marked at declaration time, but parameters are
13746 // an exception because it's technically only the call site that
13747 // actually requires the destructor.
13748 if (isa<ParmVarDecl>(Var))
13749 S.FinalizeVarWithDestructor(Var, Record);
13751 // Enter a new evaluation context to insulate the copy
13752 // full-expression.
13753 EnterExpressionEvaluationContext scope(
13754 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13756 // According to the blocks spec, the capture of a variable from
13757 // the stack requires a const copy constructor. This is not true
13758 // of the copy/move done to move a __block variable to the heap.
13759 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13760 DeclRefType.withConst(),
13764 = S.PerformCopyInitialization(
13765 InitializedEntity::InitializeBlock(Var->getLocation(),
13766 CaptureType, false),
13769 // Build a full-expression copy expression if initialization
13770 // succeeded and used a non-trivial constructor. Recover from
13771 // errors by pretending that the copy isn't necessary.
13772 if (!Result.isInvalid() &&
13773 !cast<CXXConstructExpr>(Result.get())->getConstructor()
13775 Result = S.MaybeCreateExprWithCleanups(Result);
13776 CopyExpr = Result.get();
13782 // Actually capture the variable.
13783 if (BuildAndDiagnose)
13784 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13785 SourceLocation(), CaptureType, CopyExpr);
13792 /// \brief Capture the given variable in the captured region.
13793 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13795 SourceLocation Loc,
13796 const bool BuildAndDiagnose,
13797 QualType &CaptureType,
13798 QualType &DeclRefType,
13799 const bool RefersToCapturedVariable,
13801 // By default, capture variables by reference.
13803 // Using an LValue reference type is consistent with Lambdas (see below).
13804 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13805 if (S.IsOpenMPCapturedDecl(Var))
13806 DeclRefType = DeclRefType.getUnqualifiedType();
13807 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13811 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13813 CaptureType = DeclRefType;
13815 Expr *CopyExpr = nullptr;
13816 if (BuildAndDiagnose) {
13817 // The current implementation assumes that all variables are captured
13818 // by references. Since there is no capture by copy, no expression
13819 // evaluation will be needed.
13820 RecordDecl *RD = RSI->TheRecordDecl;
13823 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13824 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13825 nullptr, false, ICIS_NoInit);
13826 Field->setImplicit(true);
13827 Field->setAccess(AS_private);
13828 RD->addDecl(Field);
13830 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13831 DeclRefType, VK_LValue, Loc);
13832 Var->setReferenced(true);
13833 Var->markUsed(S.Context);
13836 // Actually capture the variable.
13837 if (BuildAndDiagnose)
13838 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13839 SourceLocation(), CaptureType, CopyExpr);
13845 /// \brief Create a field within the lambda class for the variable
13846 /// being captured.
13847 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13848 QualType FieldType, QualType DeclRefType,
13849 SourceLocation Loc,
13850 bool RefersToCapturedVariable) {
13851 CXXRecordDecl *Lambda = LSI->Lambda;
13853 // Build the non-static data member.
13855 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13856 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13857 nullptr, false, ICIS_NoInit);
13858 Field->setImplicit(true);
13859 Field->setAccess(AS_private);
13860 Lambda->addDecl(Field);
13863 /// \brief Capture the given variable in the lambda.
13864 static bool captureInLambda(LambdaScopeInfo *LSI,
13866 SourceLocation Loc,
13867 const bool BuildAndDiagnose,
13868 QualType &CaptureType,
13869 QualType &DeclRefType,
13870 const bool RefersToCapturedVariable,
13871 const Sema::TryCaptureKind Kind,
13872 SourceLocation EllipsisLoc,
13873 const bool IsTopScope,
13876 // Determine whether we are capturing by reference or by value.
13877 bool ByRef = false;
13878 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13879 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13881 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13884 // Compute the type of the field that will capture this variable.
13886 // C++11 [expr.prim.lambda]p15:
13887 // An entity is captured by reference if it is implicitly or
13888 // explicitly captured but not captured by copy. It is
13889 // unspecified whether additional unnamed non-static data
13890 // members are declared in the closure type for entities
13891 // captured by reference.
13893 // FIXME: It is not clear whether we want to build an lvalue reference
13894 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13895 // to do the former, while EDG does the latter. Core issue 1249 will
13896 // clarify, but for now we follow GCC because it's a more permissive and
13897 // easily defensible position.
13898 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13900 // C++11 [expr.prim.lambda]p14:
13901 // For each entity captured by copy, an unnamed non-static
13902 // data member is declared in the closure type. The
13903 // declaration order of these members is unspecified. The type
13904 // of such a data member is the type of the corresponding
13905 // captured entity if the entity is not a reference to an
13906 // object, or the referenced type otherwise. [Note: If the
13907 // captured entity is a reference to a function, the
13908 // corresponding data member is also a reference to a
13909 // function. - end note ]
13910 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13911 if (!RefType->getPointeeType()->isFunctionType())
13912 CaptureType = RefType->getPointeeType();
13915 // Forbid the lambda copy-capture of autoreleasing variables.
13916 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13917 if (BuildAndDiagnose) {
13918 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13919 S.Diag(Var->getLocation(), diag::note_previous_decl)
13920 << Var->getDeclName();
13925 // Make sure that by-copy captures are of a complete and non-abstract type.
13926 if (BuildAndDiagnose) {
13927 if (!CaptureType->isDependentType() &&
13928 S.RequireCompleteType(Loc, CaptureType,
13929 diag::err_capture_of_incomplete_type,
13930 Var->getDeclName()))
13933 if (S.RequireNonAbstractType(Loc, CaptureType,
13934 diag::err_capture_of_abstract_type))
13939 // Capture this variable in the lambda.
13940 if (BuildAndDiagnose)
13941 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13942 RefersToCapturedVariable);
13944 // Compute the type of a reference to this captured variable.
13946 DeclRefType = CaptureType.getNonReferenceType();
13948 // C++ [expr.prim.lambda]p5:
13949 // The closure type for a lambda-expression has a public inline
13950 // function call operator [...]. This function call operator is
13951 // declared const (9.3.1) if and only if the lambda-expression's
13952 // parameter-declaration-clause is not followed by mutable.
13953 DeclRefType = CaptureType.getNonReferenceType();
13954 if (!LSI->Mutable && !CaptureType->isReferenceType())
13955 DeclRefType.addConst();
13958 // Add the capture.
13959 if (BuildAndDiagnose)
13960 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13961 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13966 bool Sema::tryCaptureVariable(
13967 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13968 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13969 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13970 // An init-capture is notionally from the context surrounding its
13971 // declaration, but its parent DC is the lambda class.
13972 DeclContext *VarDC = Var->getDeclContext();
13973 if (Var->isInitCapture())
13974 VarDC = VarDC->getParent();
13976 DeclContext *DC = CurContext;
13977 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13978 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13979 // We need to sync up the Declaration Context with the
13980 // FunctionScopeIndexToStopAt
13981 if (FunctionScopeIndexToStopAt) {
13982 unsigned FSIndex = FunctionScopes.size() - 1;
13983 while (FSIndex != MaxFunctionScopesIndex) {
13984 DC = getLambdaAwareParentOfDeclContext(DC);
13990 // If the variable is declared in the current context, there is no need to
13992 if (VarDC == DC) return true;
13994 // Capture global variables if it is required to use private copy of this
13996 bool IsGlobal = !Var->hasLocalStorage();
13997 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14000 // Walk up the stack to determine whether we can capture the variable,
14001 // performing the "simple" checks that don't depend on type. We stop when
14002 // we've either hit the declared scope of the variable or find an existing
14003 // capture of that variable. We start from the innermost capturing-entity
14004 // (the DC) and ensure that all intervening capturing-entities
14005 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14006 // declcontext can either capture the variable or have already captured
14008 CaptureType = Var->getType();
14009 DeclRefType = CaptureType.getNonReferenceType();
14010 bool Nested = false;
14011 bool Explicit = (Kind != TryCapture_Implicit);
14012 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14014 // Only block literals, captured statements, and lambda expressions can
14015 // capture; other scopes don't work.
14016 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14020 // We need to check for the parent *first* because, if we *have*
14021 // private-captured a global variable, we need to recursively capture it in
14022 // intermediate blocks, lambdas, etc.
14025 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14031 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
14032 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14035 // Check whether we've already captured it.
14036 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14038 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14041 // If we are instantiating a generic lambda call operator body,
14042 // we do not want to capture new variables. What was captured
14043 // during either a lambdas transformation or initial parsing
14045 if (isGenericLambdaCallOperatorSpecialization(DC)) {
14046 if (BuildAndDiagnose) {
14047 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14048 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14049 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14050 Diag(Var->getLocation(), diag::note_previous_decl)
14051 << Var->getDeclName();
14052 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14054 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14058 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14059 // certain types of variables (unnamed, variably modified types etc.)
14060 // so check for eligibility.
14061 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14064 // Try to capture variable-length arrays types.
14065 if (Var->getType()->isVariablyModifiedType()) {
14066 // We're going to walk down into the type and look for VLA
14068 QualType QTy = Var->getType();
14069 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14070 QTy = PVD->getOriginalType();
14071 captureVariablyModifiedType(Context, QTy, CSI);
14074 if (getLangOpts().OpenMP) {
14075 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14076 // OpenMP private variables should not be captured in outer scope, so
14077 // just break here. Similarly, global variables that are captured in a
14078 // target region should not be captured outside the scope of the region.
14079 if (RSI->CapRegionKind == CR_OpenMP) {
14080 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14081 // When we detect target captures we are looking from inside the
14082 // target region, therefore we need to propagate the capture from the
14083 // enclosing region. Therefore, the capture is not initially nested.
14085 FunctionScopesIndex--;
14087 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14088 Nested = !IsTargetCap;
14089 DeclRefType = DeclRefType.getUnqualifiedType();
14090 CaptureType = Context.getLValueReferenceType(DeclRefType);
14096 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14097 // No capture-default, and this is not an explicit capture
14098 // so cannot capture this variable.
14099 if (BuildAndDiagnose) {
14100 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14101 Diag(Var->getLocation(), diag::note_previous_decl)
14102 << Var->getDeclName();
14103 if (cast<LambdaScopeInfo>(CSI)->Lambda)
14104 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14105 diag::note_lambda_decl);
14106 // FIXME: If we error out because an outer lambda can not implicitly
14107 // capture a variable that an inner lambda explicitly captures, we
14108 // should have the inner lambda do the explicit capture - because
14109 // it makes for cleaner diagnostics later. This would purely be done
14110 // so that the diagnostic does not misleadingly claim that a variable
14111 // can not be captured by a lambda implicitly even though it is captured
14112 // explicitly. Suggestion:
14113 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14114 // at the function head
14115 // - cache the StartingDeclContext - this must be a lambda
14116 // - captureInLambda in the innermost lambda the variable.
14121 FunctionScopesIndex--;
14124 } while (!VarDC->Equals(DC));
14126 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14127 // computing the type of the capture at each step, checking type-specific
14128 // requirements, and adding captures if requested.
14129 // If the variable had already been captured previously, we start capturing
14130 // at the lambda nested within that one.
14131 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14133 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14135 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14136 if (!captureInBlock(BSI, Var, ExprLoc,
14137 BuildAndDiagnose, CaptureType,
14138 DeclRefType, Nested, *this))
14141 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14142 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14143 BuildAndDiagnose, CaptureType,
14144 DeclRefType, Nested, *this))
14148 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14149 if (!captureInLambda(LSI, Var, ExprLoc,
14150 BuildAndDiagnose, CaptureType,
14151 DeclRefType, Nested, Kind, EllipsisLoc,
14152 /*IsTopScope*/I == N - 1, *this))
14160 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14161 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14162 QualType CaptureType;
14163 QualType DeclRefType;
14164 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14165 /*BuildAndDiagnose=*/true, CaptureType,
14166 DeclRefType, nullptr);
14169 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14170 QualType CaptureType;
14171 QualType DeclRefType;
14172 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14173 /*BuildAndDiagnose=*/false, CaptureType,
14174 DeclRefType, nullptr);
14177 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14178 QualType CaptureType;
14179 QualType DeclRefType;
14181 // Determine whether we can capture this variable.
14182 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14183 /*BuildAndDiagnose=*/false, CaptureType,
14184 DeclRefType, nullptr))
14187 return DeclRefType;
14192 // If either the type of the variable or the initializer is dependent,
14193 // return false. Otherwise, determine whether the variable is a constant
14194 // expression. Use this if you need to know if a variable that might or
14195 // might not be dependent is truly a constant expression.
14196 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14197 ASTContext &Context) {
14199 if (Var->getType()->isDependentType())
14201 const VarDecl *DefVD = nullptr;
14202 Var->getAnyInitializer(DefVD);
14205 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14206 Expr *Init = cast<Expr>(Eval->Value);
14207 if (Init->isValueDependent())
14209 return IsVariableAConstantExpression(Var, Context);
14213 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14214 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14215 // an object that satisfies the requirements for appearing in a
14216 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14217 // is immediately applied." This function handles the lvalue-to-rvalue
14218 // conversion part.
14219 MaybeODRUseExprs.erase(E->IgnoreParens());
14221 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14222 // to a variable that is a constant expression, and if so, identify it as
14223 // a reference to a variable that does not involve an odr-use of that
14225 if (LambdaScopeInfo *LSI = getCurLambda()) {
14226 Expr *SansParensExpr = E->IgnoreParens();
14227 VarDecl *Var = nullptr;
14228 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14229 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14230 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14231 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14233 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14234 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14238 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14239 Res = CorrectDelayedTyposInExpr(Res);
14241 if (!Res.isUsable())
14244 // If a constant-expression is a reference to a variable where we delay
14245 // deciding whether it is an odr-use, just assume we will apply the
14246 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
14247 // (a non-type template argument), we have special handling anyway.
14248 UpdateMarkingForLValueToRValue(Res.get());
14252 void Sema::CleanupVarDeclMarking() {
14253 for (Expr *E : MaybeODRUseExprs) {
14255 SourceLocation Loc;
14256 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14257 Var = cast<VarDecl>(DRE->getDecl());
14258 Loc = DRE->getLocation();
14259 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14260 Var = cast<VarDecl>(ME->getMemberDecl());
14261 Loc = ME->getMemberLoc();
14263 llvm_unreachable("Unexpected expression");
14266 MarkVarDeclODRUsed(Var, Loc, *this,
14267 /*MaxFunctionScopeIndex Pointer*/ nullptr);
14270 MaybeODRUseExprs.clear();
14274 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14275 VarDecl *Var, Expr *E) {
14276 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14277 "Invalid Expr argument to DoMarkVarDeclReferenced");
14278 Var->setReferenced();
14280 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14282 bool OdrUseContext = isOdrUseContext(SemaRef);
14283 bool NeedDefinition =
14284 OdrUseContext || (isEvaluatableContext(SemaRef) &&
14285 Var->isUsableInConstantExpressions(SemaRef.Context));
14287 VarTemplateSpecializationDecl *VarSpec =
14288 dyn_cast<VarTemplateSpecializationDecl>(Var);
14289 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14290 "Can't instantiate a partial template specialization.");
14292 // If this might be a member specialization of a static data member, check
14293 // the specialization is visible. We already did the checks for variable
14294 // template specializations when we created them.
14295 if (NeedDefinition && TSK != TSK_Undeclared &&
14296 !isa<VarTemplateSpecializationDecl>(Var))
14297 SemaRef.checkSpecializationVisibility(Loc, Var);
14299 // Perform implicit instantiation of static data members, static data member
14300 // templates of class templates, and variable template specializations. Delay
14301 // instantiations of variable templates, except for those that could be used
14302 // in a constant expression.
14303 if (NeedDefinition && isTemplateInstantiation(TSK)) {
14304 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14306 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14307 if (Var->getPointOfInstantiation().isInvalid()) {
14308 // This is a modification of an existing AST node. Notify listeners.
14309 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14310 L->StaticDataMemberInstantiated(Var);
14311 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14312 // Don't bother trying to instantiate it again, unless we might need
14313 // its initializer before we get to the end of the TU.
14314 TryInstantiating = false;
14317 if (Var->getPointOfInstantiation().isInvalid())
14318 Var->setTemplateSpecializationKind(TSK, Loc);
14320 if (TryInstantiating) {
14321 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14322 bool InstantiationDependent = false;
14323 bool IsNonDependent =
14324 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14325 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14328 // Do not instantiate specializations that are still type-dependent.
14329 if (IsNonDependent) {
14330 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14331 // Do not defer instantiations of variables which could be used in a
14332 // constant expression.
14333 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14335 SemaRef.PendingInstantiations
14336 .push_back(std::make_pair(Var, PointOfInstantiation));
14342 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14343 // the requirements for appearing in a constant expression (5.19) and, if
14344 // it is an object, the lvalue-to-rvalue conversion (4.1)
14345 // is immediately applied." We check the first part here, and
14346 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14347 // Note that we use the C++11 definition everywhere because nothing in
14348 // C++03 depends on whether we get the C++03 version correct. The second
14349 // part does not apply to references, since they are not objects.
14350 if (OdrUseContext && E &&
14351 IsVariableAConstantExpression(Var, SemaRef.Context)) {
14352 // A reference initialized by a constant expression can never be
14353 // odr-used, so simply ignore it.
14354 if (!Var->getType()->isReferenceType())
14355 SemaRef.MaybeODRUseExprs.insert(E);
14356 } else if (OdrUseContext) {
14357 MarkVarDeclODRUsed(Var, Loc, SemaRef,
14358 /*MaxFunctionScopeIndex ptr*/ nullptr);
14359 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14360 // If this is a dependent context, we don't need to mark variables as
14361 // odr-used, but we may still need to track them for lambda capture.
14362 // FIXME: Do we also need to do this inside dependent typeid expressions
14363 // (which are modeled as unevaluated at this point)?
14364 const bool RefersToEnclosingScope =
14365 (SemaRef.CurContext != Var->getDeclContext() &&
14366 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14367 if (RefersToEnclosingScope) {
14368 LambdaScopeInfo *const LSI =
14369 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14370 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14371 // If a variable could potentially be odr-used, defer marking it so
14372 // until we finish analyzing the full expression for any
14373 // lvalue-to-rvalue
14374 // or discarded value conversions that would obviate odr-use.
14375 // Add it to the list of potential captures that will be analyzed
14376 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14377 // unless the variable is a reference that was initialized by a constant
14378 // expression (this will never need to be captured or odr-used).
14379 assert(E && "Capture variable should be used in an expression.");
14380 if (!Var->getType()->isReferenceType() ||
14381 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14382 LSI->addPotentialCapture(E->IgnoreParens());
14388 /// \brief Mark a variable referenced, and check whether it is odr-used
14389 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
14390 /// used directly for normal expressions referring to VarDecl.
14391 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14392 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14395 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14396 Decl *D, Expr *E, bool MightBeOdrUse) {
14397 if (SemaRef.isInOpenMPDeclareTargetContext())
14398 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14400 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14401 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14405 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14407 // If this is a call to a method via a cast, also mark the method in the
14408 // derived class used in case codegen can devirtualize the call.
14409 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14412 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14415 // Only attempt to devirtualize if this is truly a virtual call.
14416 bool IsVirtualCall = MD->isVirtual() &&
14417 ME->performsVirtualDispatch(SemaRef.getLangOpts());
14418 if (!IsVirtualCall)
14420 const Expr *Base = ME->getBase();
14421 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14422 if (!MostDerivedClassDecl)
14424 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14425 if (!DM || DM->isPure())
14427 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14430 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14431 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14432 // TODO: update this with DR# once a defect report is filed.
14433 // C++11 defect. The address of a pure member should not be an ODR use, even
14434 // if it's a qualified reference.
14435 bool OdrUse = true;
14436 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14437 if (Method->isVirtual())
14439 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14442 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14443 void Sema::MarkMemberReferenced(MemberExpr *E) {
14444 // C++11 [basic.def.odr]p2:
14445 // A non-overloaded function whose name appears as a potentially-evaluated
14446 // expression or a member of a set of candidate functions, if selected by
14447 // overload resolution when referred to from a potentially-evaluated
14448 // expression, is odr-used, unless it is a pure virtual function and its
14449 // name is not explicitly qualified.
14450 bool MightBeOdrUse = true;
14451 if (E->performsVirtualDispatch(getLangOpts())) {
14452 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14453 if (Method->isPure())
14454 MightBeOdrUse = false;
14456 SourceLocation Loc = E->getMemberLoc().isValid() ?
14457 E->getMemberLoc() : E->getLocStart();
14458 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14461 /// \brief Perform marking for a reference to an arbitrary declaration. It
14462 /// marks the declaration referenced, and performs odr-use checking for
14463 /// functions and variables. This method should not be used when building a
14464 /// normal expression which refers to a variable.
14465 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14466 bool MightBeOdrUse) {
14467 if (MightBeOdrUse) {
14468 if (auto *VD = dyn_cast<VarDecl>(D)) {
14469 MarkVariableReferenced(Loc, VD);
14473 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14474 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14477 D->setReferenced();
14481 // Mark all of the declarations used by a type as referenced.
14482 // FIXME: Not fully implemented yet! We need to have a better understanding
14483 // of when we're entering a context we should not recurse into.
14484 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14485 // TreeTransforms rebuilding the type in a new context. Rather than
14486 // duplicating the TreeTransform logic, we should consider reusing it here.
14487 // Currently that causes problems when rebuilding LambdaExprs.
14488 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14490 SourceLocation Loc;
14493 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14495 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14497 bool TraverseTemplateArgument(const TemplateArgument &Arg);
14501 bool MarkReferencedDecls::TraverseTemplateArgument(
14502 const TemplateArgument &Arg) {
14504 // A non-type template argument is a constant-evaluated context.
14505 EnterExpressionEvaluationContext Evaluated(
14506 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14507 if (Arg.getKind() == TemplateArgument::Declaration) {
14508 if (Decl *D = Arg.getAsDecl())
14509 S.MarkAnyDeclReferenced(Loc, D, true);
14510 } else if (Arg.getKind() == TemplateArgument::Expression) {
14511 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14515 return Inherited::TraverseTemplateArgument(Arg);
14518 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14519 MarkReferencedDecls Marker(*this, Loc);
14520 Marker.TraverseType(T);
14524 /// \brief Helper class that marks all of the declarations referenced by
14525 /// potentially-evaluated subexpressions as "referenced".
14526 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14528 bool SkipLocalVariables;
14531 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14533 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14534 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14536 void VisitDeclRefExpr(DeclRefExpr *E) {
14537 // If we were asked not to visit local variables, don't.
14538 if (SkipLocalVariables) {
14539 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14540 if (VD->hasLocalStorage())
14544 S.MarkDeclRefReferenced(E);
14547 void VisitMemberExpr(MemberExpr *E) {
14548 S.MarkMemberReferenced(E);
14549 Inherited::VisitMemberExpr(E);
14552 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14553 S.MarkFunctionReferenced(E->getLocStart(),
14554 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14555 Visit(E->getSubExpr());
14558 void VisitCXXNewExpr(CXXNewExpr *E) {
14559 if (E->getOperatorNew())
14560 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14561 if (E->getOperatorDelete())
14562 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14563 Inherited::VisitCXXNewExpr(E);
14566 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14567 if (E->getOperatorDelete())
14568 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14569 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14570 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14571 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14572 S.MarkFunctionReferenced(E->getLocStart(),
14573 S.LookupDestructor(Record));
14576 Inherited::VisitCXXDeleteExpr(E);
14579 void VisitCXXConstructExpr(CXXConstructExpr *E) {
14580 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14581 Inherited::VisitCXXConstructExpr(E);
14584 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14585 Visit(E->getExpr());
14588 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14589 Inherited::VisitImplicitCastExpr(E);
14591 if (E->getCastKind() == CK_LValueToRValue)
14592 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14597 /// \brief Mark any declarations that appear within this expression or any
14598 /// potentially-evaluated subexpressions as "referenced".
14600 /// \param SkipLocalVariables If true, don't mark local variables as
14602 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14603 bool SkipLocalVariables) {
14604 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14607 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14608 /// of the program being compiled.
14610 /// This routine emits the given diagnostic when the code currently being
14611 /// type-checked is "potentially evaluated", meaning that there is a
14612 /// possibility that the code will actually be executable. Code in sizeof()
14613 /// expressions, code used only during overload resolution, etc., are not
14614 /// potentially evaluated. This routine will suppress such diagnostics or,
14615 /// in the absolutely nutty case of potentially potentially evaluated
14616 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14619 /// This routine should be used for all diagnostics that describe the run-time
14620 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14621 /// Failure to do so will likely result in spurious diagnostics or failures
14622 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14623 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14624 const PartialDiagnostic &PD) {
14625 switch (ExprEvalContexts.back().Context) {
14626 case ExpressionEvaluationContext::Unevaluated:
14627 case ExpressionEvaluationContext::UnevaluatedList:
14628 case ExpressionEvaluationContext::UnevaluatedAbstract:
14629 case ExpressionEvaluationContext::DiscardedStatement:
14630 // The argument will never be evaluated, so don't complain.
14633 case ExpressionEvaluationContext::ConstantEvaluated:
14634 // Relevant diagnostics should be produced by constant evaluation.
14637 case ExpressionEvaluationContext::PotentiallyEvaluated:
14638 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14639 if (Statement && getCurFunctionOrMethodDecl()) {
14640 FunctionScopes.back()->PossiblyUnreachableDiags.
14641 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14652 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14653 CallExpr *CE, FunctionDecl *FD) {
14654 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14657 // If we're inside a decltype's expression, don't check for a valid return
14658 // type or construct temporaries until we know whether this is the last call.
14659 if (ExprEvalContexts.back().IsDecltype) {
14660 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14664 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14669 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14670 : FD(FD), CE(CE) { }
14672 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14674 S.Diag(Loc, diag::err_call_incomplete_return)
14675 << T << CE->getSourceRange();
14679 S.Diag(Loc, diag::err_call_function_incomplete_return)
14680 << CE->getSourceRange() << FD->getDeclName() << T;
14681 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14682 << FD->getDeclName();
14684 } Diagnoser(FD, CE);
14686 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14692 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14693 // will prevent this condition from triggering, which is what we want.
14694 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14695 SourceLocation Loc;
14697 unsigned diagnostic = diag::warn_condition_is_assignment;
14698 bool IsOrAssign = false;
14700 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14701 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14704 IsOrAssign = Op->getOpcode() == BO_OrAssign;
14706 // Greylist some idioms by putting them into a warning subcategory.
14707 if (ObjCMessageExpr *ME
14708 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14709 Selector Sel = ME->getSelector();
14711 // self = [<foo> init...]
14712 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14713 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14715 // <foo> = [<bar> nextObject]
14716 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14717 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14720 Loc = Op->getOperatorLoc();
14721 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14722 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14725 IsOrAssign = Op->getOperator() == OO_PipeEqual;
14726 Loc = Op->getOperatorLoc();
14727 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14728 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14730 // Not an assignment.
14734 Diag(Loc, diagnostic) << E->getSourceRange();
14736 SourceLocation Open = E->getLocStart();
14737 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14738 Diag(Loc, diag::note_condition_assign_silence)
14739 << FixItHint::CreateInsertion(Open, "(")
14740 << FixItHint::CreateInsertion(Close, ")");
14743 Diag(Loc, diag::note_condition_or_assign_to_comparison)
14744 << FixItHint::CreateReplacement(Loc, "!=");
14746 Diag(Loc, diag::note_condition_assign_to_comparison)
14747 << FixItHint::CreateReplacement(Loc, "==");
14750 /// \brief Redundant parentheses over an equality comparison can indicate
14751 /// that the user intended an assignment used as condition.
14752 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14753 // Don't warn if the parens came from a macro.
14754 SourceLocation parenLoc = ParenE->getLocStart();
14755 if (parenLoc.isInvalid() || parenLoc.isMacroID())
14757 // Don't warn for dependent expressions.
14758 if (ParenE->isTypeDependent())
14761 Expr *E = ParenE->IgnoreParens();
14763 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14764 if (opE->getOpcode() == BO_EQ &&
14765 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14766 == Expr::MLV_Valid) {
14767 SourceLocation Loc = opE->getOperatorLoc();
14769 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14770 SourceRange ParenERange = ParenE->getSourceRange();
14771 Diag(Loc, diag::note_equality_comparison_silence)
14772 << FixItHint::CreateRemoval(ParenERange.getBegin())
14773 << FixItHint::CreateRemoval(ParenERange.getEnd());
14774 Diag(Loc, diag::note_equality_comparison_to_assign)
14775 << FixItHint::CreateReplacement(Loc, "=");
14779 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14780 bool IsConstexpr) {
14781 DiagnoseAssignmentAsCondition(E);
14782 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14783 DiagnoseEqualityWithExtraParens(parenE);
14785 ExprResult result = CheckPlaceholderExpr(E);
14786 if (result.isInvalid()) return ExprError();
14789 if (!E->isTypeDependent()) {
14790 if (getLangOpts().CPlusPlus)
14791 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14793 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14794 if (ERes.isInvalid())
14795 return ExprError();
14798 QualType T = E->getType();
14799 if (!T->isScalarType()) { // C99 6.8.4.1p1
14800 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14801 << T << E->getSourceRange();
14802 return ExprError();
14804 CheckBoolLikeConversion(E, Loc);
14810 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14811 Expr *SubExpr, ConditionKind CK) {
14812 // Empty conditions are valid in for-statements.
14814 return ConditionResult();
14818 case ConditionKind::Boolean:
14819 Cond = CheckBooleanCondition(Loc, SubExpr);
14822 case ConditionKind::ConstexprIf:
14823 Cond = CheckBooleanCondition(Loc, SubExpr, true);
14826 case ConditionKind::Switch:
14827 Cond = CheckSwitchCondition(Loc, SubExpr);
14830 if (Cond.isInvalid())
14831 return ConditionError();
14833 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14834 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14835 if (!FullExpr.get())
14836 return ConditionError();
14838 return ConditionResult(*this, nullptr, FullExpr,
14839 CK == ConditionKind::ConstexprIf);
14843 /// A visitor for rebuilding a call to an __unknown_any expression
14844 /// to have an appropriate type.
14845 struct RebuildUnknownAnyFunction
14846 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14850 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14852 ExprResult VisitStmt(Stmt *S) {
14853 llvm_unreachable("unexpected statement!");
14856 ExprResult VisitExpr(Expr *E) {
14857 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14858 << E->getSourceRange();
14859 return ExprError();
14862 /// Rebuild an expression which simply semantically wraps another
14863 /// expression which it shares the type and value kind of.
14864 template <class T> ExprResult rebuildSugarExpr(T *E) {
14865 ExprResult SubResult = Visit(E->getSubExpr());
14866 if (SubResult.isInvalid()) return ExprError();
14868 Expr *SubExpr = SubResult.get();
14869 E->setSubExpr(SubExpr);
14870 E->setType(SubExpr->getType());
14871 E->setValueKind(SubExpr->getValueKind());
14872 assert(E->getObjectKind() == OK_Ordinary);
14876 ExprResult VisitParenExpr(ParenExpr *E) {
14877 return rebuildSugarExpr(E);
14880 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14881 return rebuildSugarExpr(E);
14884 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14885 ExprResult SubResult = Visit(E->getSubExpr());
14886 if (SubResult.isInvalid()) return ExprError();
14888 Expr *SubExpr = SubResult.get();
14889 E->setSubExpr(SubExpr);
14890 E->setType(S.Context.getPointerType(SubExpr->getType()));
14891 assert(E->getValueKind() == VK_RValue);
14892 assert(E->getObjectKind() == OK_Ordinary);
14896 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14897 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14899 E->setType(VD->getType());
14901 assert(E->getValueKind() == VK_RValue);
14902 if (S.getLangOpts().CPlusPlus &&
14903 !(isa<CXXMethodDecl>(VD) &&
14904 cast<CXXMethodDecl>(VD)->isInstance()))
14905 E->setValueKind(VK_LValue);
14910 ExprResult VisitMemberExpr(MemberExpr *E) {
14911 return resolveDecl(E, E->getMemberDecl());
14914 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14915 return resolveDecl(E, E->getDecl());
14920 /// Given a function expression of unknown-any type, try to rebuild it
14921 /// to have a function type.
14922 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14923 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14924 if (Result.isInvalid()) return ExprError();
14925 return S.DefaultFunctionArrayConversion(Result.get());
14929 /// A visitor for rebuilding an expression of type __unknown_anytype
14930 /// into one which resolves the type directly on the referring
14931 /// expression. Strict preservation of the original source
14932 /// structure is not a goal.
14933 struct RebuildUnknownAnyExpr
14934 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14938 /// The current destination type.
14941 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14942 : S(S), DestType(CastType) {}
14944 ExprResult VisitStmt(Stmt *S) {
14945 llvm_unreachable("unexpected statement!");
14948 ExprResult VisitExpr(Expr *E) {
14949 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14950 << E->getSourceRange();
14951 return ExprError();
14954 ExprResult VisitCallExpr(CallExpr *E);
14955 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14957 /// Rebuild an expression which simply semantically wraps another
14958 /// expression which it shares the type and value kind of.
14959 template <class T> ExprResult rebuildSugarExpr(T *E) {
14960 ExprResult SubResult = Visit(E->getSubExpr());
14961 if (SubResult.isInvalid()) return ExprError();
14962 Expr *SubExpr = SubResult.get();
14963 E->setSubExpr(SubExpr);
14964 E->setType(SubExpr->getType());
14965 E->setValueKind(SubExpr->getValueKind());
14966 assert(E->getObjectKind() == OK_Ordinary);
14970 ExprResult VisitParenExpr(ParenExpr *E) {
14971 return rebuildSugarExpr(E);
14974 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14975 return rebuildSugarExpr(E);
14978 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14979 const PointerType *Ptr = DestType->getAs<PointerType>();
14981 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14982 << E->getSourceRange();
14983 return ExprError();
14986 if (isa<CallExpr>(E->getSubExpr())) {
14987 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14988 << E->getSourceRange();
14989 return ExprError();
14992 assert(E->getValueKind() == VK_RValue);
14993 assert(E->getObjectKind() == OK_Ordinary);
14994 E->setType(DestType);
14996 // Build the sub-expression as if it were an object of the pointee type.
14997 DestType = Ptr->getPointeeType();
14998 ExprResult SubResult = Visit(E->getSubExpr());
14999 if (SubResult.isInvalid()) return ExprError();
15000 E->setSubExpr(SubResult.get());
15004 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15006 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15008 ExprResult VisitMemberExpr(MemberExpr *E) {
15009 return resolveDecl(E, E->getMemberDecl());
15012 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15013 return resolveDecl(E, E->getDecl());
15018 /// Rebuilds a call expression which yielded __unknown_anytype.
15019 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15020 Expr *CalleeExpr = E->getCallee();
15024 FK_FunctionPointer,
15029 QualType CalleeType = CalleeExpr->getType();
15030 if (CalleeType == S.Context.BoundMemberTy) {
15031 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15032 Kind = FK_MemberFunction;
15033 CalleeType = Expr::findBoundMemberType(CalleeExpr);
15034 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15035 CalleeType = Ptr->getPointeeType();
15036 Kind = FK_FunctionPointer;
15038 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15039 Kind = FK_BlockPointer;
15041 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15043 // Verify that this is a legal result type of a function.
15044 if (DestType->isArrayType() || DestType->isFunctionType()) {
15045 unsigned diagID = diag::err_func_returning_array_function;
15046 if (Kind == FK_BlockPointer)
15047 diagID = diag::err_block_returning_array_function;
15049 S.Diag(E->getExprLoc(), diagID)
15050 << DestType->isFunctionType() << DestType;
15051 return ExprError();
15054 // Otherwise, go ahead and set DestType as the call's result.
15055 E->setType(DestType.getNonLValueExprType(S.Context));
15056 E->setValueKind(Expr::getValueKindForType(DestType));
15057 assert(E->getObjectKind() == OK_Ordinary);
15059 // Rebuild the function type, replacing the result type with DestType.
15060 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15062 // __unknown_anytype(...) is a special case used by the debugger when
15063 // it has no idea what a function's signature is.
15065 // We want to build this call essentially under the K&R
15066 // unprototyped rules, but making a FunctionNoProtoType in C++
15067 // would foul up all sorts of assumptions. However, we cannot
15068 // simply pass all arguments as variadic arguments, nor can we
15069 // portably just call the function under a non-variadic type; see
15070 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15071 // However, it turns out that in practice it is generally safe to
15072 // call a function declared as "A foo(B,C,D);" under the prototype
15073 // "A foo(B,C,D,...);". The only known exception is with the
15074 // Windows ABI, where any variadic function is implicitly cdecl
15075 // regardless of its normal CC. Therefore we change the parameter
15076 // types to match the types of the arguments.
15078 // This is a hack, but it is far superior to moving the
15079 // corresponding target-specific code from IR-gen to Sema/AST.
15081 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15082 SmallVector<QualType, 8> ArgTypes;
15083 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15084 ArgTypes.reserve(E->getNumArgs());
15085 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15086 Expr *Arg = E->getArg(i);
15087 QualType ArgType = Arg->getType();
15088 if (E->isLValue()) {
15089 ArgType = S.Context.getLValueReferenceType(ArgType);
15090 } else if (E->isXValue()) {
15091 ArgType = S.Context.getRValueReferenceType(ArgType);
15093 ArgTypes.push_back(ArgType);
15095 ParamTypes = ArgTypes;
15097 DestType = S.Context.getFunctionType(DestType, ParamTypes,
15098 Proto->getExtProtoInfo());
15100 DestType = S.Context.getFunctionNoProtoType(DestType,
15101 FnType->getExtInfo());
15104 // Rebuild the appropriate pointer-to-function type.
15106 case FK_MemberFunction:
15110 case FK_FunctionPointer:
15111 DestType = S.Context.getPointerType(DestType);
15114 case FK_BlockPointer:
15115 DestType = S.Context.getBlockPointerType(DestType);
15119 // Finally, we can recurse.
15120 ExprResult CalleeResult = Visit(CalleeExpr);
15121 if (!CalleeResult.isUsable()) return ExprError();
15122 E->setCallee(CalleeResult.get());
15124 // Bind a temporary if necessary.
15125 return S.MaybeBindToTemporary(E);
15128 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15129 // Verify that this is a legal result type of a call.
15130 if (DestType->isArrayType() || DestType->isFunctionType()) {
15131 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15132 << DestType->isFunctionType() << DestType;
15133 return ExprError();
15136 // Rewrite the method result type if available.
15137 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15138 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15139 Method->setReturnType(DestType);
15142 // Change the type of the message.
15143 E->setType(DestType.getNonReferenceType());
15144 E->setValueKind(Expr::getValueKindForType(DestType));
15146 return S.MaybeBindToTemporary(E);
15149 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15150 // The only case we should ever see here is a function-to-pointer decay.
15151 if (E->getCastKind() == CK_FunctionToPointerDecay) {
15152 assert(E->getValueKind() == VK_RValue);
15153 assert(E->getObjectKind() == OK_Ordinary);
15155 E->setType(DestType);
15157 // Rebuild the sub-expression as the pointee (function) type.
15158 DestType = DestType->castAs<PointerType>()->getPointeeType();
15160 ExprResult Result = Visit(E->getSubExpr());
15161 if (!Result.isUsable()) return ExprError();
15163 E->setSubExpr(Result.get());
15165 } else if (E->getCastKind() == CK_LValueToRValue) {
15166 assert(E->getValueKind() == VK_RValue);
15167 assert(E->getObjectKind() == OK_Ordinary);
15169 assert(isa<BlockPointerType>(E->getType()));
15171 E->setType(DestType);
15173 // The sub-expression has to be a lvalue reference, so rebuild it as such.
15174 DestType = S.Context.getLValueReferenceType(DestType);
15176 ExprResult Result = Visit(E->getSubExpr());
15177 if (!Result.isUsable()) return ExprError();
15179 E->setSubExpr(Result.get());
15182 llvm_unreachable("Unhandled cast type!");
15186 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15187 ExprValueKind ValueKind = VK_LValue;
15188 QualType Type = DestType;
15190 // We know how to make this work for certain kinds of decls:
15193 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15194 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15195 DestType = Ptr->getPointeeType();
15196 ExprResult Result = resolveDecl(E, VD);
15197 if (Result.isInvalid()) return ExprError();
15198 return S.ImpCastExprToType(Result.get(), Type,
15199 CK_FunctionToPointerDecay, VK_RValue);
15202 if (!Type->isFunctionType()) {
15203 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15204 << VD << E->getSourceRange();
15205 return ExprError();
15207 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15208 // We must match the FunctionDecl's type to the hack introduced in
15209 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15210 // type. See the lengthy commentary in that routine.
15211 QualType FDT = FD->getType();
15212 const FunctionType *FnType = FDT->castAs<FunctionType>();
15213 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15214 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15215 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15216 SourceLocation Loc = FD->getLocation();
15217 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15218 FD->getDeclContext(),
15219 Loc, Loc, FD->getNameInfo().getName(),
15220 DestType, FD->getTypeSourceInfo(),
15221 SC_None, false/*isInlineSpecified*/,
15222 FD->hasPrototype(),
15223 false/*isConstexprSpecified*/);
15225 if (FD->getQualifier())
15226 NewFD->setQualifierInfo(FD->getQualifierLoc());
15228 SmallVector<ParmVarDecl*, 16> Params;
15229 for (const auto &AI : FT->param_types()) {
15230 ParmVarDecl *Param =
15231 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15232 Param->setScopeInfo(0, Params.size());
15233 Params.push_back(Param);
15235 NewFD->setParams(Params);
15236 DRE->setDecl(NewFD);
15237 VD = DRE->getDecl();
15241 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15242 if (MD->isInstance()) {
15243 ValueKind = VK_RValue;
15244 Type = S.Context.BoundMemberTy;
15247 // Function references aren't l-values in C.
15248 if (!S.getLangOpts().CPlusPlus)
15249 ValueKind = VK_RValue;
15252 } else if (isa<VarDecl>(VD)) {
15253 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15254 Type = RefTy->getPointeeType();
15255 } else if (Type->isFunctionType()) {
15256 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15257 << VD << E->getSourceRange();
15258 return ExprError();
15263 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15264 << VD << E->getSourceRange();
15265 return ExprError();
15268 // Modifying the declaration like this is friendly to IR-gen but
15269 // also really dangerous.
15270 VD->setType(DestType);
15272 E->setValueKind(ValueKind);
15276 /// Check a cast of an unknown-any type. We intentionally only
15277 /// trigger this for C-style casts.
15278 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15279 Expr *CastExpr, CastKind &CastKind,
15280 ExprValueKind &VK, CXXCastPath &Path) {
15281 // The type we're casting to must be either void or complete.
15282 if (!CastType->isVoidType() &&
15283 RequireCompleteType(TypeRange.getBegin(), CastType,
15284 diag::err_typecheck_cast_to_incomplete))
15285 return ExprError();
15287 // Rewrite the casted expression from scratch.
15288 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15289 if (!result.isUsable()) return ExprError();
15291 CastExpr = result.get();
15292 VK = CastExpr->getValueKind();
15293 CastKind = CK_NoOp;
15298 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15299 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15302 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15303 Expr *arg, QualType ¶mType) {
15304 // If the syntactic form of the argument is not an explicit cast of
15305 // any sort, just do default argument promotion.
15306 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15308 ExprResult result = DefaultArgumentPromotion(arg);
15309 if (result.isInvalid()) return ExprError();
15310 paramType = result.get()->getType();
15314 // Otherwise, use the type that was written in the explicit cast.
15315 assert(!arg->hasPlaceholderType());
15316 paramType = castArg->getTypeAsWritten();
15318 // Copy-initialize a parameter of that type.
15319 InitializedEntity entity =
15320 InitializedEntity::InitializeParameter(Context, paramType,
15321 /*consumed*/ false);
15322 return PerformCopyInitialization(entity, callLoc, arg);
15325 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15327 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15329 E = E->IgnoreParenImpCasts();
15330 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15331 E = call->getCallee();
15332 diagID = diag::err_uncasted_call_of_unknown_any;
15338 SourceLocation loc;
15340 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15341 loc = ref->getLocation();
15342 d = ref->getDecl();
15343 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15344 loc = mem->getMemberLoc();
15345 d = mem->getMemberDecl();
15346 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15347 diagID = diag::err_uncasted_call_of_unknown_any;
15348 loc = msg->getSelectorStartLoc();
15349 d = msg->getMethodDecl();
15351 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15352 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15353 << orig->getSourceRange();
15354 return ExprError();
15357 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15358 << E->getSourceRange();
15359 return ExprError();
15362 S.Diag(loc, diagID) << d << orig->getSourceRange();
15364 // Never recoverable.
15365 return ExprError();
15368 /// Check for operands with placeholder types and complain if found.
15369 /// Returns true if there was an error and no recovery was possible.
15370 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15371 if (!getLangOpts().CPlusPlus) {
15372 // C cannot handle TypoExpr nodes on either side of a binop because it
15373 // doesn't handle dependent types properly, so make sure any TypoExprs have
15374 // been dealt with before checking the operands.
15375 ExprResult Result = CorrectDelayedTyposInExpr(E);
15376 if (!Result.isUsable()) return ExprError();
15380 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15381 if (!placeholderType) return E;
15383 switch (placeholderType->getKind()) {
15385 // Overloaded expressions.
15386 case BuiltinType::Overload: {
15387 // Try to resolve a single function template specialization.
15388 // This is obligatory.
15389 ExprResult Result = E;
15390 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15393 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15394 // leaves Result unchanged on failure.
15396 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15399 // If that failed, try to recover with a call.
15400 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15401 /*complain*/ true);
15405 // Bound member functions.
15406 case BuiltinType::BoundMember: {
15407 ExprResult result = E;
15408 const Expr *BME = E->IgnoreParens();
15409 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15410 // Try to give a nicer diagnostic if it is a bound member that we recognize.
15411 if (isa<CXXPseudoDestructorExpr>(BME)) {
15412 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15413 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15414 if (ME->getMemberNameInfo().getName().getNameKind() ==
15415 DeclarationName::CXXDestructorName)
15416 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15418 tryToRecoverWithCall(result, PD,
15419 /*complain*/ true);
15423 // ARC unbridged casts.
15424 case BuiltinType::ARCUnbridgedCast: {
15425 Expr *realCast = stripARCUnbridgedCast(E);
15426 diagnoseARCUnbridgedCast(realCast);
15430 // Expressions of unknown type.
15431 case BuiltinType::UnknownAny:
15432 return diagnoseUnknownAnyExpr(*this, E);
15435 case BuiltinType::PseudoObject:
15436 return checkPseudoObjectRValue(E);
15438 case BuiltinType::BuiltinFn: {
15439 // Accept __noop without parens by implicitly converting it to a call expr.
15440 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15442 auto *FD = cast<FunctionDecl>(DRE->getDecl());
15443 if (FD->getBuiltinID() == Builtin::BI__noop) {
15444 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15445 CK_BuiltinFnToFnPtr).get();
15446 return new (Context) CallExpr(Context, E, None, Context.IntTy,
15447 VK_RValue, SourceLocation());
15451 Diag(E->getLocStart(), diag::err_builtin_fn_use);
15452 return ExprError();
15455 // Expressions of unknown type.
15456 case BuiltinType::OMPArraySection:
15457 Diag(E->getLocStart(), diag::err_omp_array_section_use);
15458 return ExprError();
15460 // Everything else should be impossible.
15461 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15462 case BuiltinType::Id:
15463 #include "clang/Basic/OpenCLImageTypes.def"
15464 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15465 #define PLACEHOLDER_TYPE(Id, SingletonId)
15466 #include "clang/AST/BuiltinTypes.def"
15470 llvm_unreachable("invalid placeholder type!");
15473 bool Sema::CheckCaseExpression(Expr *E) {
15474 if (E->isTypeDependent())
15476 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15477 return E->getType()->isIntegralOrEnumerationType();
15481 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15483 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15484 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15485 "Unknown Objective-C Boolean value!");
15486 QualType BoolT = Context.ObjCBuiltinBoolTy;
15487 if (!Context.getBOOLDecl()) {
15488 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15489 Sema::LookupOrdinaryName);
15490 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15491 NamedDecl *ND = Result.getFoundDecl();
15492 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15493 Context.setBOOLDecl(TD);
15496 if (Context.getBOOLDecl())
15497 BoolT = Context.getBOOLType();
15498 return new (Context)
15499 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15502 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15503 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15504 SourceLocation RParen) {
15506 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15508 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15509 [&](const AvailabilitySpec &Spec) {
15510 return Spec.getPlatform() == Platform;
15513 VersionTuple Version;
15514 if (Spec != AvailSpecs.end())
15515 Version = Spec->getVersion();
15517 return new (Context)
15518 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);