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/FixedPoint.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaFixItUtils.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 using namespace clang;
52 /// Determine whether the use of this declaration is valid, without
53 /// emitting diagnostics.
54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
55 // See if this is an auto-typed variable whose initializer we are parsing.
56 if (ParsingInitForAutoVars.count(D))
59 // See if this is a deleted function.
60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64 // If the function has a deduced return type, and we can't deduce it,
65 // then we can't use it either.
66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
70 // See if this is an aligned allocation/deallocation function that is
72 if (TreatUnavailableAsInvalid &&
73 isUnavailableAlignedAllocationFunction(*FD))
77 // See if this function is unavailable.
78 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
79 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
85 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
86 // Warn if this is used but marked unused.
87 if (const auto *A = D->getAttr<UnusedAttr>()) {
88 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
89 // should diagnose them.
90 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
91 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
92 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
93 if (DC && !DC->hasAttr<UnusedAttr>())
94 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
99 /// Emit a note explaining that this function is deleted.
100 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
101 assert(Decl->isDeleted());
103 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
105 if (Method && Method->isDeleted() && Method->isDefaulted()) {
106 // If the method was explicitly defaulted, point at that declaration.
107 if (!Method->isImplicit())
108 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110 // Try to diagnose why this special member function was implicitly
111 // deleted. This might fail, if that reason no longer applies.
112 CXXSpecialMember CSM = getSpecialMember(Method);
113 if (CSM != CXXInvalid)
114 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
119 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
120 if (Ctor && Ctor->isInheritingConstructor())
121 return NoteDeletedInheritingConstructor(Ctor);
123 Diag(Decl->getLocation(), diag::note_availability_specified_here)
127 /// Determine whether a FunctionDecl was ever declared with an
128 /// explicit storage class.
129 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
130 for (auto I : D->redecls()) {
131 if (I->getStorageClass() != SC_None)
137 /// Check whether we're in an extern inline function and referring to a
138 /// variable or function with internal linkage (C11 6.7.4p3).
140 /// This is only a warning because we used to silently accept this code, but
141 /// in many cases it will not behave correctly. This is not enabled in C++ mode
142 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
143 /// and so while there may still be user mistakes, most of the time we can't
144 /// prove that there are errors.
145 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
147 SourceLocation Loc) {
148 // This is disabled under C++; there are too many ways for this to fire in
149 // contexts where the warning is a false positive, or where it is technically
150 // correct but benign.
151 if (S.getLangOpts().CPlusPlus)
154 // Check if this is an inlined function or method.
155 FunctionDecl *Current = S.getCurFunctionDecl();
158 if (!Current->isInlined())
160 if (!Current->isExternallyVisible())
163 // Check if the decl has internal linkage.
164 if (D->getFormalLinkage() != InternalLinkage)
167 // Downgrade from ExtWarn to Extension if
168 // (1) the supposedly external inline function is in the main file,
169 // and probably won't be included anywhere else.
170 // (2) the thing we're referencing is a pure function.
171 // (3) the thing we're referencing is another inline function.
172 // This last can give us false negatives, but it's better than warning on
173 // wrappers for simple C library functions.
174 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
175 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
176 if (!DowngradeWarning && UsedFn)
177 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
179 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
180 : diag::ext_internal_in_extern_inline)
181 << /*IsVar=*/!UsedFn << D;
183 S.MaybeSuggestAddingStaticToDecl(Current);
185 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
189 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
190 const FunctionDecl *First = Cur->getFirstDecl();
192 // Suggest "static" on the function, if possible.
193 if (!hasAnyExplicitStorageClass(First)) {
194 SourceLocation DeclBegin = First->getSourceRange().getBegin();
195 Diag(DeclBegin, diag::note_convert_inline_to_static)
196 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
200 /// Determine whether the use of this declaration is valid, and
201 /// emit any corresponding diagnostics.
203 /// This routine diagnoses various problems with referencing
204 /// declarations that can occur when using a declaration. For example,
205 /// it might warn if a deprecated or unavailable declaration is being
206 /// used, or produce an error (and return true) if a C++0x deleted
207 /// function is being used.
209 /// \returns true if there was an error (this declaration cannot be
210 /// referenced), false otherwise.
212 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
213 const ObjCInterfaceDecl *UnknownObjCClass,
214 bool ObjCPropertyAccess,
215 bool AvoidPartialAvailabilityChecks,
216 ObjCInterfaceDecl *ClassReceiver) {
217 SourceLocation Loc = Locs.front();
218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
219 // If there were any diagnostics suppressed by template argument deduction,
221 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
222 if (Pos != SuppressedDiagnostics.end()) {
223 for (const PartialDiagnosticAt &Suppressed : Pos->second)
224 Diag(Suppressed.first, Suppressed.second);
226 // Clear out the list of suppressed diagnostics, so that we don't emit
227 // them again for this specialization. However, we don't obsolete this
228 // entry from the table, because we want to avoid ever emitting these
229 // diagnostics again.
233 // C++ [basic.start.main]p3:
234 // The function 'main' shall not be used within a program.
235 if (cast<FunctionDecl>(D)->isMain())
236 Diag(Loc, diag::ext_main_used);
238 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
241 // See if this is an auto-typed variable whose initializer we are parsing.
242 if (ParsingInitForAutoVars.count(D)) {
243 if (isa<BindingDecl>(D)) {
244 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
247 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
248 << D->getDeclName() << cast<VarDecl>(D)->getType();
253 // See if this is a deleted function.
254 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
255 if (FD->isDeleted()) {
256 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
257 if (Ctor && Ctor->isInheritingConstructor())
258 Diag(Loc, diag::err_deleted_inherited_ctor_use)
260 << Ctor->getInheritedConstructor().getConstructor()->getParent();
262 Diag(Loc, diag::err_deleted_function_use);
263 NoteDeletedFunction(FD);
267 // If the function has a deduced return type, and we can't deduce it,
268 // then we can't use it either.
269 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
270 DeduceReturnType(FD, Loc))
273 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
277 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
278 // Lambdas are only default-constructible or assignable in C++2a onwards.
279 if (MD->getParent()->isLambda() &&
280 ((isa<CXXConstructorDecl>(MD) &&
281 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
282 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
283 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
284 << !isa<CXXConstructorDecl>(MD);
288 auto getReferencedObjCProp = [](const NamedDecl *D) ->
289 const ObjCPropertyDecl * {
290 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
291 return MD->findPropertyDecl();
294 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
295 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
297 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
301 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
302 // Only the variables omp_in and omp_out are allowed in the combiner.
303 // Only the variables omp_priv and omp_orig are allowed in the
304 // initializer-clause.
305 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
306 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
308 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
309 << getCurFunction()->HasOMPDeclareReductionCombiner;
310 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
314 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
315 AvoidPartialAvailabilityChecks, ClassReceiver);
317 DiagnoseUnusedOfDecl(*this, D, Loc);
319 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
324 /// Retrieve the message suffix that should be added to a
325 /// diagnostic complaining about the given function being deleted or
327 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
329 if (FD->getAvailability(&Message))
330 return ": " + Message;
332 return std::string();
335 /// DiagnoseSentinelCalls - This routine checks whether a call or
336 /// message-send is to a declaration with the sentinel attribute, and
337 /// if so, it checks that the requirements of the sentinel are
339 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
340 ArrayRef<Expr *> Args) {
341 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
345 // The number of formal parameters of the declaration.
346 unsigned numFormalParams;
348 // The kind of declaration. This is also an index into a %select in
350 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
352 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
353 numFormalParams = MD->param_size();
354 calleeType = CT_Method;
355 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
356 numFormalParams = FD->param_size();
357 calleeType = CT_Function;
358 } else if (isa<VarDecl>(D)) {
359 QualType type = cast<ValueDecl>(D)->getType();
360 const FunctionType *fn = nullptr;
361 if (const PointerType *ptr = type->getAs<PointerType>()) {
362 fn = ptr->getPointeeType()->getAs<FunctionType>();
364 calleeType = CT_Function;
365 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
366 fn = ptr->getPointeeType()->castAs<FunctionType>();
367 calleeType = CT_Block;
372 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
373 numFormalParams = proto->getNumParams();
381 // "nullPos" is the number of formal parameters at the end which
382 // effectively count as part of the variadic arguments. This is
383 // useful if you would prefer to not have *any* formal parameters,
384 // but the language forces you to have at least one.
385 unsigned nullPos = attr->getNullPos();
386 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
387 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
389 // The number of arguments which should follow the sentinel.
390 unsigned numArgsAfterSentinel = attr->getSentinel();
392 // If there aren't enough arguments for all the formal parameters,
393 // the sentinel, and the args after the sentinel, complain.
394 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
395 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
396 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
400 // Otherwise, find the sentinel expression.
401 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
402 if (!sentinelExpr) return;
403 if (sentinelExpr->isValueDependent()) return;
404 if (Context.isSentinelNullExpr(sentinelExpr)) return;
406 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
407 // or 'NULL' if those are actually defined in the context. Only use
408 // 'nil' for ObjC methods, where it's much more likely that the
409 // variadic arguments form a list of object pointers.
410 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
411 std::string NullValue;
412 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
414 else if (getLangOpts().CPlusPlus11)
415 NullValue = "nullptr";
416 else if (PP.isMacroDefined("NULL"))
419 NullValue = "(void*) 0";
421 if (MissingNilLoc.isInvalid())
422 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
424 Diag(MissingNilLoc, diag::warn_missing_sentinel)
426 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
427 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
430 SourceRange Sema::getExprRange(Expr *E) const {
431 return E ? E->getSourceRange() : SourceRange();
434 //===----------------------------------------------------------------------===//
435 // Standard Promotions and Conversions
436 //===----------------------------------------------------------------------===//
438 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
439 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
440 // Handle any placeholder expressions which made it here.
441 if (E->getType()->isPlaceholderType()) {
442 ExprResult result = CheckPlaceholderExpr(E);
443 if (result.isInvalid()) return ExprError();
447 QualType Ty = E->getType();
448 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
450 if (Ty->isFunctionType()) {
451 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
452 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
453 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
456 E = ImpCastExprToType(E, Context.getPointerType(Ty),
457 CK_FunctionToPointerDecay).get();
458 } else if (Ty->isArrayType()) {
459 // In C90 mode, arrays only promote to pointers if the array expression is
460 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
461 // type 'array of type' is converted to an expression that has type 'pointer
462 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
463 // that has type 'array of type' ...". The relevant change is "an lvalue"
464 // (C90) to "an expression" (C99).
467 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
468 // T" can be converted to an rvalue of type "pointer to T".
470 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
471 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
472 CK_ArrayToPointerDecay).get();
477 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
478 // Check to see if we are dereferencing a null pointer. If so,
479 // and if not volatile-qualified, this is undefined behavior that the
480 // optimizer will delete, so warn about it. People sometimes try to use this
481 // to get a deterministic trap and are surprised by clang's behavior. This
482 // only handles the pattern "*null", which is a very syntactic check.
483 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
484 if (UO->getOpcode() == UO_Deref &&
485 UO->getSubExpr()->IgnoreParenCasts()->
486 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
487 !UO->getType().isVolatileQualified()) {
488 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
489 S.PDiag(diag::warn_indirection_through_null)
490 << UO->getSubExpr()->getSourceRange());
491 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
492 S.PDiag(diag::note_indirection_through_null));
496 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
497 SourceLocation AssignLoc,
499 const ObjCIvarDecl *IV = OIRE->getDecl();
503 DeclarationName MemberName = IV->getDeclName();
504 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
505 if (!Member || !Member->isStr("isa"))
508 const Expr *Base = OIRE->getBase();
509 QualType BaseType = Base->getType();
511 BaseType = BaseType->getPointeeType();
512 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
513 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
514 ObjCInterfaceDecl *ClassDeclared = nullptr;
515 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
516 if (!ClassDeclared->getSuperClass()
517 && (*ClassDeclared->ivar_begin()) == IV) {
519 NamedDecl *ObjectSetClass =
520 S.LookupSingleName(S.TUScope,
521 &S.Context.Idents.get("object_setClass"),
522 SourceLocation(), S.LookupOrdinaryName);
523 if (ObjectSetClass) {
524 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
525 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
526 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
528 << FixItHint::CreateReplacement(
529 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
530 << FixItHint::CreateInsertion(RHSLocEnd, ")");
533 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
535 NamedDecl *ObjectGetClass =
536 S.LookupSingleName(S.TUScope,
537 &S.Context.Idents.get("object_getClass"),
538 SourceLocation(), S.LookupOrdinaryName);
540 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
541 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
543 << FixItHint::CreateReplacement(
544 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
546 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
548 S.Diag(IV->getLocation(), diag::note_ivar_decl);
553 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
554 // Handle any placeholder expressions which made it here.
555 if (E->getType()->isPlaceholderType()) {
556 ExprResult result = CheckPlaceholderExpr(E);
557 if (result.isInvalid()) return ExprError();
561 // C++ [conv.lval]p1:
562 // A glvalue of a non-function, non-array type T can be
563 // converted to a prvalue.
564 if (!E->isGLValue()) return E;
566 QualType T = E->getType();
567 assert(!T.isNull() && "r-value conversion on typeless expression?");
569 // We don't want to throw lvalue-to-rvalue casts on top of
570 // expressions of certain types in C++.
571 if (getLangOpts().CPlusPlus &&
572 (E->getType() == Context.OverloadTy ||
573 T->isDependentType() ||
577 // The C standard is actually really unclear on this point, and
578 // DR106 tells us what the result should be but not why. It's
579 // generally best to say that void types just doesn't undergo
580 // lvalue-to-rvalue at all. Note that expressions of unqualified
581 // 'void' type are never l-values, but qualified void can be.
585 // OpenCL usually rejects direct accesses to values of 'half' type.
586 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
588 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
593 CheckForNullPointerDereference(*this, E);
594 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
595 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
596 &Context.Idents.get("object_getClass"),
597 SourceLocation(), LookupOrdinaryName);
599 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
600 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
601 << FixItHint::CreateReplacement(
602 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
604 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
606 else if (const ObjCIvarRefExpr *OIRE =
607 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
608 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
610 // C++ [conv.lval]p1:
611 // [...] If T is a non-class type, the type of the prvalue is the
612 // cv-unqualified version of T. Otherwise, the type of the
616 // If the lvalue has qualified type, the value has the unqualified
617 // version of the type of the lvalue; otherwise, the value has the
618 // type of the lvalue.
619 if (T.hasQualifiers())
620 T = T.getUnqualifiedType();
622 // Under the MS ABI, lock down the inheritance model now.
623 if (T->isMemberPointerType() &&
624 Context.getTargetInfo().getCXXABI().isMicrosoft())
625 (void)isCompleteType(E->getExprLoc(), T);
627 UpdateMarkingForLValueToRValue(E);
629 // Loading a __weak object implicitly retains the value, so we need a cleanup to
631 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
632 Cleanup.setExprNeedsCleanups(true);
634 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
638 // ... if the lvalue has atomic type, the value has the non-atomic version
639 // of the type of the lvalue ...
640 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
641 T = Atomic->getValueType().getUnqualifiedType();
642 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
649 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
650 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
653 Res = DefaultLvalueConversion(Res.get());
659 /// CallExprUnaryConversions - a special case of an unary conversion
660 /// performed on a function designator of a call expression.
661 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
662 QualType Ty = E->getType();
664 // Only do implicit cast for a function type, but not for a pointer
666 if (Ty->isFunctionType()) {
667 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
668 CK_FunctionToPointerDecay).get();
672 Res = DefaultLvalueConversion(Res.get());
678 /// UsualUnaryConversions - Performs various conversions that are common to most
679 /// operators (C99 6.3). The conversions of array and function types are
680 /// sometimes suppressed. For example, the array->pointer conversion doesn't
681 /// apply if the array is an argument to the sizeof or address (&) operators.
682 /// In these instances, this routine should *not* be called.
683 ExprResult Sema::UsualUnaryConversions(Expr *E) {
684 // First, convert to an r-value.
685 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
690 QualType Ty = E->getType();
691 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
693 // Half FP have to be promoted to float unless it is natively supported
694 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
695 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
697 // Try to perform integral promotions if the object has a theoretically
699 if (Ty->isIntegralOrUnscopedEnumerationType()) {
702 // The following may be used in an expression wherever an int or
703 // unsigned int may be used:
704 // - an object or expression with an integer type whose integer
705 // conversion rank is less than or equal to the rank of int
707 // - A bit-field of type _Bool, int, signed int, or unsigned int.
709 // If an int can represent all values of the original type, the
710 // value is converted to an int; otherwise, it is converted to an
711 // unsigned int. These are called the integer promotions. All
712 // other types are unchanged by the integer promotions.
714 QualType PTy = Context.isPromotableBitField(E);
716 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
719 if (Ty->isPromotableIntegerType()) {
720 QualType PT = Context.getPromotedIntegerType(Ty);
721 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
728 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
729 /// do not have a prototype. Arguments that have type float or __fp16
730 /// are promoted to double. All other argument types are converted by
731 /// UsualUnaryConversions().
732 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
733 QualType Ty = E->getType();
734 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
736 ExprResult Res = UsualUnaryConversions(E);
741 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
742 // promote to double.
743 // Note that default argument promotion applies only to float (and
744 // half/fp16); it does not apply to _Float16.
745 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
746 if (BTy && (BTy->getKind() == BuiltinType::Half ||
747 BTy->getKind() == BuiltinType::Float)) {
748 if (getLangOpts().OpenCL &&
749 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
750 if (BTy->getKind() == BuiltinType::Half) {
751 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
754 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
758 // C++ performs lvalue-to-rvalue conversion as a default argument
759 // promotion, even on class types, but note:
760 // C++11 [conv.lval]p2:
761 // When an lvalue-to-rvalue conversion occurs in an unevaluated
762 // operand or a subexpression thereof the value contained in the
763 // referenced object is not accessed. Otherwise, if the glvalue
764 // has a class type, the conversion copy-initializes a temporary
765 // of type T from the glvalue and the result of the conversion
766 // is a prvalue for the temporary.
767 // FIXME: add some way to gate this entire thing for correctness in
768 // potentially potentially evaluated contexts.
769 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
770 ExprResult Temp = PerformCopyInitialization(
771 InitializedEntity::InitializeTemporary(E->getType()),
773 if (Temp.isInvalid())
781 /// Determine the degree of POD-ness for an expression.
782 /// Incomplete types are considered POD, since this check can be performed
783 /// when we're in an unevaluated context.
784 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
785 if (Ty->isIncompleteType()) {
786 // C++11 [expr.call]p7:
787 // After these conversions, if the argument does not have arithmetic,
788 // enumeration, pointer, pointer to member, or class type, the program
791 // Since we've already performed array-to-pointer and function-to-pointer
792 // decay, the only such type in C++ is cv void. This also handles
793 // initializer lists as variadic arguments.
794 if (Ty->isVoidType())
797 if (Ty->isObjCObjectType())
802 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
805 if (Ty.isCXX98PODType(Context))
808 // C++11 [expr.call]p7:
809 // Passing a potentially-evaluated argument of class type (Clause 9)
810 // having a non-trivial copy constructor, a non-trivial move constructor,
811 // or a non-trivial destructor, with no corresponding parameter,
812 // is conditionally-supported with implementation-defined semantics.
813 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
814 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
815 if (!Record->hasNonTrivialCopyConstructor() &&
816 !Record->hasNonTrivialMoveConstructor() &&
817 !Record->hasNonTrivialDestructor())
818 return VAK_ValidInCXX11;
820 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
823 if (Ty->isObjCObjectType())
826 if (getLangOpts().MSVCCompat)
827 return VAK_MSVCUndefined;
829 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
830 // permitted to reject them. We should consider doing so.
831 return VAK_Undefined;
834 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
835 // Don't allow one to pass an Objective-C interface to a vararg.
836 const QualType &Ty = E->getType();
837 VarArgKind VAK = isValidVarArgType(Ty);
839 // Complain about passing non-POD types through varargs.
841 case VAK_ValidInCXX11:
843 E->getBeginLoc(), nullptr,
844 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
847 if (Ty->isRecordType()) {
848 // This is unlikely to be what the user intended. If the class has a
849 // 'c_str' member function, the user probably meant to call that.
850 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
851 PDiag(diag::warn_pass_class_arg_to_vararg)
852 << Ty << CT << hasCStrMethod(E) << ".c_str()");
857 case VAK_MSVCUndefined:
858 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
859 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
860 << getLangOpts().CPlusPlus11 << Ty << CT);
864 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
865 Diag(E->getBeginLoc(),
866 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
868 else if (Ty->isObjCObjectType())
869 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
870 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
873 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
874 << isa<InitListExpr>(E) << Ty << CT;
879 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
880 /// will create a trap if the resulting type is not a POD type.
881 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
882 FunctionDecl *FDecl) {
883 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
884 // Strip the unbridged-cast placeholder expression off, if applicable.
885 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
886 (CT == VariadicMethod ||
887 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
888 E = stripARCUnbridgedCast(E);
890 // Otherwise, do normal placeholder checking.
892 ExprResult ExprRes = CheckPlaceholderExpr(E);
893 if (ExprRes.isInvalid())
899 ExprResult ExprRes = DefaultArgumentPromotion(E);
900 if (ExprRes.isInvalid())
904 // Diagnostics regarding non-POD argument types are
905 // emitted along with format string checking in Sema::CheckFunctionCall().
906 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
907 // Turn this into a trap.
909 SourceLocation TemplateKWLoc;
911 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
913 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
915 if (TrapFn.isInvalid())
918 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
919 None, E->getEndLoc());
920 if (Call.isInvalid())
924 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
925 if (Comma.isInvalid())
930 if (!getLangOpts().CPlusPlus &&
931 RequireCompleteType(E->getExprLoc(), E->getType(),
932 diag::err_call_incomplete_argument))
938 /// Converts an integer to complex float type. Helper function of
939 /// UsualArithmeticConversions()
941 /// \return false if the integer expression is an integer type and is
942 /// successfully converted to the complex type.
943 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
944 ExprResult &ComplexExpr,
948 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
949 if (SkipCast) return false;
950 if (IntTy->isIntegerType()) {
951 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
952 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
953 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
954 CK_FloatingRealToComplex);
956 assert(IntTy->isComplexIntegerType());
957 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
958 CK_IntegralComplexToFloatingComplex);
963 /// Handle arithmetic conversion with complex types. Helper function of
964 /// UsualArithmeticConversions()
965 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
966 ExprResult &RHS, QualType LHSType,
969 // if we have an integer operand, the result is the complex type.
970 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
973 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
974 /*skipCast*/IsCompAssign))
977 // This handles complex/complex, complex/float, or float/complex.
978 // When both operands are complex, the shorter operand is converted to the
979 // type of the longer, and that is the type of the result. This corresponds
980 // to what is done when combining two real floating-point operands.
981 // The fun begins when size promotion occur across type domains.
982 // From H&S 6.3.4: When one operand is complex and the other is a real
983 // floating-point type, the less precise type is converted, within it's
984 // real or complex domain, to the precision of the other type. For example,
985 // when combining a "long double" with a "double _Complex", the
986 // "double _Complex" is promoted to "long double _Complex".
988 // Compute the rank of the two types, regardless of whether they are complex.
989 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
991 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
992 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
993 QualType LHSElementType =
994 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
995 QualType RHSElementType =
996 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
998 QualType ResultType = S.Context.getComplexType(LHSElementType);
1000 // Promote the precision of the LHS if not an assignment.
1001 ResultType = S.Context.getComplexType(RHSElementType);
1002 if (!IsCompAssign) {
1005 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1007 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1009 } else if (Order > 0) {
1010 // Promote the precision of the RHS.
1012 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1014 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1019 /// Handle arithmetic conversion from integer to float. Helper function
1020 /// of UsualArithmeticConversions()
1021 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1022 ExprResult &IntExpr,
1023 QualType FloatTy, QualType IntTy,
1024 bool ConvertFloat, bool ConvertInt) {
1025 if (IntTy->isIntegerType()) {
1027 // Convert intExpr to the lhs floating point type.
1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1029 CK_IntegralToFloating);
1033 // Convert both sides to the appropriate complex float.
1034 assert(IntTy->isComplexIntegerType());
1035 QualType result = S.Context.getComplexType(FloatTy);
1037 // _Complex int -> _Complex float
1039 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1040 CK_IntegralComplexToFloatingComplex);
1042 // float -> _Complex float
1044 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1045 CK_FloatingRealToComplex);
1050 /// Handle arithmethic conversion with floating point types. Helper
1051 /// function of UsualArithmeticConversions()
1052 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1053 ExprResult &RHS, QualType LHSType,
1054 QualType RHSType, bool IsCompAssign) {
1055 bool LHSFloat = LHSType->isRealFloatingType();
1056 bool RHSFloat = RHSType->isRealFloatingType();
1058 // If we have two real floating types, convert the smaller operand
1059 // to the bigger result.
1060 if (LHSFloat && RHSFloat) {
1061 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1063 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1067 assert(order < 0 && "illegal float comparison");
1069 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1074 // Half FP has to be promoted to float unless it is natively supported
1075 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1076 LHSType = S.Context.FloatTy;
1078 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1079 /*convertFloat=*/!IsCompAssign,
1080 /*convertInt=*/ true);
1083 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1084 /*convertInt=*/ true,
1085 /*convertFloat=*/!IsCompAssign);
1088 /// Diagnose attempts to convert between __float128 and long double if
1089 /// there is no support for such conversion. Helper function of
1090 /// UsualArithmeticConversions().
1091 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1093 /* No issue converting if at least one of the types is not a floating point
1094 type or the two types have the same rank.
1096 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1097 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1100 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1101 "The remaining types must be floating point types.");
1103 auto *LHSComplex = LHSType->getAs<ComplexType>();
1104 auto *RHSComplex = RHSType->getAs<ComplexType>();
1106 QualType LHSElemType = LHSComplex ?
1107 LHSComplex->getElementType() : LHSType;
1108 QualType RHSElemType = RHSComplex ?
1109 RHSComplex->getElementType() : RHSType;
1111 // No issue if the two types have the same representation
1112 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1113 &S.Context.getFloatTypeSemantics(RHSElemType))
1116 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1117 RHSElemType == S.Context.LongDoubleTy);
1118 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1119 RHSElemType == S.Context.Float128Ty);
1121 // We've handled the situation where __float128 and long double have the same
1122 // representation. We allow all conversions for all possible long double types
1123 // except PPC's double double.
1124 return Float128AndLongDouble &&
1125 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1126 &llvm::APFloat::PPCDoubleDouble());
1129 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1132 /// These helper callbacks are placed in an anonymous namespace to
1133 /// permit their use as function template parameters.
1134 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1135 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1138 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1139 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1140 CK_IntegralComplexCast);
1144 /// Handle integer arithmetic conversions. Helper function of
1145 /// UsualArithmeticConversions()
1146 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1147 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1148 ExprResult &RHS, QualType LHSType,
1149 QualType RHSType, bool IsCompAssign) {
1150 // The rules for this case are in C99 6.3.1.8
1151 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1152 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1153 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1154 if (LHSSigned == RHSSigned) {
1155 // Same signedness; use the higher-ranked type
1157 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1159 } else if (!IsCompAssign)
1160 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162 } else if (order != (LHSSigned ? 1 : -1)) {
1163 // The unsigned type has greater than or equal rank to the
1164 // signed type, so use the unsigned type
1166 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1168 } else if (!IsCompAssign)
1169 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1171 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1172 // The two types are different widths; if we are here, that
1173 // means the signed type is larger than the unsigned type, so
1174 // use the signed type.
1176 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1178 } else if (!IsCompAssign)
1179 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1182 // The signed type is higher-ranked than the unsigned type,
1183 // but isn't actually any bigger (like unsigned int and long
1184 // on most 32-bit systems). Use the unsigned type corresponding
1185 // to the signed type.
1187 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1188 RHS = (*doRHSCast)(S, RHS.get(), result);
1190 LHS = (*doLHSCast)(S, LHS.get(), result);
1195 /// Handle conversions with GCC complex int extension. Helper function
1196 /// of UsualArithmeticConversions()
1197 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1198 ExprResult &RHS, QualType LHSType,
1200 bool IsCompAssign) {
1201 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1202 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1204 if (LHSComplexInt && RHSComplexInt) {
1205 QualType LHSEltType = LHSComplexInt->getElementType();
1206 QualType RHSEltType = RHSComplexInt->getElementType();
1207 QualType ScalarType =
1208 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1209 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1211 return S.Context.getComplexType(ScalarType);
1214 if (LHSComplexInt) {
1215 QualType LHSEltType = LHSComplexInt->getElementType();
1216 QualType ScalarType =
1217 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1218 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1219 QualType ComplexType = S.Context.getComplexType(ScalarType);
1220 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1221 CK_IntegralRealToComplex);
1226 assert(RHSComplexInt);
1228 QualType RHSEltType = RHSComplexInt->getElementType();
1229 QualType ScalarType =
1230 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1231 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1232 QualType ComplexType = S.Context.getComplexType(ScalarType);
1235 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1236 CK_IntegralRealToComplex);
1240 /// UsualArithmeticConversions - Performs various conversions that are common to
1241 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1242 /// routine returns the first non-arithmetic type found. The client is
1243 /// responsible for emitting appropriate error diagnostics.
1244 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1245 bool IsCompAssign) {
1246 if (!IsCompAssign) {
1247 LHS = UsualUnaryConversions(LHS.get());
1248 if (LHS.isInvalid())
1252 RHS = UsualUnaryConversions(RHS.get());
1253 if (RHS.isInvalid())
1256 // For conversion purposes, we ignore any qualifiers.
1257 // For example, "const float" and "float" are equivalent.
1259 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1261 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1263 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1264 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1265 LHSType = AtomicLHS->getValueType();
1267 // If both types are identical, no conversion is needed.
1268 if (LHSType == RHSType)
1271 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1272 // The caller can deal with this (e.g. pointer + int).
1273 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1276 // Apply unary and bitfield promotions to the LHS's type.
1277 QualType LHSUnpromotedType = LHSType;
1278 if (LHSType->isPromotableIntegerType())
1279 LHSType = Context.getPromotedIntegerType(LHSType);
1280 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1281 if (!LHSBitfieldPromoteTy.isNull())
1282 LHSType = LHSBitfieldPromoteTy;
1283 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1284 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1286 // If both types are identical, no conversion is needed.
1287 if (LHSType == RHSType)
1290 // At this point, we have two different arithmetic types.
1292 // Diagnose attempts to convert between __float128 and long double where
1293 // such conversions currently can't be handled.
1294 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1297 // Handle complex types first (C99 6.3.1.8p1).
1298 if (LHSType->isComplexType() || RHSType->isComplexType())
1299 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1302 // Now handle "real" floating types (i.e. float, double, long double).
1303 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1304 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1307 // Handle GCC complex int extension.
1308 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1309 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1312 // Finally, we have two differing integer types.
1313 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1314 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1318 //===----------------------------------------------------------------------===//
1319 // Semantic Analysis for various Expression Types
1320 //===----------------------------------------------------------------------===//
1324 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1325 SourceLocation DefaultLoc,
1326 SourceLocation RParenLoc,
1327 Expr *ControllingExpr,
1328 ArrayRef<ParsedType> ArgTypes,
1329 ArrayRef<Expr *> ArgExprs) {
1330 unsigned NumAssocs = ArgTypes.size();
1331 assert(NumAssocs == ArgExprs.size());
1333 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1334 for (unsigned i = 0; i < NumAssocs; ++i) {
1336 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1341 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1343 llvm::makeArrayRef(Types, NumAssocs),
1350 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1351 SourceLocation DefaultLoc,
1352 SourceLocation RParenLoc,
1353 Expr *ControllingExpr,
1354 ArrayRef<TypeSourceInfo *> Types,
1355 ArrayRef<Expr *> Exprs) {
1356 unsigned NumAssocs = Types.size();
1357 assert(NumAssocs == Exprs.size());
1359 // Decay and strip qualifiers for the controlling expression type, and handle
1360 // placeholder type replacement. See committee discussion from WG14 DR423.
1362 EnterExpressionEvaluationContext Unevaluated(
1363 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1364 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1367 ControllingExpr = R.get();
1370 // The controlling expression is an unevaluated operand, so side effects are
1371 // likely unintended.
1372 if (!inTemplateInstantiation() &&
1373 ControllingExpr->HasSideEffects(Context, false))
1374 Diag(ControllingExpr->getExprLoc(),
1375 diag::warn_side_effects_unevaluated_context);
1377 bool TypeErrorFound = false,
1378 IsResultDependent = ControllingExpr->isTypeDependent(),
1379 ContainsUnexpandedParameterPack
1380 = ControllingExpr->containsUnexpandedParameterPack();
1382 for (unsigned i = 0; i < NumAssocs; ++i) {
1383 if (Exprs[i]->containsUnexpandedParameterPack())
1384 ContainsUnexpandedParameterPack = true;
1387 if (Types[i]->getType()->containsUnexpandedParameterPack())
1388 ContainsUnexpandedParameterPack = true;
1390 if (Types[i]->getType()->isDependentType()) {
1391 IsResultDependent = true;
1393 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1394 // complete object type other than a variably modified type."
1396 if (Types[i]->getType()->isIncompleteType())
1397 D = diag::err_assoc_type_incomplete;
1398 else if (!Types[i]->getType()->isObjectType())
1399 D = diag::err_assoc_type_nonobject;
1400 else if (Types[i]->getType()->isVariablyModifiedType())
1401 D = diag::err_assoc_type_variably_modified;
1404 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1405 << Types[i]->getTypeLoc().getSourceRange()
1406 << Types[i]->getType();
1407 TypeErrorFound = true;
1410 // C11 6.5.1.1p2 "No two generic associations in the same generic
1411 // selection shall specify compatible types."
1412 for (unsigned j = i+1; j < NumAssocs; ++j)
1413 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1414 Context.typesAreCompatible(Types[i]->getType(),
1415 Types[j]->getType())) {
1416 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1417 diag::err_assoc_compatible_types)
1418 << Types[j]->getTypeLoc().getSourceRange()
1419 << Types[j]->getType()
1420 << Types[i]->getType();
1421 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1422 diag::note_compat_assoc)
1423 << Types[i]->getTypeLoc().getSourceRange()
1424 << Types[i]->getType();
1425 TypeErrorFound = true;
1433 // If we determined that the generic selection is result-dependent, don't
1434 // try to compute the result expression.
1435 if (IsResultDependent)
1436 return new (Context) GenericSelectionExpr(
1437 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1438 ContainsUnexpandedParameterPack);
1440 SmallVector<unsigned, 1> CompatIndices;
1441 unsigned DefaultIndex = -1U;
1442 for (unsigned i = 0; i < NumAssocs; ++i) {
1445 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1446 Types[i]->getType()))
1447 CompatIndices.push_back(i);
1450 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1451 // type compatible with at most one of the types named in its generic
1452 // association list."
1453 if (CompatIndices.size() > 1) {
1454 // We strip parens here because the controlling expression is typically
1455 // parenthesized in macro definitions.
1456 ControllingExpr = ControllingExpr->IgnoreParens();
1457 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1458 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1459 << (unsigned)CompatIndices.size();
1460 for (unsigned I : CompatIndices) {
1461 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1462 diag::note_compat_assoc)
1463 << Types[I]->getTypeLoc().getSourceRange()
1464 << Types[I]->getType();
1469 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1470 // its controlling expression shall have type compatible with exactly one of
1471 // the types named in its generic association list."
1472 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1473 // We strip parens here because the controlling expression is typically
1474 // parenthesized in macro definitions.
1475 ControllingExpr = ControllingExpr->IgnoreParens();
1476 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1477 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1481 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1482 // type name that is compatible with the type of the controlling expression,
1483 // then the result expression of the generic selection is the expression
1484 // in that generic association. Otherwise, the result expression of the
1485 // generic selection is the expression in the default generic association."
1486 unsigned ResultIndex =
1487 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1489 return new (Context) GenericSelectionExpr(
1490 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1491 ContainsUnexpandedParameterPack, ResultIndex);
1494 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1495 /// location of the token and the offset of the ud-suffix within it.
1496 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1498 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1502 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1503 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1504 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1505 IdentifierInfo *UDSuffix,
1506 SourceLocation UDSuffixLoc,
1507 ArrayRef<Expr*> Args,
1508 SourceLocation LitEndLoc) {
1509 assert(Args.size() <= 2 && "too many arguments for literal operator");
1512 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1513 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1514 if (ArgTy[ArgIdx]->isArrayType())
1515 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1518 DeclarationName OpName =
1519 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1520 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1521 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1523 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1524 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1525 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1526 /*AllowStringTemplate*/ false,
1527 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1530 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1533 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1534 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1535 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1536 /// multiple tokens. However, the common case is that StringToks points to one
1540 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1541 assert(!StringToks.empty() && "Must have at least one string!");
1543 StringLiteralParser Literal(StringToks, PP);
1544 if (Literal.hadError)
1547 SmallVector<SourceLocation, 4> StringTokLocs;
1548 for (const Token &Tok : StringToks)
1549 StringTokLocs.push_back(Tok.getLocation());
1551 QualType CharTy = Context.CharTy;
1552 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1553 if (Literal.isWide()) {
1554 CharTy = Context.getWideCharType();
1555 Kind = StringLiteral::Wide;
1556 } else if (Literal.isUTF8()) {
1557 if (getLangOpts().Char8)
1558 CharTy = Context.Char8Ty;
1559 Kind = StringLiteral::UTF8;
1560 } else if (Literal.isUTF16()) {
1561 CharTy = Context.Char16Ty;
1562 Kind = StringLiteral::UTF16;
1563 } else if (Literal.isUTF32()) {
1564 CharTy = Context.Char32Ty;
1565 Kind = StringLiteral::UTF32;
1566 } else if (Literal.isPascal()) {
1567 CharTy = Context.UnsignedCharTy;
1570 // Warn on initializing an array of char from a u8 string literal; this
1571 // becomes ill-formed in C++2a.
1572 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1573 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1574 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1576 // Create removals for all 'u8' prefixes in the string literal(s). This
1577 // ensures C++2a compatibility (but may change the program behavior when
1578 // built by non-Clang compilers for which the execution character set is
1579 // not always UTF-8).
1580 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1581 SourceLocation RemovalDiagLoc;
1582 for (const Token &Tok : StringToks) {
1583 if (Tok.getKind() == tok::utf8_string_literal) {
1584 if (RemovalDiagLoc.isInvalid())
1585 RemovalDiagLoc = Tok.getLocation();
1586 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1588 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1589 getSourceManager(), getLangOpts())));
1592 Diag(RemovalDiagLoc, RemovalDiag);
1596 QualType CharTyConst = CharTy;
1597 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1598 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1599 CharTyConst.addConst();
1601 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1603 // Get an array type for the string, according to C99 6.4.5. This includes
1604 // the nul terminator character as well as the string length for pascal
1606 QualType StrTy = Context.getConstantArrayType(
1607 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1608 ArrayType::Normal, 0);
1610 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1611 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1612 Kind, Literal.Pascal, StrTy,
1614 StringTokLocs.size());
1615 if (Literal.getUDSuffix().empty())
1618 // We're building a user-defined literal.
1619 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1620 SourceLocation UDSuffixLoc =
1621 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1622 Literal.getUDSuffixOffset());
1624 // Make sure we're allowed user-defined literals here.
1626 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1628 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1629 // operator "" X (str, len)
1630 QualType SizeType = Context.getSizeType();
1632 DeclarationName OpName =
1633 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1634 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1635 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1637 QualType ArgTy[] = {
1638 Context.getArrayDecayedType(StrTy), SizeType
1641 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1642 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1643 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1644 /*AllowStringTemplate*/ true,
1645 /*DiagnoseMissing*/ true)) {
1648 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1649 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1651 Expr *Args[] = { Lit, LenArg };
1653 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1656 case LOLR_StringTemplate: {
1657 TemplateArgumentListInfo ExplicitArgs;
1659 unsigned CharBits = Context.getIntWidth(CharTy);
1660 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1661 llvm::APSInt Value(CharBits, CharIsUnsigned);
1663 TemplateArgument TypeArg(CharTy);
1664 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1665 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1667 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1668 Value = Lit->getCodeUnit(I);
1669 TemplateArgument Arg(Context, Value, CharTy);
1670 TemplateArgumentLocInfo ArgInfo;
1671 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1673 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1678 case LOLR_ErrorNoDiagnostic:
1679 llvm_unreachable("unexpected literal operator lookup result");
1683 llvm_unreachable("unexpected literal operator lookup result");
1687 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1689 const CXXScopeSpec *SS) {
1690 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1691 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1694 /// BuildDeclRefExpr - Build an expression that references a
1695 /// declaration that does not require a closure capture.
1697 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1698 const DeclarationNameInfo &NameInfo,
1699 const CXXScopeSpec *SS, NamedDecl *FoundD,
1700 const TemplateArgumentListInfo *TemplateArgs) {
1701 bool RefersToCapturedVariable =
1703 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1706 if (isa<VarTemplateSpecializationDecl>(D)) {
1707 VarTemplateSpecializationDecl *VarSpec =
1708 cast<VarTemplateSpecializationDecl>(D);
1710 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1711 : NestedNameSpecifierLoc(),
1712 VarSpec->getTemplateKeywordLoc(), D,
1713 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1714 FoundD, TemplateArgs);
1716 assert(!TemplateArgs && "No template arguments for non-variable"
1717 " template specialization references");
1718 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1719 : NestedNameSpecifierLoc(),
1720 SourceLocation(), D, RefersToCapturedVariable,
1721 NameInfo, Ty, VK, FoundD);
1724 MarkDeclRefReferenced(E);
1726 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1727 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1728 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1729 getCurFunction()->recordUseOfWeak(E);
1731 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1732 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1733 FD = IFD->getAnonField();
1735 UnusedPrivateFields.remove(FD);
1736 // Just in case we're building an illegal pointer-to-member.
1737 if (FD->isBitField())
1738 E->setObjectKind(OK_BitField);
1741 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1742 // designates a bit-field.
1743 if (auto *BD = dyn_cast<BindingDecl>(D))
1744 if (auto *BE = BD->getBinding())
1745 E->setObjectKind(BE->getObjectKind());
1750 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1751 /// possibly a list of template arguments.
1753 /// If this produces template arguments, it is permitted to call
1754 /// DecomposeTemplateName.
1756 /// This actually loses a lot of source location information for
1757 /// non-standard name kinds; we should consider preserving that in
1760 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1761 TemplateArgumentListInfo &Buffer,
1762 DeclarationNameInfo &NameInfo,
1763 const TemplateArgumentListInfo *&TemplateArgs) {
1764 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1765 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1766 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1768 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1769 Id.TemplateId->NumArgs);
1770 translateTemplateArguments(TemplateArgsPtr, Buffer);
1772 TemplateName TName = Id.TemplateId->Template.get();
1773 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1774 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1775 TemplateArgs = &Buffer;
1777 NameInfo = GetNameFromUnqualifiedId(Id);
1778 TemplateArgs = nullptr;
1782 static void emitEmptyLookupTypoDiagnostic(
1783 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1784 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1785 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1787 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1789 // Emit a special diagnostic for failed member lookups.
1790 // FIXME: computing the declaration context might fail here (?)
1792 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1795 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1799 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1800 bool DroppedSpecifier =
1801 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1802 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1803 ? diag::note_implicit_param_decl
1804 : diag::note_previous_decl;
1806 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1807 SemaRef.PDiag(NoteID));
1809 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1810 << Typo << Ctx << DroppedSpecifier
1812 SemaRef.PDiag(NoteID));
1815 /// Diagnose an empty lookup.
1817 /// \return false if new lookup candidates were found
1819 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1820 std::unique_ptr<CorrectionCandidateCallback> CCC,
1821 TemplateArgumentListInfo *ExplicitTemplateArgs,
1822 ArrayRef<Expr *> Args, TypoExpr **Out) {
1823 DeclarationName Name = R.getLookupName();
1825 unsigned diagnostic = diag::err_undeclared_var_use;
1826 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1827 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1828 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1829 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1830 diagnostic = diag::err_undeclared_use;
1831 diagnostic_suggest = diag::err_undeclared_use_suggest;
1834 // If the original lookup was an unqualified lookup, fake an
1835 // unqualified lookup. This is useful when (for example) the
1836 // original lookup would not have found something because it was a
1838 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1840 if (isa<CXXRecordDecl>(DC)) {
1841 LookupQualifiedName(R, DC);
1844 // Don't give errors about ambiguities in this lookup.
1845 R.suppressDiagnostics();
1847 // During a default argument instantiation the CurContext points
1848 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1849 // function parameter list, hence add an explicit check.
1850 bool isDefaultArgument =
1851 !CodeSynthesisContexts.empty() &&
1852 CodeSynthesisContexts.back().Kind ==
1853 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1854 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1855 bool isInstance = CurMethod &&
1856 CurMethod->isInstance() &&
1857 DC == CurMethod->getParent() && !isDefaultArgument;
1859 // Give a code modification hint to insert 'this->'.
1860 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1861 // Actually quite difficult!
1862 if (getLangOpts().MSVCCompat)
1863 diagnostic = diag::ext_found_via_dependent_bases_lookup;
1865 Diag(R.getNameLoc(), diagnostic) << Name
1866 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1867 CheckCXXThisCapture(R.getNameLoc());
1869 Diag(R.getNameLoc(), diagnostic) << Name;
1872 // Do we really want to note all of these?
1873 for (NamedDecl *D : R)
1874 Diag(D->getLocation(), diag::note_dependent_var_use);
1876 // Return true if we are inside a default argument instantiation
1877 // and the found name refers to an instance member function, otherwise
1878 // the function calling DiagnoseEmptyLookup will try to create an
1879 // implicit member call and this is wrong for default argument.
1880 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1881 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1885 // Tell the callee to try to recover.
1892 // In Microsoft mode, if we are performing lookup from within a friend
1893 // function definition declared at class scope then we must set
1894 // DC to the lexical parent to be able to search into the parent
1896 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1897 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1898 DC->getLexicalParent()->isRecord())
1899 DC = DC->getLexicalParent();
1901 DC = DC->getParent();
1904 // We didn't find anything, so try to correct for a typo.
1905 TypoCorrection Corrected;
1907 SourceLocation TypoLoc = R.getNameLoc();
1908 assert(!ExplicitTemplateArgs &&
1909 "Diagnosing an empty lookup with explicit template args!");
1910 *Out = CorrectTypoDelayed(
1911 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1912 [=](const TypoCorrection &TC) {
1913 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1914 diagnostic, diagnostic_suggest);
1916 nullptr, CTK_ErrorRecovery);
1919 } else if (S && (Corrected =
1920 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1921 &SS, std::move(CCC), CTK_ErrorRecovery))) {
1922 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1923 bool DroppedSpecifier =
1924 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1925 R.setLookupName(Corrected.getCorrection());
1927 bool AcceptableWithRecovery = false;
1928 bool AcceptableWithoutRecovery = false;
1929 NamedDecl *ND = Corrected.getFoundDecl();
1931 if (Corrected.isOverloaded()) {
1932 OverloadCandidateSet OCS(R.getNameLoc(),
1933 OverloadCandidateSet::CSK_Normal);
1934 OverloadCandidateSet::iterator Best;
1935 for (NamedDecl *CD : Corrected) {
1936 if (FunctionTemplateDecl *FTD =
1937 dyn_cast<FunctionTemplateDecl>(CD))
1938 AddTemplateOverloadCandidate(
1939 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1941 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1942 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1943 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1946 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1948 ND = Best->FoundDecl;
1949 Corrected.setCorrectionDecl(ND);
1952 // FIXME: Arbitrarily pick the first declaration for the note.
1953 Corrected.setCorrectionDecl(ND);
1958 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1959 CXXRecordDecl *Record = nullptr;
1960 if (Corrected.getCorrectionSpecifier()) {
1961 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1962 Record = Ty->getAsCXXRecordDecl();
1965 Record = cast<CXXRecordDecl>(
1966 ND->getDeclContext()->getRedeclContext());
1967 R.setNamingClass(Record);
1970 auto *UnderlyingND = ND->getUnderlyingDecl();
1971 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1972 isa<FunctionTemplateDecl>(UnderlyingND);
1973 // FIXME: If we ended up with a typo for a type name or
1974 // Objective-C class name, we're in trouble because the parser
1975 // is in the wrong place to recover. Suggest the typo
1976 // correction, but don't make it a fix-it since we're not going
1977 // to recover well anyway.
1978 AcceptableWithoutRecovery =
1979 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1981 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1982 // because we aren't able to recover.
1983 AcceptableWithoutRecovery = true;
1986 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1987 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1988 ? diag::note_implicit_param_decl
1989 : diag::note_previous_decl;
1991 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1992 PDiag(NoteID), AcceptableWithRecovery);
1994 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1995 << Name << computeDeclContext(SS, false)
1996 << DroppedSpecifier << SS.getRange(),
1997 PDiag(NoteID), AcceptableWithRecovery);
1999 // Tell the callee whether to try to recover.
2000 return !AcceptableWithRecovery;
2005 // Emit a special diagnostic for failed member lookups.
2006 // FIXME: computing the declaration context might fail here (?)
2007 if (!SS.isEmpty()) {
2008 Diag(R.getNameLoc(), diag::err_no_member)
2009 << Name << computeDeclContext(SS, false)
2014 // Give up, we can't recover.
2015 Diag(R.getNameLoc(), diagnostic) << Name;
2019 /// In Microsoft mode, if we are inside a template class whose parent class has
2020 /// dependent base classes, and we can't resolve an unqualified identifier, then
2021 /// assume the identifier is a member of a dependent base class. We can only
2022 /// recover successfully in static methods, instance methods, and other contexts
2023 /// where 'this' is available. This doesn't precisely match MSVC's
2024 /// instantiation model, but it's close enough.
2026 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2027 DeclarationNameInfo &NameInfo,
2028 SourceLocation TemplateKWLoc,
2029 const TemplateArgumentListInfo *TemplateArgs) {
2030 // Only try to recover from lookup into dependent bases in static methods or
2031 // contexts where 'this' is available.
2032 QualType ThisType = S.getCurrentThisType();
2033 const CXXRecordDecl *RD = nullptr;
2034 if (!ThisType.isNull())
2035 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2036 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2037 RD = MD->getParent();
2038 if (!RD || !RD->hasAnyDependentBases())
2041 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2042 // is available, suggest inserting 'this->' as a fixit.
2043 SourceLocation Loc = NameInfo.getLoc();
2044 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2045 DB << NameInfo.getName() << RD;
2047 if (!ThisType.isNull()) {
2048 DB << FixItHint::CreateInsertion(Loc, "this->");
2049 return CXXDependentScopeMemberExpr::Create(
2050 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2051 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2052 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2055 // Synthesize a fake NNS that points to the derived class. This will
2056 // perform name lookup during template instantiation.
2059 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2060 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2061 return DependentScopeDeclRefExpr::Create(
2062 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2067 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2068 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2069 bool HasTrailingLParen, bool IsAddressOfOperand,
2070 std::unique_ptr<CorrectionCandidateCallback> CCC,
2071 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2072 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2073 "cannot be direct & operand and have a trailing lparen");
2077 TemplateArgumentListInfo TemplateArgsBuffer;
2079 // Decompose the UnqualifiedId into the following data.
2080 DeclarationNameInfo NameInfo;
2081 const TemplateArgumentListInfo *TemplateArgs;
2082 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2084 DeclarationName Name = NameInfo.getName();
2085 IdentifierInfo *II = Name.getAsIdentifierInfo();
2086 SourceLocation NameLoc = NameInfo.getLoc();
2088 if (II && II->isEditorPlaceholder()) {
2089 // FIXME: When typed placeholders are supported we can create a typed
2090 // placeholder expression node.
2094 // C++ [temp.dep.expr]p3:
2095 // An id-expression is type-dependent if it contains:
2096 // -- an identifier that was declared with a dependent type,
2097 // (note: handled after lookup)
2098 // -- a template-id that is dependent,
2099 // (note: handled in BuildTemplateIdExpr)
2100 // -- a conversion-function-id that specifies a dependent type,
2101 // -- a nested-name-specifier that contains a class-name that
2102 // names a dependent type.
2103 // Determine whether this is a member of an unknown specialization;
2104 // we need to handle these differently.
2105 bool DependentID = false;
2106 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2107 Name.getCXXNameType()->isDependentType()) {
2109 } else if (SS.isSet()) {
2110 if (DeclContext *DC = computeDeclContext(SS, false)) {
2111 if (RequireCompleteDeclContext(SS, DC))
2119 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2120 IsAddressOfOperand, TemplateArgs);
2122 // Perform the required lookup.
2123 LookupResult R(*this, NameInfo,
2124 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2125 ? LookupObjCImplicitSelfParam
2126 : LookupOrdinaryName);
2127 if (TemplateKWLoc.isValid() || TemplateArgs) {
2128 // Lookup the template name again to correctly establish the context in
2129 // which it was found. This is really unfortunate as we already did the
2130 // lookup to determine that it was a template name in the first place. If
2131 // this becomes a performance hit, we can work harder to preserve those
2132 // results until we get here but it's likely not worth it.
2133 bool MemberOfUnknownSpecialization;
2134 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2135 MemberOfUnknownSpecialization, TemplateKWLoc))
2138 if (MemberOfUnknownSpecialization ||
2139 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2140 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2141 IsAddressOfOperand, TemplateArgs);
2143 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2144 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2146 // If the result might be in a dependent base class, this is a dependent
2148 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2149 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2150 IsAddressOfOperand, TemplateArgs);
2152 // If this reference is in an Objective-C method, then we need to do
2153 // some special Objective-C lookup, too.
2154 if (IvarLookupFollowUp) {
2155 ExprResult E(LookupInObjCMethod(R, S, II, true));
2159 if (Expr *Ex = E.getAs<Expr>())
2164 if (R.isAmbiguous())
2167 // This could be an implicitly declared function reference (legal in C90,
2168 // extension in C99, forbidden in C++).
2169 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2170 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2171 if (D) R.addDecl(D);
2174 // Determine whether this name might be a candidate for
2175 // argument-dependent lookup.
2176 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2178 if (R.empty() && !ADL) {
2179 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2180 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2181 TemplateKWLoc, TemplateArgs))
2185 // Don't diagnose an empty lookup for inline assembly.
2186 if (IsInlineAsmIdentifier)
2189 // If this name wasn't predeclared and if this is not a function
2190 // call, diagnose the problem.
2191 TypoExpr *TE = nullptr;
2192 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2193 II, SS.isValid() ? SS.getScopeRep() : nullptr);
2194 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2195 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2196 "Typo correction callback misconfigured");
2198 // Make sure the callback knows what the typo being diagnosed is.
2199 CCC->setTypoName(II);
2201 CCC->setTypoNNS(SS.getScopeRep());
2203 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2204 // a template name, but we happen to have always already looked up the name
2205 // before we get here if it must be a template name.
2206 if (DiagnoseEmptyLookup(S, SS, R,
2207 CCC ? std::move(CCC) : std::move(DefaultValidator),
2208 nullptr, None, &TE)) {
2209 if (TE && KeywordReplacement) {
2210 auto &State = getTypoExprState(TE);
2211 auto BestTC = State.Consumer->getNextCorrection();
2212 if (BestTC.isKeyword()) {
2213 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2214 if (State.DiagHandler)
2215 State.DiagHandler(BestTC);
2216 KeywordReplacement->startToken();
2217 KeywordReplacement->setKind(II->getTokenID());
2218 KeywordReplacement->setIdentifierInfo(II);
2219 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2220 // Clean up the state associated with the TypoExpr, since it has
2221 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2222 clearDelayedTypo(TE);
2223 // Signal that a correction to a keyword was performed by returning a
2224 // valid-but-null ExprResult.
2225 return (Expr*)nullptr;
2227 State.Consumer->resetCorrectionStream();
2229 return TE ? TE : ExprError();
2232 assert(!R.empty() &&
2233 "DiagnoseEmptyLookup returned false but added no results");
2235 // If we found an Objective-C instance variable, let
2236 // LookupInObjCMethod build the appropriate expression to
2237 // reference the ivar.
2238 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2240 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2241 // In a hopelessly buggy code, Objective-C instance variable
2242 // lookup fails and no expression will be built to reference it.
2243 if (!E.isInvalid() && !E.get())
2249 // This is guaranteed from this point on.
2250 assert(!R.empty() || ADL);
2252 // Check whether this might be a C++ implicit instance member access.
2253 // C++ [class.mfct.non-static]p3:
2254 // When an id-expression that is not part of a class member access
2255 // syntax and not used to form a pointer to member is used in the
2256 // body of a non-static member function of class X, if name lookup
2257 // resolves the name in the id-expression to a non-static non-type
2258 // member of some class C, the id-expression is transformed into a
2259 // class member access expression using (*this) as the
2260 // postfix-expression to the left of the . operator.
2262 // But we don't actually need to do this for '&' operands if R
2263 // resolved to a function or overloaded function set, because the
2264 // expression is ill-formed if it actually works out to be a
2265 // non-static member function:
2267 // C++ [expr.ref]p4:
2268 // Otherwise, if E1.E2 refers to a non-static member function. . .
2269 // [t]he expression can be used only as the left-hand operand of a
2270 // member function call.
2272 // There are other safeguards against such uses, but it's important
2273 // to get this right here so that we don't end up making a
2274 // spuriously dependent expression if we're inside a dependent
2276 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2277 bool MightBeImplicitMember;
2278 if (!IsAddressOfOperand)
2279 MightBeImplicitMember = true;
2280 else if (!SS.isEmpty())
2281 MightBeImplicitMember = false;
2282 else if (R.isOverloadedResult())
2283 MightBeImplicitMember = false;
2284 else if (R.isUnresolvableResult())
2285 MightBeImplicitMember = true;
2287 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2288 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2289 isa<MSPropertyDecl>(R.getFoundDecl());
2291 if (MightBeImplicitMember)
2292 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2293 R, TemplateArgs, S);
2296 if (TemplateArgs || TemplateKWLoc.isValid()) {
2298 // In C++1y, if this is a variable template id, then check it
2299 // in BuildTemplateIdExpr().
2300 // The single lookup result must be a variable template declaration.
2301 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2302 Id.TemplateId->Kind == TNK_Var_template) {
2303 assert(R.getAsSingle<VarTemplateDecl>() &&
2304 "There should only be one declaration found.");
2307 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2310 return BuildDeclarationNameExpr(SS, R, ADL);
2313 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2314 /// declaration name, generally during template instantiation.
2315 /// There's a large number of things which don't need to be done along
2317 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2318 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2319 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2320 DeclContext *DC = computeDeclContext(SS, false);
2322 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2323 NameInfo, /*TemplateArgs=*/nullptr);
2325 if (RequireCompleteDeclContext(SS, DC))
2328 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2329 LookupQualifiedName(R, DC);
2331 if (R.isAmbiguous())
2334 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2335 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2336 NameInfo, /*TemplateArgs=*/nullptr);
2339 Diag(NameInfo.getLoc(), diag::err_no_member)
2340 << NameInfo.getName() << DC << SS.getRange();
2344 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2345 // Diagnose a missing typename if this resolved unambiguously to a type in
2346 // a dependent context. If we can recover with a type, downgrade this to
2347 // a warning in Microsoft compatibility mode.
2348 unsigned DiagID = diag::err_typename_missing;
2349 if (RecoveryTSI && getLangOpts().MSVCCompat)
2350 DiagID = diag::ext_typename_missing;
2351 SourceLocation Loc = SS.getBeginLoc();
2352 auto D = Diag(Loc, DiagID);
2353 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2354 << SourceRange(Loc, NameInfo.getEndLoc());
2356 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2361 // Only issue the fixit if we're prepared to recover.
2362 D << FixItHint::CreateInsertion(Loc, "typename ");
2364 // Recover by pretending this was an elaborated type.
2365 QualType Ty = Context.getTypeDeclType(TD);
2367 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2369 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2370 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2371 QTL.setElaboratedKeywordLoc(SourceLocation());
2372 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2374 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2379 // Defend against this resolving to an implicit member access. We usually
2380 // won't get here if this might be a legitimate a class member (we end up in
2381 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2382 // a pointer-to-member or in an unevaluated context in C++11.
2383 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2384 return BuildPossibleImplicitMemberExpr(SS,
2385 /*TemplateKWLoc=*/SourceLocation(),
2386 R, /*TemplateArgs=*/nullptr, S);
2388 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2391 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2392 /// detected that we're currently inside an ObjC method. Perform some
2393 /// additional lookup.
2395 /// Ideally, most of this would be done by lookup, but there's
2396 /// actually quite a lot of extra work involved.
2398 /// Returns a null sentinel to indicate trivial success.
2400 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2401 IdentifierInfo *II, bool AllowBuiltinCreation) {
2402 SourceLocation Loc = Lookup.getNameLoc();
2403 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2405 // Check for error condition which is already reported.
2409 // There are two cases to handle here. 1) scoped lookup could have failed,
2410 // in which case we should look for an ivar. 2) scoped lookup could have
2411 // found a decl, but that decl is outside the current instance method (i.e.
2412 // a global variable). In these two cases, we do a lookup for an ivar with
2413 // this name, if the lookup sucedes, we replace it our current decl.
2415 // If we're in a class method, we don't normally want to look for
2416 // ivars. But if we don't find anything else, and there's an
2417 // ivar, that's an error.
2418 bool IsClassMethod = CurMethod->isClassMethod();
2422 LookForIvars = true;
2423 else if (IsClassMethod)
2424 LookForIvars = false;
2426 LookForIvars = (Lookup.isSingleResult() &&
2427 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2428 ObjCInterfaceDecl *IFace = nullptr;
2430 IFace = CurMethod->getClassInterface();
2431 ObjCInterfaceDecl *ClassDeclared;
2432 ObjCIvarDecl *IV = nullptr;
2433 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2434 // Diagnose using an ivar in a class method.
2436 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2437 << IV->getDeclName());
2439 // If we're referencing an invalid decl, just return this as a silent
2440 // error node. The error diagnostic was already emitted on the decl.
2441 if (IV->isInvalidDecl())
2444 // Check if referencing a field with __attribute__((deprecated)).
2445 if (DiagnoseUseOfDecl(IV, Loc))
2448 // Diagnose the use of an ivar outside of the declaring class.
2449 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2450 !declaresSameEntity(ClassDeclared, IFace) &&
2451 !getLangOpts().DebuggerSupport)
2452 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2454 // FIXME: This should use a new expr for a direct reference, don't
2455 // turn this into Self->ivar, just return a BareIVarExpr or something.
2456 IdentifierInfo &II = Context.Idents.get("self");
2457 UnqualifiedId SelfName;
2458 SelfName.setIdentifier(&II, SourceLocation());
2459 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2460 CXXScopeSpec SelfScopeSpec;
2461 SourceLocation TemplateKWLoc;
2462 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2463 SelfName, false, false);
2464 if (SelfExpr.isInvalid())
2467 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2468 if (SelfExpr.isInvalid())
2471 MarkAnyDeclReferenced(Loc, IV, true);
2473 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2474 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2475 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2476 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2478 ObjCIvarRefExpr *Result = new (Context)
2479 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2480 IV->getLocation(), SelfExpr.get(), true, true);
2482 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2483 if (!isUnevaluatedContext() &&
2484 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2485 getCurFunction()->recordUseOfWeak(Result);
2487 if (getLangOpts().ObjCAutoRefCount) {
2488 if (CurContext->isClosure())
2489 Diag(Loc, diag::warn_implicitly_retains_self)
2490 << FixItHint::CreateInsertion(Loc, "self->");
2495 } else if (CurMethod->isInstanceMethod()) {
2496 // We should warn if a local variable hides an ivar.
2497 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2498 ObjCInterfaceDecl *ClassDeclared;
2499 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2500 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2501 declaresSameEntity(IFace, ClassDeclared))
2502 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2505 } else if (Lookup.isSingleResult() &&
2506 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2507 // If accessing a stand-alone ivar in a class method, this is an error.
2508 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2509 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2510 << IV->getDeclName());
2513 if (Lookup.empty() && II && AllowBuiltinCreation) {
2514 // FIXME. Consolidate this with similar code in LookupName.
2515 if (unsigned BuiltinID = II->getBuiltinID()) {
2516 if (!(getLangOpts().CPlusPlus &&
2517 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2518 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2519 S, Lookup.isForRedeclaration(),
2520 Lookup.getNameLoc());
2521 if (D) Lookup.addDecl(D);
2525 // Sentinel value saying that we didn't do anything special.
2526 return ExprResult((Expr *)nullptr);
2529 /// Cast a base object to a member's actual type.
2531 /// Logically this happens in three phases:
2533 /// * First we cast from the base type to the naming class.
2534 /// The naming class is the class into which we were looking
2535 /// when we found the member; it's the qualifier type if a
2536 /// qualifier was provided, and otherwise it's the base type.
2538 /// * Next we cast from the naming class to the declaring class.
2539 /// If the member we found was brought into a class's scope by
2540 /// a using declaration, this is that class; otherwise it's
2541 /// the class declaring the member.
2543 /// * Finally we cast from the declaring class to the "true"
2544 /// declaring class of the member. This conversion does not
2545 /// obey access control.
2547 Sema::PerformObjectMemberConversion(Expr *From,
2548 NestedNameSpecifier *Qualifier,
2549 NamedDecl *FoundDecl,
2550 NamedDecl *Member) {
2551 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2555 QualType DestRecordType;
2557 QualType FromRecordType;
2558 QualType FromType = From->getType();
2559 bool PointerConversions = false;
2560 if (isa<FieldDecl>(Member)) {
2561 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2563 if (FromType->getAs<PointerType>()) {
2564 DestType = Context.getPointerType(DestRecordType);
2565 FromRecordType = FromType->getPointeeType();
2566 PointerConversions = true;
2568 DestType = DestRecordType;
2569 FromRecordType = FromType;
2571 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2572 if (Method->isStatic())
2575 DestType = Method->getThisType();
2576 DestRecordType = DestType->getPointeeType();
2578 if (FromType->getAs<PointerType>()) {
2579 FromRecordType = FromType->getPointeeType();
2580 PointerConversions = true;
2582 FromRecordType = FromType;
2583 DestType = DestRecordType;
2586 // No conversion necessary.
2590 if (DestType->isDependentType() || FromType->isDependentType())
2593 // If the unqualified types are the same, no conversion is necessary.
2594 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2597 SourceRange FromRange = From->getSourceRange();
2598 SourceLocation FromLoc = FromRange.getBegin();
2600 ExprValueKind VK = From->getValueKind();
2602 // C++ [class.member.lookup]p8:
2603 // [...] Ambiguities can often be resolved by qualifying a name with its
2606 // If the member was a qualified name and the qualified referred to a
2607 // specific base subobject type, we'll cast to that intermediate type
2608 // first and then to the object in which the member is declared. That allows
2609 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2611 // class Base { public: int x; };
2612 // class Derived1 : public Base { };
2613 // class Derived2 : public Base { };
2614 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2616 // void VeryDerived::f() {
2617 // x = 17; // error: ambiguous base subobjects
2618 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2620 if (Qualifier && Qualifier->getAsType()) {
2621 QualType QType = QualType(Qualifier->getAsType(), 0);
2622 assert(QType->isRecordType() && "lookup done with non-record type");
2624 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2626 // In C++98, the qualifier type doesn't actually have to be a base
2627 // type of the object type, in which case we just ignore it.
2628 // Otherwise build the appropriate casts.
2629 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2630 CXXCastPath BasePath;
2631 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2632 FromLoc, FromRange, &BasePath))
2635 if (PointerConversions)
2636 QType = Context.getPointerType(QType);
2637 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2638 VK, &BasePath).get();
2641 FromRecordType = QRecordType;
2643 // If the qualifier type was the same as the destination type,
2645 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2650 bool IgnoreAccess = false;
2652 // If we actually found the member through a using declaration, cast
2653 // down to the using declaration's type.
2655 // Pointer equality is fine here because only one declaration of a
2656 // class ever has member declarations.
2657 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2658 assert(isa<UsingShadowDecl>(FoundDecl));
2659 QualType URecordType = Context.getTypeDeclType(
2660 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2662 // We only need to do this if the naming-class to declaring-class
2663 // conversion is non-trivial.
2664 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2665 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2666 CXXCastPath BasePath;
2667 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2668 FromLoc, FromRange, &BasePath))
2671 QualType UType = URecordType;
2672 if (PointerConversions)
2673 UType = Context.getPointerType(UType);
2674 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2675 VK, &BasePath).get();
2677 FromRecordType = URecordType;
2680 // We don't do access control for the conversion from the
2681 // declaring class to the true declaring class.
2682 IgnoreAccess = true;
2685 CXXCastPath BasePath;
2686 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2687 FromLoc, FromRange, &BasePath,
2691 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2695 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2696 const LookupResult &R,
2697 bool HasTrailingLParen) {
2698 // Only when used directly as the postfix-expression of a call.
2699 if (!HasTrailingLParen)
2702 // Never if a scope specifier was provided.
2706 // Only in C++ or ObjC++.
2707 if (!getLangOpts().CPlusPlus)
2710 // Turn off ADL when we find certain kinds of declarations during
2712 for (NamedDecl *D : R) {
2713 // C++0x [basic.lookup.argdep]p3:
2714 // -- a declaration of a class member
2715 // Since using decls preserve this property, we check this on the
2717 if (D->isCXXClassMember())
2720 // C++0x [basic.lookup.argdep]p3:
2721 // -- a block-scope function declaration that is not a
2722 // using-declaration
2723 // NOTE: we also trigger this for function templates (in fact, we
2724 // don't check the decl type at all, since all other decl types
2725 // turn off ADL anyway).
2726 if (isa<UsingShadowDecl>(D))
2727 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2728 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2731 // C++0x [basic.lookup.argdep]p3:
2732 // -- a declaration that is neither a function or a function
2734 // And also for builtin functions.
2735 if (isa<FunctionDecl>(D)) {
2736 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2738 // But also builtin functions.
2739 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2741 } else if (!isa<FunctionTemplateDecl>(D))
2749 /// Diagnoses obvious problems with the use of the given declaration
2750 /// as an expression. This is only actually called for lookups that
2751 /// were not overloaded, and it doesn't promise that the declaration
2752 /// will in fact be used.
2753 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2754 if (D->isInvalidDecl())
2757 if (isa<TypedefNameDecl>(D)) {
2758 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2762 if (isa<ObjCInterfaceDecl>(D)) {
2763 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2767 if (isa<NamespaceDecl>(D)) {
2768 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2775 // Certain multiversion types should be treated as overloaded even when there is
2777 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2778 assert(R.isSingleResult() && "Expected only a single result");
2779 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2781 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2784 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2785 LookupResult &R, bool NeedsADL,
2786 bool AcceptInvalidDecl) {
2787 // If this is a single, fully-resolved result and we don't need ADL,
2788 // just build an ordinary singleton decl ref.
2789 if (!NeedsADL && R.isSingleResult() &&
2790 !R.getAsSingle<FunctionTemplateDecl>() &&
2791 !ShouldLookupResultBeMultiVersionOverload(R))
2792 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2793 R.getRepresentativeDecl(), nullptr,
2796 // We only need to check the declaration if there's exactly one
2797 // result, because in the overloaded case the results can only be
2798 // functions and function templates.
2799 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2800 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2803 // Otherwise, just build an unresolved lookup expression. Suppress
2804 // any lookup-related diagnostics; we'll hash these out later, when
2805 // we've picked a target.
2806 R.suppressDiagnostics();
2808 UnresolvedLookupExpr *ULE
2809 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2810 SS.getWithLocInContext(Context),
2811 R.getLookupNameInfo(),
2812 NeedsADL, R.isOverloadedResult(),
2813 R.begin(), R.end());
2819 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2820 ValueDecl *var, DeclContext *DC);
2822 /// Complete semantic analysis for a reference to the given declaration.
2823 ExprResult Sema::BuildDeclarationNameExpr(
2824 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2825 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2826 bool AcceptInvalidDecl) {
2827 assert(D && "Cannot refer to a NULL declaration");
2828 assert(!isa<FunctionTemplateDecl>(D) &&
2829 "Cannot refer unambiguously to a function template");
2831 SourceLocation Loc = NameInfo.getLoc();
2832 if (CheckDeclInExpr(*this, Loc, D))
2835 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2836 // Specifically diagnose references to class templates that are missing
2837 // a template argument list.
2838 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2842 // Make sure that we're referring to a value.
2843 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2845 Diag(Loc, diag::err_ref_non_value)
2846 << D << SS.getRange();
2847 Diag(D->getLocation(), diag::note_declared_at);
2851 // Check whether this declaration can be used. Note that we suppress
2852 // this check when we're going to perform argument-dependent lookup
2853 // on this function name, because this might not be the function
2854 // that overload resolution actually selects.
2855 if (DiagnoseUseOfDecl(VD, Loc))
2858 // Only create DeclRefExpr's for valid Decl's.
2859 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2862 // Handle members of anonymous structs and unions. If we got here,
2863 // and the reference is to a class member indirect field, then this
2864 // must be the subject of a pointer-to-member expression.
2865 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2866 if (!indirectField->isCXXClassMember())
2867 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2871 QualType type = VD->getType();
2874 if (auto *FPT = type->getAs<FunctionProtoType>()) {
2875 // C++ [except.spec]p17:
2876 // An exception-specification is considered to be needed when:
2877 // - in an expression, the function is the unique lookup result or
2878 // the selected member of a set of overloaded functions.
2879 ResolveExceptionSpec(Loc, FPT);
2880 type = VD->getType();
2882 ExprValueKind valueKind = VK_RValue;
2884 switch (D->getKind()) {
2885 // Ignore all the non-ValueDecl kinds.
2886 #define ABSTRACT_DECL(kind)
2887 #define VALUE(type, base)
2888 #define DECL(type, base) \
2890 #include "clang/AST/DeclNodes.inc"
2891 llvm_unreachable("invalid value decl kind");
2893 // These shouldn't make it here.
2894 case Decl::ObjCAtDefsField:
2895 case Decl::ObjCIvar:
2896 llvm_unreachable("forming non-member reference to ivar?");
2898 // Enum constants are always r-values and never references.
2899 // Unresolved using declarations are dependent.
2900 case Decl::EnumConstant:
2901 case Decl::UnresolvedUsingValue:
2902 case Decl::OMPDeclareReduction:
2903 valueKind = VK_RValue;
2906 // Fields and indirect fields that got here must be for
2907 // pointer-to-member expressions; we just call them l-values for
2908 // internal consistency, because this subexpression doesn't really
2909 // exist in the high-level semantics.
2911 case Decl::IndirectField:
2912 assert(getLangOpts().CPlusPlus &&
2913 "building reference to field in C?");
2915 // These can't have reference type in well-formed programs, but
2916 // for internal consistency we do this anyway.
2917 type = type.getNonReferenceType();
2918 valueKind = VK_LValue;
2921 // Non-type template parameters are either l-values or r-values
2922 // depending on the type.
2923 case Decl::NonTypeTemplateParm: {
2924 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2925 type = reftype->getPointeeType();
2926 valueKind = VK_LValue; // even if the parameter is an r-value reference
2930 // For non-references, we need to strip qualifiers just in case
2931 // the template parameter was declared as 'const int' or whatever.
2932 valueKind = VK_RValue;
2933 type = type.getUnqualifiedType();
2938 case Decl::VarTemplateSpecialization:
2939 case Decl::VarTemplatePartialSpecialization:
2940 case Decl::Decomposition:
2941 case Decl::OMPCapturedExpr:
2942 // In C, "extern void blah;" is valid and is an r-value.
2943 if (!getLangOpts().CPlusPlus &&
2944 !type.hasQualifiers() &&
2945 type->isVoidType()) {
2946 valueKind = VK_RValue;
2951 case Decl::ImplicitParam:
2952 case Decl::ParmVar: {
2953 // These are always l-values.
2954 valueKind = VK_LValue;
2955 type = type.getNonReferenceType();
2957 // FIXME: Does the addition of const really only apply in
2958 // potentially-evaluated contexts? Since the variable isn't actually
2959 // captured in an unevaluated context, it seems that the answer is no.
2960 if (!isUnevaluatedContext()) {
2961 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2962 if (!CapturedType.isNull())
2963 type = CapturedType;
2969 case Decl::Binding: {
2970 // These are always lvalues.
2971 valueKind = VK_LValue;
2972 type = type.getNonReferenceType();
2973 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2974 // decides how that's supposed to work.
2975 auto *BD = cast<BindingDecl>(VD);
2976 if (BD->getDeclContext()->isFunctionOrMethod() &&
2977 BD->getDeclContext() != CurContext)
2978 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2982 case Decl::Function: {
2983 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2984 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2985 type = Context.BuiltinFnTy;
2986 valueKind = VK_RValue;
2991 const FunctionType *fty = type->castAs<FunctionType>();
2993 // If we're referring to a function with an __unknown_anytype
2994 // result type, make the entire expression __unknown_anytype.
2995 if (fty->getReturnType() == Context.UnknownAnyTy) {
2996 type = Context.UnknownAnyTy;
2997 valueKind = VK_RValue;
3001 // Functions are l-values in C++.
3002 if (getLangOpts().CPlusPlus) {
3003 valueKind = VK_LValue;
3007 // C99 DR 316 says that, if a function type comes from a
3008 // function definition (without a prototype), that type is only
3009 // used for checking compatibility. Therefore, when referencing
3010 // the function, we pretend that we don't have the full function
3012 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3013 isa<FunctionProtoType>(fty))
3014 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3017 // Functions are r-values in C.
3018 valueKind = VK_RValue;
3022 case Decl::CXXDeductionGuide:
3023 llvm_unreachable("building reference to deduction guide");
3025 case Decl::MSProperty:
3026 valueKind = VK_LValue;
3029 case Decl::CXXMethod:
3030 // If we're referring to a method with an __unknown_anytype
3031 // result type, make the entire expression __unknown_anytype.
3032 // This should only be possible with a type written directly.
3033 if (const FunctionProtoType *proto
3034 = dyn_cast<FunctionProtoType>(VD->getType()))
3035 if (proto->getReturnType() == Context.UnknownAnyTy) {
3036 type = Context.UnknownAnyTy;
3037 valueKind = VK_RValue;
3041 // C++ methods are l-values if static, r-values if non-static.
3042 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3043 valueKind = VK_LValue;
3048 case Decl::CXXConversion:
3049 case Decl::CXXDestructor:
3050 case Decl::CXXConstructor:
3051 valueKind = VK_RValue;
3055 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3060 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3061 SmallString<32> &Target) {
3062 Target.resize(CharByteWidth * (Source.size() + 1));
3063 char *ResultPtr = &Target[0];
3064 const llvm::UTF8 *ErrorPtr;
3066 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3069 Target.resize(ResultPtr - &Target[0]);
3072 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3073 PredefinedExpr::IdentKind IK) {
3074 // Pick the current block, lambda, captured statement or function.
3075 Decl *currentDecl = nullptr;
3076 if (const BlockScopeInfo *BSI = getCurBlock())
3077 currentDecl = BSI->TheDecl;
3078 else if (const LambdaScopeInfo *LSI = getCurLambda())
3079 currentDecl = LSI->CallOperator;
3080 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3081 currentDecl = CSI->TheCapturedDecl;
3083 currentDecl = getCurFunctionOrMethodDecl();
3086 Diag(Loc, diag::ext_predef_outside_function);
3087 currentDecl = Context.getTranslationUnitDecl();
3091 StringLiteral *SL = nullptr;
3092 if (cast<DeclContext>(currentDecl)->isDependentContext())
3093 ResTy = Context.DependentTy;
3095 // Pre-defined identifiers are of type char[x], where x is the length of
3097 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3098 unsigned Length = Str.length();
3100 llvm::APInt LengthI(32, Length + 1);
3101 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3103 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3104 SmallString<32> RawChars;
3105 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3107 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3108 /*IndexTypeQuals*/ 0);
3109 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3110 /*Pascal*/ false, ResTy, Loc);
3112 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3113 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3114 /*IndexTypeQuals*/ 0);
3115 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3116 /*Pascal*/ false, ResTy, Loc);
3120 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3123 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3124 PredefinedExpr::IdentKind IK;
3127 default: llvm_unreachable("Unknown simple primary expr!");
3128 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3129 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3130 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3131 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3132 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3133 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3134 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3137 return BuildPredefinedExpr(Loc, IK);
3140 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3141 SmallString<16> CharBuffer;
3142 bool Invalid = false;
3143 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3147 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3149 if (Literal.hadError())
3153 if (Literal.isWide())
3154 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3155 else if (Literal.isUTF8() && getLangOpts().Char8)
3156 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3157 else if (Literal.isUTF16())
3158 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3159 else if (Literal.isUTF32())
3160 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3161 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3162 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3164 Ty = Context.CharTy; // 'x' -> char in C++
3166 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3167 if (Literal.isWide())
3168 Kind = CharacterLiteral::Wide;
3169 else if (Literal.isUTF16())
3170 Kind = CharacterLiteral::UTF16;
3171 else if (Literal.isUTF32())
3172 Kind = CharacterLiteral::UTF32;
3173 else if (Literal.isUTF8())
3174 Kind = CharacterLiteral::UTF8;
3176 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3179 if (Literal.getUDSuffix().empty())
3182 // We're building a user-defined literal.
3183 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3184 SourceLocation UDSuffixLoc =
3185 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3187 // Make sure we're allowed user-defined literals here.
3189 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3191 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3192 // operator "" X (ch)
3193 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3194 Lit, Tok.getLocation());
3197 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3198 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3199 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3200 Context.IntTy, Loc);
3203 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3204 QualType Ty, SourceLocation Loc) {
3205 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3207 using llvm::APFloat;
3208 APFloat Val(Format);
3210 APFloat::opStatus result = Literal.GetFloatValue(Val);
3212 // Overflow is always an error, but underflow is only an error if
3213 // we underflowed to zero (APFloat reports denormals as underflow).
3214 if ((result & APFloat::opOverflow) ||
3215 ((result & APFloat::opUnderflow) && Val.isZero())) {
3216 unsigned diagnostic;
3217 SmallString<20> buffer;
3218 if (result & APFloat::opOverflow) {
3219 diagnostic = diag::warn_float_overflow;
3220 APFloat::getLargest(Format).toString(buffer);
3222 diagnostic = diag::warn_float_underflow;
3223 APFloat::getSmallest(Format).toString(buffer);
3226 S.Diag(Loc, diagnostic)
3228 << StringRef(buffer.data(), buffer.size());
3231 bool isExact = (result == APFloat::opOK);
3232 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3235 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3236 assert(E && "Invalid expression");
3238 if (E->isValueDependent())
3241 QualType QT = E->getType();
3242 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3243 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3247 llvm::APSInt ValueAPS;
3248 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3253 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3254 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3255 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3256 << ValueAPS.toString(10) << ValueIsPositive;
3263 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3264 // Fast path for a single digit (which is quite common). A single digit
3265 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3266 if (Tok.getLength() == 1) {
3267 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3268 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3271 SmallString<128> SpellingBuffer;
3272 // NumericLiteralParser wants to overread by one character. Add padding to
3273 // the buffer in case the token is copied to the buffer. If getSpelling()
3274 // returns a StringRef to the memory buffer, it should have a null char at
3275 // the EOF, so it is also safe.
3276 SpellingBuffer.resize(Tok.getLength() + 1);
3278 // Get the spelling of the token, which eliminates trigraphs, etc.
3279 bool Invalid = false;
3280 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3284 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3285 if (Literal.hadError)
3288 if (Literal.hasUDSuffix()) {
3289 // We're building a user-defined literal.
3290 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3291 SourceLocation UDSuffixLoc =
3292 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3294 // Make sure we're allowed user-defined literals here.
3296 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3299 if (Literal.isFloatingLiteral()) {
3300 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3301 // long double, the literal is treated as a call of the form
3302 // operator "" X (f L)
3303 CookedTy = Context.LongDoubleTy;
3305 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3306 // unsigned long long, the literal is treated as a call of the form
3307 // operator "" X (n ULL)
3308 CookedTy = Context.UnsignedLongLongTy;
3311 DeclarationName OpName =
3312 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3313 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3314 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3316 SourceLocation TokLoc = Tok.getLocation();
3318 // Perform literal operator lookup to determine if we're building a raw
3319 // literal or a cooked one.
3320 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3321 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3322 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3323 /*AllowStringTemplate*/ false,
3324 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3325 case LOLR_ErrorNoDiagnostic:
3326 // Lookup failure for imaginary constants isn't fatal, there's still the
3327 // GNU extension producing _Complex types.
3333 if (Literal.isFloatingLiteral()) {
3334 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3336 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3337 if (Literal.GetIntegerValue(ResultVal))
3338 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3339 << /* Unsigned */ 1;
3340 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3343 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3347 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3348 // literal is treated as a call of the form
3349 // operator "" X ("n")
3350 unsigned Length = Literal.getUDSuffixOffset();
3351 QualType StrTy = Context.getConstantArrayType(
3352 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3353 llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3354 Expr *Lit = StringLiteral::Create(
3355 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3356 /*Pascal*/false, StrTy, &TokLoc, 1);
3357 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3360 case LOLR_Template: {
3361 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3362 // template), L is treated as a call fo the form
3363 // operator "" X <'c1', 'c2', ... 'ck'>()
3364 // where n is the source character sequence c1 c2 ... ck.
3365 TemplateArgumentListInfo ExplicitArgs;
3366 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3367 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3368 llvm::APSInt Value(CharBits, CharIsUnsigned);
3369 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3370 Value = TokSpelling[I];
3371 TemplateArgument Arg(Context, Value, Context.CharTy);
3372 TemplateArgumentLocInfo ArgInfo;
3373 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3375 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3378 case LOLR_StringTemplate:
3379 llvm_unreachable("unexpected literal operator lookup result");
3385 if (Literal.isFixedPointLiteral()) {
3388 if (Literal.isAccum) {
3389 if (Literal.isHalf) {
3390 Ty = Context.ShortAccumTy;
3391 } else if (Literal.isLong) {
3392 Ty = Context.LongAccumTy;
3394 Ty = Context.AccumTy;
3396 } else if (Literal.isFract) {
3397 if (Literal.isHalf) {
3398 Ty = Context.ShortFractTy;
3399 } else if (Literal.isLong) {
3400 Ty = Context.LongFractTy;
3402 Ty = Context.FractTy;
3406 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3408 bool isSigned = !Literal.isUnsigned;
3409 unsigned scale = Context.getFixedPointScale(Ty);
3410 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3412 llvm::APInt Val(bit_width, 0, isSigned);
3413 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3414 bool ValIsZero = Val.isNullValue() && !Overflowed;
3416 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3417 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3418 // Clause 6.4.4 - The value of a constant shall be in the range of
3419 // representable values for its type, with exception for constants of a
3420 // fract type with a value of exactly 1; such a constant shall denote
3421 // the maximal value for the type.
3423 else if (Val.ugt(MaxVal) || Overflowed)
3424 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3426 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3427 Tok.getLocation(), scale);
3428 } else if (Literal.isFloatingLiteral()) {
3430 if (Literal.isHalf){
3431 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3432 Ty = Context.HalfTy;
3434 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3437 } else if (Literal.isFloat)
3438 Ty = Context.FloatTy;
3439 else if (Literal.isLong)
3440 Ty = Context.LongDoubleTy;
3441 else if (Literal.isFloat16)
3442 Ty = Context.Float16Ty;
3443 else if (Literal.isFloat128)
3444 Ty = Context.Float128Ty;
3446 Ty = Context.DoubleTy;
3448 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3450 if (Ty == Context.DoubleTy) {
3451 if (getLangOpts().SinglePrecisionConstants) {
3452 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3453 if (BTy->getKind() != BuiltinType::Float) {
3454 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3456 } else if (getLangOpts().OpenCL &&
3457 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3458 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3459 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3460 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3463 } else if (!Literal.isIntegerLiteral()) {
3468 // 'long long' is a C99 or C++11 feature.
3469 if (!getLangOpts().C99 && Literal.isLongLong) {
3470 if (getLangOpts().CPlusPlus)
3471 Diag(Tok.getLocation(),
3472 getLangOpts().CPlusPlus11 ?
3473 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3475 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3478 // Get the value in the widest-possible width.
3479 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3480 llvm::APInt ResultVal(MaxWidth, 0);
3482 if (Literal.GetIntegerValue(ResultVal)) {
3483 // If this value didn't fit into uintmax_t, error and force to ull.
3484 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3485 << /* Unsigned */ 1;
3486 Ty = Context.UnsignedLongLongTy;
3487 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3488 "long long is not intmax_t?");
3490 // If this value fits into a ULL, try to figure out what else it fits into
3491 // according to the rules of C99 6.4.4.1p5.
3493 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3494 // be an unsigned int.
3495 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3497 // Check from smallest to largest, picking the smallest type we can.
3500 // Microsoft specific integer suffixes are explicitly sized.
3501 if (Literal.MicrosoftInteger) {
3502 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3504 Ty = Context.CharTy;
3506 Width = Literal.MicrosoftInteger;
3507 Ty = Context.getIntTypeForBitwidth(Width,
3508 /*Signed=*/!Literal.isUnsigned);
3512 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3513 // Are int/unsigned possibilities?
3514 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3516 // Does it fit in a unsigned int?
3517 if (ResultVal.isIntN(IntSize)) {
3518 // Does it fit in a signed int?
3519 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3521 else if (AllowUnsigned)
3522 Ty = Context.UnsignedIntTy;
3527 // Are long/unsigned long possibilities?
3528 if (Ty.isNull() && !Literal.isLongLong) {
3529 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3531 // Does it fit in a unsigned long?
3532 if (ResultVal.isIntN(LongSize)) {
3533 // Does it fit in a signed long?
3534 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3535 Ty = Context.LongTy;
3536 else if (AllowUnsigned)
3537 Ty = Context.UnsignedLongTy;
3538 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3540 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3541 const unsigned LongLongSize =
3542 Context.getTargetInfo().getLongLongWidth();
3543 Diag(Tok.getLocation(),
3544 getLangOpts().CPlusPlus
3546 ? diag::warn_old_implicitly_unsigned_long_cxx
3547 : /*C++98 UB*/ diag::
3548 ext_old_implicitly_unsigned_long_cxx
3549 : diag::warn_old_implicitly_unsigned_long)
3550 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3551 : /*will be ill-formed*/ 1);
3552 Ty = Context.UnsignedLongTy;
3558 // Check long long if needed.
3560 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3562 // Does it fit in a unsigned long long?
3563 if (ResultVal.isIntN(LongLongSize)) {
3564 // Does it fit in a signed long long?
3565 // To be compatible with MSVC, hex integer literals ending with the
3566 // LL or i64 suffix are always signed in Microsoft mode.
3567 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3568 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3569 Ty = Context.LongLongTy;
3570 else if (AllowUnsigned)
3571 Ty = Context.UnsignedLongLongTy;
3572 Width = LongLongSize;
3576 // If we still couldn't decide a type, we probably have something that
3577 // does not fit in a signed long long, but has no U suffix.
3579 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3580 Ty = Context.UnsignedLongLongTy;
3581 Width = Context.getTargetInfo().getLongLongWidth();
3584 if (ResultVal.getBitWidth() != Width)
3585 ResultVal = ResultVal.trunc(Width);
3587 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3590 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3591 if (Literal.isImaginary) {
3592 Res = new (Context) ImaginaryLiteral(Res,
3593 Context.getComplexType(Res->getType()));
3595 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3600 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3601 assert(E && "ActOnParenExpr() missing expr");
3602 return new (Context) ParenExpr(L, R, E);
3605 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3607 SourceRange ArgRange) {
3608 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3609 // scalar or vector data type argument..."
3610 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3611 // type (C99 6.2.5p18) or void.
3612 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3613 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3618 assert((T->isVoidType() || !T->isIncompleteType()) &&
3619 "Scalar types should always be complete");
3623 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3625 SourceRange ArgRange,
3626 UnaryExprOrTypeTrait TraitKind) {
3627 // Invalid types must be hard errors for SFINAE in C++.
3628 if (S.LangOpts.CPlusPlus)
3632 if (T->isFunctionType() &&
3633 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3634 TraitKind == UETT_PreferredAlignOf)) {
3635 // sizeof(function)/alignof(function) is allowed as an extension.
3636 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3637 << TraitKind << ArgRange;
3641 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3642 // this is an error (OpenCL v1.1 s6.3.k)
3643 if (T->isVoidType()) {
3644 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3645 : diag::ext_sizeof_alignof_void_type;
3646 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3653 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3655 SourceRange ArgRange,
3656 UnaryExprOrTypeTrait TraitKind) {
3657 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3658 // runtime doesn't allow it.
3659 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3660 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3661 << T << (TraitKind == UETT_SizeOf)
3669 /// Check whether E is a pointer from a decayed array type (the decayed
3670 /// pointer type is equal to T) and emit a warning if it is.
3671 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3673 // Don't warn if the operation changed the type.
3674 if (T != E->getType())
3677 // Now look for array decays.
3678 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3679 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3682 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3684 << ICE->getSubExpr()->getType();
3687 /// Check the constraints on expression operands to unary type expression
3688 /// and type traits.
3690 /// Completes any types necessary and validates the constraints on the operand
3691 /// expression. The logic mostly mirrors the type-based overload, but may modify
3692 /// the expression as it completes the type for that expression through template
3693 /// instantiation, etc.
3694 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3695 UnaryExprOrTypeTrait ExprKind) {
3696 QualType ExprTy = E->getType();
3697 assert(!ExprTy->isReferenceType());
3699 if (ExprKind == UETT_VecStep)
3700 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3701 E->getSourceRange());
3703 // Whitelist some types as extensions
3704 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3705 E->getSourceRange(), ExprKind))
3708 // 'alignof' applied to an expression only requires the base element type of
3709 // the expression to be complete. 'sizeof' requires the expression's type to
3710 // be complete (and will attempt to complete it if it's an array of unknown
3712 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3713 if (RequireCompleteType(E->getExprLoc(),
3714 Context.getBaseElementType(E->getType()),
3715 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3716 E->getSourceRange()))
3719 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3720 ExprKind, E->getSourceRange()))
3724 // Completing the expression's type may have changed it.
3725 ExprTy = E->getType();
3726 assert(!ExprTy->isReferenceType());
3728 if (ExprTy->isFunctionType()) {
3729 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3730 << ExprKind << E->getSourceRange();
3734 // The operand for sizeof and alignof is in an unevaluated expression context,
3735 // so side effects could result in unintended consequences.
3736 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3737 ExprKind == UETT_PreferredAlignOf) &&
3738 !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3739 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3741 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3742 E->getSourceRange(), ExprKind))
3745 if (ExprKind == UETT_SizeOf) {
3746 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3747 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3748 QualType OType = PVD->getOriginalType();
3749 QualType Type = PVD->getType();
3750 if (Type->isPointerType() && OType->isArrayType()) {
3751 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3753 Diag(PVD->getLocation(), diag::note_declared_at);
3758 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3759 // decays into a pointer and returns an unintended result. This is most
3760 // likely a typo for "sizeof(array) op x".
3761 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3762 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3764 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3772 /// Check the constraints on operands to unary expression and type
3775 /// This will complete any types necessary, and validate the various constraints
3776 /// on those operands.
3778 /// The UsualUnaryConversions() function is *not* called by this routine.
3779 /// C99 6.3.2.1p[2-4] all state:
3780 /// Except when it is the operand of the sizeof operator ...
3782 /// C++ [expr.sizeof]p4
3783 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3784 /// standard conversions are not applied to the operand of sizeof.
3786 /// This policy is followed for all of the unary trait expressions.
3787 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3788 SourceLocation OpLoc,
3789 SourceRange ExprRange,
3790 UnaryExprOrTypeTrait ExprKind) {
3791 if (ExprType->isDependentType())
3794 // C++ [expr.sizeof]p2:
3795 // When applied to a reference or a reference type, the result
3796 // is the size of the referenced type.
3797 // C++11 [expr.alignof]p3:
3798 // When alignof is applied to a reference type, the result
3799 // shall be the alignment of the referenced type.
3800 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3801 ExprType = Ref->getPointeeType();
3803 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3804 // When alignof or _Alignof is applied to an array type, the result
3805 // is the alignment of the element type.
3806 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3807 ExprKind == UETT_OpenMPRequiredSimdAlign)
3808 ExprType = Context.getBaseElementType(ExprType);
3810 if (ExprKind == UETT_VecStep)
3811 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3813 // Whitelist some types as extensions
3814 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3818 if (RequireCompleteType(OpLoc, ExprType,
3819 diag::err_sizeof_alignof_incomplete_type,
3820 ExprKind, ExprRange))
3823 if (ExprType->isFunctionType()) {
3824 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3825 << ExprKind << ExprRange;
3829 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3836 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3837 E = E->IgnoreParens();
3839 // Cannot know anything else if the expression is dependent.
3840 if (E->isTypeDependent())
3843 if (E->getObjectKind() == OK_BitField) {
3844 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3845 << 1 << E->getSourceRange();
3849 ValueDecl *D = nullptr;
3850 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3852 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3853 D = ME->getMemberDecl();
3856 // If it's a field, require the containing struct to have a
3857 // complete definition so that we can compute the layout.
3859 // This can happen in C++11 onwards, either by naming the member
3860 // in a way that is not transformed into a member access expression
3861 // (in an unevaluated operand, for instance), or by naming the member
3862 // in a trailing-return-type.
3864 // For the record, since __alignof__ on expressions is a GCC
3865 // extension, GCC seems to permit this but always gives the
3866 // nonsensical answer 0.
3868 // We don't really need the layout here --- we could instead just
3869 // directly check for all the appropriate alignment-lowing
3870 // attributes --- but that would require duplicating a lot of
3871 // logic that just isn't worth duplicating for such a marginal
3873 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3874 // Fast path this check, since we at least know the record has a
3875 // definition if we can find a member of it.
3876 if (!FD->getParent()->isCompleteDefinition()) {
3877 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3878 << E->getSourceRange();
3882 // Otherwise, if it's a field, and the field doesn't have
3883 // reference type, then it must have a complete type (or be a
3884 // flexible array member, which we explicitly want to
3885 // white-list anyway), which makes the following checks trivial.
3886 if (!FD->getType()->isReferenceType())
3890 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3893 bool Sema::CheckVecStepExpr(Expr *E) {
3894 E = E->IgnoreParens();
3896 // Cannot know anything else if the expression is dependent.
3897 if (E->isTypeDependent())
3900 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3903 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3904 CapturingScopeInfo *CSI) {
3905 assert(T->isVariablyModifiedType());
3906 assert(CSI != nullptr);
3908 // We're going to walk down into the type and look for VLA expressions.
3910 const Type *Ty = T.getTypePtr();
3911 switch (Ty->getTypeClass()) {
3912 #define TYPE(Class, Base)
3913 #define ABSTRACT_TYPE(Class, Base)
3914 #define NON_CANONICAL_TYPE(Class, Base)
3915 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3916 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3917 #include "clang/AST/TypeNodes.def"
3920 // These types are never variably-modified.
3924 case Type::ExtVector:
3927 case Type::Elaborated:
3928 case Type::TemplateSpecialization:
3929 case Type::ObjCObject:
3930 case Type::ObjCInterface:
3931 case Type::ObjCObjectPointer:
3932 case Type::ObjCTypeParam:
3934 llvm_unreachable("type class is never variably-modified!");
3935 case Type::Adjusted:
3936 T = cast<AdjustedType>(Ty)->getOriginalType();
3939 T = cast<DecayedType>(Ty)->getPointeeType();
3942 T = cast<PointerType>(Ty)->getPointeeType();
3944 case Type::BlockPointer:
3945 T = cast<BlockPointerType>(Ty)->getPointeeType();
3947 case Type::LValueReference:
3948 case Type::RValueReference:
3949 T = cast<ReferenceType>(Ty)->getPointeeType();
3951 case Type::MemberPointer:
3952 T = cast<MemberPointerType>(Ty)->getPointeeType();
3954 case Type::ConstantArray:
3955 case Type::IncompleteArray:
3956 // Losing element qualification here is fine.
3957 T = cast<ArrayType>(Ty)->getElementType();
3959 case Type::VariableArray: {
3960 // Losing element qualification here is fine.
3961 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3963 // Unknown size indication requires no size computation.
3964 // Otherwise, evaluate and record it.
3965 if (auto Size = VAT->getSizeExpr()) {
3966 if (!CSI->isVLATypeCaptured(VAT)) {
3967 RecordDecl *CapRecord = nullptr;
3968 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3969 CapRecord = LSI->Lambda;
3970 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3971 CapRecord = CRSI->TheRecordDecl;
3974 auto ExprLoc = Size->getExprLoc();
3975 auto SizeType = Context.getSizeType();
3976 // Build the non-static data member.
3978 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3979 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3980 /*BW*/ nullptr, /*Mutable*/ false,
3981 /*InitStyle*/ ICIS_NoInit);
3982 Field->setImplicit(true);
3983 Field->setAccess(AS_private);
3984 Field->setCapturedVLAType(VAT);
3985 CapRecord->addDecl(Field);
3987 CSI->addVLATypeCapture(ExprLoc, SizeType);
3991 T = VAT->getElementType();
3994 case Type::FunctionProto:
3995 case Type::FunctionNoProto:
3996 T = cast<FunctionType>(Ty)->getReturnType();
4000 case Type::UnaryTransform:
4001 case Type::Attributed:
4002 case Type::SubstTemplateTypeParm:
4003 case Type::PackExpansion:
4004 // Keep walking after single level desugaring.
4005 T = T.getSingleStepDesugaredType(Context);
4008 T = cast<TypedefType>(Ty)->desugar();
4010 case Type::Decltype:
4011 T = cast<DecltypeType>(Ty)->desugar();
4014 case Type::DeducedTemplateSpecialization:
4015 T = cast<DeducedType>(Ty)->getDeducedType();
4017 case Type::TypeOfExpr:
4018 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4021 T = cast<AtomicType>(Ty)->getValueType();
4024 } while (!T.isNull() && T->isVariablyModifiedType());
4027 /// Build a sizeof or alignof expression given a type operand.
4029 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4030 SourceLocation OpLoc,
4031 UnaryExprOrTypeTrait ExprKind,
4036 QualType T = TInfo->getType();
4038 if (!T->isDependentType() &&
4039 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4042 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4043 if (auto *TT = T->getAs<TypedefType>()) {
4044 for (auto I = FunctionScopes.rbegin(),
4045 E = std::prev(FunctionScopes.rend());
4047 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4050 DeclContext *DC = nullptr;
4051 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4052 DC = LSI->CallOperator;
4053 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4054 DC = CRSI->TheCapturedDecl;
4055 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4058 if (DC->containsDecl(TT->getDecl()))
4060 captureVariablyModifiedType(Context, T, CSI);
4066 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4067 return new (Context) UnaryExprOrTypeTraitExpr(
4068 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4071 /// Build a sizeof or alignof expression given an expression
4074 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4075 UnaryExprOrTypeTrait ExprKind) {
4076 ExprResult PE = CheckPlaceholderExpr(E);
4082 // Verify that the operand is valid.
4083 bool isInvalid = false;
4084 if (E->isTypeDependent()) {
4085 // Delay type-checking for type-dependent expressions.
4086 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4087 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4088 } else if (ExprKind == UETT_VecStep) {
4089 isInvalid = CheckVecStepExpr(E);
4090 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4091 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4093 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4094 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4097 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4103 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4104 PE = TransformToPotentiallyEvaluated(E);
4105 if (PE.isInvalid()) return ExprError();
4109 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4110 return new (Context) UnaryExprOrTypeTraitExpr(
4111 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4114 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4115 /// expr and the same for @c alignof and @c __alignof
4116 /// Note that the ArgRange is invalid if isType is false.
4118 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4119 UnaryExprOrTypeTrait ExprKind, bool IsType,
4120 void *TyOrEx, SourceRange ArgRange) {
4121 // If error parsing type, ignore.
4122 if (!TyOrEx) return ExprError();
4125 TypeSourceInfo *TInfo;
4126 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4127 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4130 Expr *ArgEx = (Expr *)TyOrEx;
4131 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4135 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4137 if (V.get()->isTypeDependent())
4138 return S.Context.DependentTy;
4140 // _Real and _Imag are only l-values for normal l-values.
4141 if (V.get()->getObjectKind() != OK_Ordinary) {
4142 V = S.DefaultLvalueConversion(V.get());
4147 // These operators return the element type of a complex type.
4148 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4149 return CT->getElementType();
4151 // Otherwise they pass through real integer and floating point types here.
4152 if (V.get()->getType()->isArithmeticType())
4153 return V.get()->getType();
4155 // Test for placeholders.
4156 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4157 if (PR.isInvalid()) return QualType();
4158 if (PR.get() != V.get()) {
4160 return CheckRealImagOperand(S, V, Loc, IsReal);
4163 // Reject anything else.
4164 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4165 << (IsReal ? "__real" : "__imag");
4172 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4173 tok::TokenKind Kind, Expr *Input) {
4174 UnaryOperatorKind Opc;
4176 default: llvm_unreachable("Unknown unary op!");
4177 case tok::plusplus: Opc = UO_PostInc; break;
4178 case tok::minusminus: Opc = UO_PostDec; break;
4181 // Since this might is a postfix expression, get rid of ParenListExprs.
4182 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4183 if (Result.isInvalid()) return ExprError();
4184 Input = Result.get();
4186 return BuildUnaryOp(S, OpLoc, Opc, Input);
4189 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4191 /// \return true on error
4192 static bool checkArithmeticOnObjCPointer(Sema &S,
4193 SourceLocation opLoc,
4195 assert(op->getType()->isObjCObjectPointerType());
4196 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4197 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4200 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4201 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4202 << op->getSourceRange();
4206 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4207 auto *BaseNoParens = Base->IgnoreParens();
4208 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4209 return MSProp->getPropertyDecl()->getType()->isArrayType();
4210 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4214 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4215 Expr *idx, SourceLocation rbLoc) {
4216 if (base && !base->getType().isNull() &&
4217 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4218 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4219 /*Length=*/nullptr, rbLoc);
4221 // Since this might be a postfix expression, get rid of ParenListExprs.
4222 if (isa<ParenListExpr>(base)) {
4223 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4224 if (result.isInvalid()) return ExprError();
4225 base = result.get();
4228 // Handle any non-overload placeholder types in the base and index
4229 // expressions. We can't handle overloads here because the other
4230 // operand might be an overloadable type, in which case the overload
4231 // resolution for the operator overload should get the first crack
4233 bool IsMSPropertySubscript = false;
4234 if (base->getType()->isNonOverloadPlaceholderType()) {
4235 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4236 if (!IsMSPropertySubscript) {
4237 ExprResult result = CheckPlaceholderExpr(base);
4238 if (result.isInvalid())
4240 base = result.get();
4243 if (idx->getType()->isNonOverloadPlaceholderType()) {
4244 ExprResult result = CheckPlaceholderExpr(idx);
4245 if (result.isInvalid()) return ExprError();
4249 // Build an unanalyzed expression if either operand is type-dependent.
4250 if (getLangOpts().CPlusPlus &&
4251 (base->isTypeDependent() || idx->isTypeDependent())) {
4252 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4253 VK_LValue, OK_Ordinary, rbLoc);
4256 // MSDN, property (C++)
4257 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4258 // This attribute can also be used in the declaration of an empty array in a
4259 // class or structure definition. For example:
4260 // __declspec(property(get=GetX, put=PutX)) int x[];
4261 // The above statement indicates that x[] can be used with one or more array
4262 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4263 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4264 if (IsMSPropertySubscript) {
4265 // Build MS property subscript expression if base is MS property reference
4266 // or MS property subscript.
4267 return new (Context) MSPropertySubscriptExpr(
4268 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4271 // Use C++ overloaded-operator rules if either operand has record
4272 // type. The spec says to do this if either type is *overloadable*,
4273 // but enum types can't declare subscript operators or conversion
4274 // operators, so there's nothing interesting for overload resolution
4275 // to do if there aren't any record types involved.
4277 // ObjC pointers have their own subscripting logic that is not tied
4278 // to overload resolution and so should not take this path.
4279 if (getLangOpts().CPlusPlus &&
4280 (base->getType()->isRecordType() ||
4281 (!base->getType()->isObjCObjectPointerType() &&
4282 idx->getType()->isRecordType()))) {
4283 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4286 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4288 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4289 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4294 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4295 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4296 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4298 // For expressions like `&(*s).b`, the base is recorded and what should be
4300 const MemberExpr *Member = nullptr;
4301 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4302 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4304 LastRecord.PossibleDerefs.erase(StrippedExpr);
4307 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4308 QualType ResultTy = E->getType();
4309 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4311 // Bail if the element is an array since it is not memory access.
4312 if (isa<ArrayType>(ResultTy))
4315 if (ResultTy->hasAttr(attr::NoDeref)) {
4316 LastRecord.PossibleDerefs.insert(E);
4320 // Check if the base type is a pointer to a member access of a struct
4321 // marked with noderef.
4322 const Expr *Base = E->getBase();
4323 QualType BaseTy = Base->getType();
4324 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4325 // Not a pointer access
4328 const MemberExpr *Member = nullptr;
4329 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4331 Base = Member->getBase();
4333 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4334 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4335 LastRecord.PossibleDerefs.insert(E);
4339 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4341 SourceLocation ColonLoc, Expr *Length,
4342 SourceLocation RBLoc) {
4343 if (Base->getType()->isPlaceholderType() &&
4344 !Base->getType()->isSpecificPlaceholderType(
4345 BuiltinType::OMPArraySection)) {
4346 ExprResult Result = CheckPlaceholderExpr(Base);
4347 if (Result.isInvalid())
4349 Base = Result.get();
4351 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4352 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4353 if (Result.isInvalid())
4355 Result = DefaultLvalueConversion(Result.get());
4356 if (Result.isInvalid())
4358 LowerBound = Result.get();
4360 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4361 ExprResult Result = CheckPlaceholderExpr(Length);
4362 if (Result.isInvalid())
4364 Result = DefaultLvalueConversion(Result.get());
4365 if (Result.isInvalid())
4367 Length = Result.get();
4370 // Build an unanalyzed expression if either operand is type-dependent.
4371 if (Base->isTypeDependent() ||
4373 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4374 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4375 return new (Context)
4376 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4377 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4380 // Perform default conversions.
4381 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4383 if (OriginalTy->isAnyPointerType()) {
4384 ResultTy = OriginalTy->getPointeeType();
4385 } else if (OriginalTy->isArrayType()) {
4386 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4389 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4390 << Base->getSourceRange());
4394 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4396 if (Res.isInvalid())
4397 return ExprError(Diag(LowerBound->getExprLoc(),
4398 diag::err_omp_typecheck_section_not_integer)
4399 << 0 << LowerBound->getSourceRange());
4400 LowerBound = Res.get();
4402 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4403 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4404 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4405 << 0 << LowerBound->getSourceRange();
4409 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4410 if (Res.isInvalid())
4411 return ExprError(Diag(Length->getExprLoc(),
4412 diag::err_omp_typecheck_section_not_integer)
4413 << 1 << Length->getSourceRange());
4416 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4417 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4418 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4419 << 1 << Length->getSourceRange();
4422 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4423 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4424 // type. Note that functions are not objects, and that (in C99 parlance)
4425 // incomplete types are not object types.
4426 if (ResultTy->isFunctionType()) {
4427 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4428 << ResultTy << Base->getSourceRange();
4432 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4433 diag::err_omp_section_incomplete_type, Base))
4436 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4437 Expr::EvalResult Result;
4438 if (LowerBound->EvaluateAsInt(Result, Context)) {
4439 // OpenMP 4.5, [2.4 Array Sections]
4440 // The array section must be a subset of the original array.
4441 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4442 if (LowerBoundValue.isNegative()) {
4443 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4444 << LowerBound->getSourceRange();
4451 Expr::EvalResult Result;
4452 if (Length->EvaluateAsInt(Result, Context)) {
4453 // OpenMP 4.5, [2.4 Array Sections]
4454 // The length must evaluate to non-negative integers.
4455 llvm::APSInt LengthValue = Result.Val.getInt();
4456 if (LengthValue.isNegative()) {
4457 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4458 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4459 << Length->getSourceRange();
4463 } else if (ColonLoc.isValid() &&
4464 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4465 !OriginalTy->isVariableArrayType()))) {
4466 // OpenMP 4.5, [2.4 Array Sections]
4467 // When the size of the array dimension is not known, the length must be
4468 // specified explicitly.
4469 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4470 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4474 if (!Base->getType()->isSpecificPlaceholderType(
4475 BuiltinType::OMPArraySection)) {
4476 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4477 if (Result.isInvalid())
4479 Base = Result.get();
4481 return new (Context)
4482 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4483 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4487 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4488 Expr *Idx, SourceLocation RLoc) {
4489 Expr *LHSExp = Base;
4492 ExprValueKind VK = VK_LValue;
4493 ExprObjectKind OK = OK_Ordinary;
4495 // Per C++ core issue 1213, the result is an xvalue if either operand is
4496 // a non-lvalue array, and an lvalue otherwise.
4497 if (getLangOpts().CPlusPlus11) {
4498 for (auto *Op : {LHSExp, RHSExp}) {
4499 Op = Op->IgnoreImplicit();
4500 if (Op->getType()->isArrayType() && !Op->isLValue())
4505 // Perform default conversions.
4506 if (!LHSExp->getType()->getAs<VectorType>()) {
4507 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4508 if (Result.isInvalid())
4510 LHSExp = Result.get();
4512 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4513 if (Result.isInvalid())
4515 RHSExp = Result.get();
4517 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4519 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4520 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4521 // in the subscript position. As a result, we need to derive the array base
4522 // and index from the expression types.
4523 Expr *BaseExpr, *IndexExpr;
4524 QualType ResultType;
4525 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4528 ResultType = Context.DependentTy;
4529 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4532 ResultType = PTy->getPointeeType();
4533 } else if (const ObjCObjectPointerType *PTy =
4534 LHSTy->getAs<ObjCObjectPointerType>()) {
4538 // Use custom logic if this should be the pseudo-object subscript
4540 if (!LangOpts.isSubscriptPointerArithmetic())
4541 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4544 ResultType = PTy->getPointeeType();
4545 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4546 // Handle the uncommon case of "123[Ptr]".
4549 ResultType = PTy->getPointeeType();
4550 } else if (const ObjCObjectPointerType *PTy =
4551 RHSTy->getAs<ObjCObjectPointerType>()) {
4552 // Handle the uncommon case of "123[Ptr]".
4555 ResultType = PTy->getPointeeType();
4556 if (!LangOpts.isSubscriptPointerArithmetic()) {
4557 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4558 << ResultType << BaseExpr->getSourceRange();
4561 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4562 BaseExpr = LHSExp; // vectors: V[123]
4564 // We apply C++ DR1213 to vector subscripting too.
4565 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4566 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4567 if (Materialized.isInvalid())
4569 LHSExp = Materialized.get();
4571 VK = LHSExp->getValueKind();
4572 if (VK != VK_RValue)
4573 OK = OK_VectorComponent;
4575 ResultType = VTy->getElementType();
4576 QualType BaseType = BaseExpr->getType();
4577 Qualifiers BaseQuals = BaseType.getQualifiers();
4578 Qualifiers MemberQuals = ResultType.getQualifiers();
4579 Qualifiers Combined = BaseQuals + MemberQuals;
4580 if (Combined != MemberQuals)
4581 ResultType = Context.getQualifiedType(ResultType, Combined);
4582 } else if (LHSTy->isArrayType()) {
4583 // If we see an array that wasn't promoted by
4584 // DefaultFunctionArrayLvalueConversion, it must be an array that
4585 // wasn't promoted because of the C90 rule that doesn't
4586 // allow promoting non-lvalue arrays. Warn, then
4587 // force the promotion here.
4588 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4589 << LHSExp->getSourceRange();
4590 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4591 CK_ArrayToPointerDecay).get();
4592 LHSTy = LHSExp->getType();
4596 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4597 } else if (RHSTy->isArrayType()) {
4598 // Same as previous, except for 123[f().a] case
4599 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4600 << RHSExp->getSourceRange();
4601 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4602 CK_ArrayToPointerDecay).get();
4603 RHSTy = RHSExp->getType();
4607 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4609 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4610 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4613 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4614 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4615 << IndexExpr->getSourceRange());
4617 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4618 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4619 && !IndexExpr->isTypeDependent())
4620 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4622 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4623 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4624 // type. Note that Functions are not objects, and that (in C99 parlance)
4625 // incomplete types are not object types.
4626 if (ResultType->isFunctionType()) {
4627 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4628 << ResultType << BaseExpr->getSourceRange();
4632 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4633 // GNU extension: subscripting on pointer to void
4634 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4635 << BaseExpr->getSourceRange();
4637 // C forbids expressions of unqualified void type from being l-values.
4638 // See IsCForbiddenLValueType.
4639 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4640 } else if (!ResultType->isDependentType() &&
4641 RequireCompleteType(LLoc, ResultType,
4642 diag::err_subscript_incomplete_type, BaseExpr))
4645 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4646 !ResultType.isCForbiddenLValueType());
4648 return new (Context)
4649 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4652 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4653 ParmVarDecl *Param) {
4654 if (Param->hasUnparsedDefaultArg()) {
4656 diag::err_use_of_default_argument_to_function_declared_later) <<
4657 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4658 Diag(UnparsedDefaultArgLocs[Param],
4659 diag::note_default_argument_declared_here);
4663 if (Param->hasUninstantiatedDefaultArg()) {
4664 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4666 EnterExpressionEvaluationContext EvalContext(
4667 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4669 // Instantiate the expression.
4671 // FIXME: Pass in a correct Pattern argument, otherwise
4672 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4674 // template<typename T>
4676 // static int FooImpl();
4678 // template<typename Tp>
4679 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4680 // // template argument list [[T], [Tp]], should be [[Tp]].
4681 // friend A<Tp> Foo(int a);
4684 // template<typename T>
4685 // A<T> Foo(int a = A<T>::FooImpl());
4686 MultiLevelTemplateArgumentList MutiLevelArgList
4687 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4689 InstantiatingTemplate Inst(*this, CallLoc, Param,
4690 MutiLevelArgList.getInnermost());
4691 if (Inst.isInvalid())
4693 if (Inst.isAlreadyInstantiating()) {
4694 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4695 Param->setInvalidDecl();
4701 // C++ [dcl.fct.default]p5:
4702 // The names in the [default argument] expression are bound, and
4703 // the semantic constraints are checked, at the point where the
4704 // default argument expression appears.
4705 ContextRAII SavedContext(*this, FD);
4706 LocalInstantiationScope Local(*this);
4707 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4708 /*DirectInit*/false);
4710 if (Result.isInvalid())
4713 // Check the expression as an initializer for the parameter.
4714 InitializedEntity Entity
4715 = InitializedEntity::InitializeParameter(Context, Param);
4716 InitializationKind Kind = InitializationKind::CreateCopy(
4717 Param->getLocation(),
4718 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4719 Expr *ResultE = Result.getAs<Expr>();
4721 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4722 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4723 if (Result.isInvalid())
4726 Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4727 Param->getOuterLocStart());
4728 if (Result.isInvalid())
4731 // Remember the instantiated default argument.
4732 Param->setDefaultArg(Result.getAs<Expr>());
4733 if (ASTMutationListener *L = getASTMutationListener()) {
4734 L->DefaultArgumentInstantiated(Param);
4738 // If the default argument expression is not set yet, we are building it now.
4739 if (!Param->hasInit()) {
4740 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4741 Param->setInvalidDecl();
4745 // If the default expression creates temporaries, we need to
4746 // push them to the current stack of expression temporaries so they'll
4747 // be properly destroyed.
4748 // FIXME: We should really be rebuilding the default argument with new
4749 // bound temporaries; see the comment in PR5810.
4750 // We don't need to do that with block decls, though, because
4751 // blocks in default argument expression can never capture anything.
4752 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4753 // Set the "needs cleanups" bit regardless of whether there are
4754 // any explicit objects.
4755 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4757 // Append all the objects to the cleanup list. Right now, this
4758 // should always be a no-op, because blocks in default argument
4759 // expressions should never be able to capture anything.
4760 assert(!Init->getNumObjects() &&
4761 "default argument expression has capturing blocks?");
4764 // We already type-checked the argument, so we know it works.
4765 // Just mark all of the declarations in this potentially-evaluated expression
4766 // as being "referenced".
4767 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4768 /*SkipLocalVariables=*/true);
4772 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4773 FunctionDecl *FD, ParmVarDecl *Param) {
4774 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4776 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4779 Sema::VariadicCallType
4780 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4782 if (Proto && Proto->isVariadic()) {
4783 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4784 return VariadicConstructor;
4785 else if (Fn && Fn->getType()->isBlockPointerType())
4786 return VariadicBlock;
4788 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4789 if (Method->isInstance())
4790 return VariadicMethod;
4791 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4792 return VariadicMethod;
4793 return VariadicFunction;
4795 return VariadicDoesNotApply;
4799 class FunctionCallCCC : public FunctionCallFilterCCC {
4801 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4802 unsigned NumArgs, MemberExpr *ME)
4803 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4804 FunctionName(FuncName) {}
4806 bool ValidateCandidate(const TypoCorrection &candidate) override {
4807 if (!candidate.getCorrectionSpecifier() ||
4808 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4812 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4816 const IdentifierInfo *const FunctionName;
4820 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4821 FunctionDecl *FDecl,
4822 ArrayRef<Expr *> Args) {
4823 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4824 DeclarationName FuncName = FDecl->getDeclName();
4825 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4827 if (TypoCorrection Corrected = S.CorrectTypo(
4828 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4829 S.getScopeForContext(S.CurContext), nullptr,
4830 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4832 Sema::CTK_ErrorRecovery)) {
4833 if (NamedDecl *ND = Corrected.getFoundDecl()) {
4834 if (Corrected.isOverloaded()) {
4835 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4836 OverloadCandidateSet::iterator Best;
4837 for (NamedDecl *CD : Corrected) {
4838 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4839 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4842 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4844 ND = Best->FoundDecl;
4845 Corrected.setCorrectionDecl(ND);
4851 ND = ND->getUnderlyingDecl();
4852 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4856 return TypoCorrection();
4859 /// ConvertArgumentsForCall - Converts the arguments specified in
4860 /// Args/NumArgs to the parameter types of the function FDecl with
4861 /// function prototype Proto. Call is the call expression itself, and
4862 /// Fn is the function expression. For a C++ member function, this
4863 /// routine does not attempt to convert the object argument. Returns
4864 /// true if the call is ill-formed.
4866 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4867 FunctionDecl *FDecl,
4868 const FunctionProtoType *Proto,
4869 ArrayRef<Expr *> Args,
4870 SourceLocation RParenLoc,
4871 bool IsExecConfig) {
4872 // Bail out early if calling a builtin with custom typechecking.
4874 if (unsigned ID = FDecl->getBuiltinID())
4875 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4878 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4879 // assignment, to the types of the corresponding parameter, ...
4880 unsigned NumParams = Proto->getNumParams();
4881 bool Invalid = false;
4882 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4883 unsigned FnKind = Fn->getType()->isBlockPointerType()
4885 : (IsExecConfig ? 3 /* kernel function (exec config) */
4886 : 0 /* function */);
4888 // If too few arguments are available (and we don't have default
4889 // arguments for the remaining parameters), don't make the call.
4890 if (Args.size() < NumParams) {
4891 if (Args.size() < MinArgs) {
4893 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4895 MinArgs == NumParams && !Proto->isVariadic()
4896 ? diag::err_typecheck_call_too_few_args_suggest
4897 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4898 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4899 << static_cast<unsigned>(Args.size())
4900 << TC.getCorrectionRange());
4901 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4903 MinArgs == NumParams && !Proto->isVariadic()
4904 ? diag::err_typecheck_call_too_few_args_one
4905 : diag::err_typecheck_call_too_few_args_at_least_one)
4906 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4908 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4909 ? diag::err_typecheck_call_too_few_args
4910 : diag::err_typecheck_call_too_few_args_at_least)
4911 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4912 << Fn->getSourceRange();
4914 // Emit the location of the prototype.
4915 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4916 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4920 // We reserve space for the default arguments when we create
4921 // the call expression, before calling ConvertArgumentsForCall.
4922 assert((Call->getNumArgs() == NumParams) &&
4923 "We should have reserved space for the default arguments before!");
4926 // If too many are passed and not variadic, error on the extras and drop
4928 if (Args.size() > NumParams) {
4929 if (!Proto->isVariadic()) {
4931 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4933 MinArgs == NumParams && !Proto->isVariadic()
4934 ? diag::err_typecheck_call_too_many_args_suggest
4935 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4936 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4937 << static_cast<unsigned>(Args.size())
4938 << TC.getCorrectionRange());
4939 } else if (NumParams == 1 && FDecl &&
4940 FDecl->getParamDecl(0)->getDeclName())
4941 Diag(Args[NumParams]->getBeginLoc(),
4942 MinArgs == NumParams
4943 ? diag::err_typecheck_call_too_many_args_one
4944 : diag::err_typecheck_call_too_many_args_at_most_one)
4945 << FnKind << FDecl->getParamDecl(0)
4946 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4947 << SourceRange(Args[NumParams]->getBeginLoc(),
4948 Args.back()->getEndLoc());
4950 Diag(Args[NumParams]->getBeginLoc(),
4951 MinArgs == NumParams
4952 ? diag::err_typecheck_call_too_many_args
4953 : diag::err_typecheck_call_too_many_args_at_most)
4954 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4955 << Fn->getSourceRange()
4956 << SourceRange(Args[NumParams]->getBeginLoc(),
4957 Args.back()->getEndLoc());
4959 // Emit the location of the prototype.
4960 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4961 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4963 // This deletes the extra arguments.
4964 Call->shrinkNumArgs(NumParams);
4968 SmallVector<Expr *, 8> AllArgs;
4969 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4971 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
4975 unsigned TotalNumArgs = AllArgs.size();
4976 for (unsigned i = 0; i < TotalNumArgs; ++i)
4977 Call->setArg(i, AllArgs[i]);
4982 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4983 const FunctionProtoType *Proto,
4984 unsigned FirstParam, ArrayRef<Expr *> Args,
4985 SmallVectorImpl<Expr *> &AllArgs,
4986 VariadicCallType CallType, bool AllowExplicit,
4987 bool IsListInitialization) {
4988 unsigned NumParams = Proto->getNumParams();
4989 bool Invalid = false;
4991 // Continue to check argument types (even if we have too few/many args).
4992 for (unsigned i = FirstParam; i < NumParams; i++) {
4993 QualType ProtoArgType = Proto->getParamType(i);
4996 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4997 if (ArgIx < Args.size()) {
4998 Arg = Args[ArgIx++];
5000 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5001 diag::err_call_incomplete_argument, Arg))
5004 // Strip the unbridged-cast placeholder expression off, if applicable.
5005 bool CFAudited = false;
5006 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5007 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5008 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5009 Arg = stripARCUnbridgedCast(Arg);
5010 else if (getLangOpts().ObjCAutoRefCount &&
5011 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5012 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5015 if (Proto->getExtParameterInfo(i).isNoEscape())
5016 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5017 BE->getBlockDecl()->setDoesNotEscape();
5019 InitializedEntity Entity =
5020 Param ? InitializedEntity::InitializeParameter(Context, Param,
5022 : InitializedEntity::InitializeParameter(
5023 Context, ProtoArgType, Proto->isParamConsumed(i));
5025 // Remember that parameter belongs to a CF audited API.
5027 Entity.setParameterCFAudited();
5029 ExprResult ArgE = PerformCopyInitialization(
5030 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5031 if (ArgE.isInvalid())
5034 Arg = ArgE.getAs<Expr>();
5036 assert(Param && "can't use default arguments without a known callee");
5038 ExprResult ArgExpr =
5039 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5040 if (ArgExpr.isInvalid())
5043 Arg = ArgExpr.getAs<Expr>();
5046 // Check for array bounds violations for each argument to the call. This
5047 // check only triggers warnings when the argument isn't a more complex Expr
5048 // with its own checking, such as a BinaryOperator.
5049 CheckArrayAccess(Arg);
5051 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5052 CheckStaticArrayArgument(CallLoc, Param, Arg);
5054 AllArgs.push_back(Arg);
5057 // If this is a variadic call, handle args passed through "...".
5058 if (CallType != VariadicDoesNotApply) {
5059 // Assume that extern "C" functions with variadic arguments that
5060 // return __unknown_anytype aren't *really* variadic.
5061 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5062 FDecl->isExternC()) {
5063 for (Expr *A : Args.slice(ArgIx)) {
5064 QualType paramType; // ignored
5065 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5066 Invalid |= arg.isInvalid();
5067 AllArgs.push_back(arg.get());
5070 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5072 for (Expr *A : Args.slice(ArgIx)) {
5073 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5074 Invalid |= Arg.isInvalid();
5075 AllArgs.push_back(Arg.get());
5079 // Check for array bounds violations.
5080 for (Expr *A : Args.slice(ArgIx))
5081 CheckArrayAccess(A);
5086 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5087 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5088 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5089 TL = DTL.getOriginalLoc();
5090 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5091 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5092 << ATL.getLocalSourceRange();
5095 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5096 /// array parameter, check that it is non-null, and that if it is formed by
5097 /// array-to-pointer decay, the underlying array is sufficiently large.
5099 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5100 /// array type derivation, then for each call to the function, the value of the
5101 /// corresponding actual argument shall provide access to the first element of
5102 /// an array with at least as many elements as specified by the size expression.
5104 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5106 const Expr *ArgExpr) {
5107 // Static array parameters are not supported in C++.
5108 if (!Param || getLangOpts().CPlusPlus)
5111 QualType OrigTy = Param->getOriginalType();
5113 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5114 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5117 if (ArgExpr->isNullPointerConstant(Context,
5118 Expr::NPC_NeverValueDependent)) {
5119 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5120 DiagnoseCalleeStaticArrayParam(*this, Param);
5124 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5128 const ConstantArrayType *ArgCAT =
5129 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5133 if (ArgCAT->getSize().ult(CAT->getSize())) {
5134 Diag(CallLoc, diag::warn_static_array_too_small)
5135 << ArgExpr->getSourceRange()
5136 << (unsigned) ArgCAT->getSize().getZExtValue()
5137 << (unsigned) CAT->getSize().getZExtValue();
5138 DiagnoseCalleeStaticArrayParam(*this, Param);
5142 /// Given a function expression of unknown-any type, try to rebuild it
5143 /// to have a function type.
5144 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5146 /// Is the given type a placeholder that we need to lower out
5147 /// immediately during argument processing?
5148 static bool isPlaceholderToRemoveAsArg(QualType type) {
5149 // Placeholders are never sugared.
5150 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5151 if (!placeholder) return false;
5153 switch (placeholder->getKind()) {
5154 // Ignore all the non-placeholder types.
5155 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5156 case BuiltinType::Id:
5157 #include "clang/Basic/OpenCLImageTypes.def"
5158 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5159 case BuiltinType::Id:
5160 #include "clang/Basic/OpenCLExtensionTypes.def"
5161 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5162 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5163 #include "clang/AST/BuiltinTypes.def"
5166 // We cannot lower out overload sets; they might validly be resolved
5167 // by the call machinery.
5168 case BuiltinType::Overload:
5171 // Unbridged casts in ARC can be handled in some call positions and
5172 // should be left in place.
5173 case BuiltinType::ARCUnbridgedCast:
5176 // Pseudo-objects should be converted as soon as possible.
5177 case BuiltinType::PseudoObject:
5180 // The debugger mode could theoretically but currently does not try
5181 // to resolve unknown-typed arguments based on known parameter types.
5182 case BuiltinType::UnknownAny:
5185 // These are always invalid as call arguments and should be reported.
5186 case BuiltinType::BoundMember:
5187 case BuiltinType::BuiltinFn:
5188 case BuiltinType::OMPArraySection:
5192 llvm_unreachable("bad builtin type kind");
5195 /// Check an argument list for placeholders that we won't try to
5197 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5198 // Apply this processing to all the arguments at once instead of
5199 // dying at the first failure.
5200 bool hasInvalid = false;
5201 for (size_t i = 0, e = args.size(); i != e; i++) {
5202 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5203 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5204 if (result.isInvalid()) hasInvalid = true;
5205 else args[i] = result.get();
5206 } else if (hasInvalid) {
5207 (void)S.CorrectDelayedTyposInExpr(args[i]);
5213 /// If a builtin function has a pointer argument with no explicit address
5214 /// space, then it should be able to accept a pointer to any address
5215 /// space as input. In order to do this, we need to replace the
5216 /// standard builtin declaration with one that uses the same address space
5219 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5220 /// it does not contain any pointer arguments without
5221 /// an address space qualifer. Otherwise the rewritten
5222 /// FunctionDecl is returned.
5223 /// TODO: Handle pointer return types.
5224 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5225 const FunctionDecl *FDecl,
5226 MultiExprArg ArgExprs) {
5228 QualType DeclType = FDecl->getType();
5229 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5231 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5232 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5235 bool NeedsNewDecl = false;
5237 SmallVector<QualType, 8> OverloadParams;
5239 for (QualType ParamType : FT->param_types()) {
5241 // Convert array arguments to pointer to simplify type lookup.
5243 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5244 if (ArgRes.isInvalid())
5246 Expr *Arg = ArgRes.get();
5247 QualType ArgType = Arg->getType();
5248 if (!ParamType->isPointerType() ||
5249 ParamType.getQualifiers().hasAddressSpace() ||
5250 !ArgType->isPointerType() ||
5251 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5252 OverloadParams.push_back(ParamType);
5256 QualType PointeeType = ParamType->getPointeeType();
5257 if (PointeeType.getQualifiers().hasAddressSpace())
5260 NeedsNewDecl = true;
5261 LangAS AS = ArgType->getPointeeType().getAddressSpace();
5263 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5264 OverloadParams.push_back(Context.getPointerType(PointeeType));
5270 FunctionProtoType::ExtProtoInfo EPI;
5271 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5272 OverloadParams, EPI);
5273 DeclContext *Parent = Context.getTranslationUnitDecl();
5274 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5275 FDecl->getLocation(),
5276 FDecl->getLocation(),
5277 FDecl->getIdentifier(),
5281 /*hasPrototype=*/true);
5282 SmallVector<ParmVarDecl*, 16> Params;
5283 FT = cast<FunctionProtoType>(OverloadTy);
5284 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5285 QualType ParamType = FT->getParamType(i);
5287 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5288 SourceLocation(), nullptr, ParamType,
5289 /*TInfo=*/nullptr, SC_None, nullptr);
5290 Parm->setScopeInfo(0, i);
5291 Params.push_back(Parm);
5293 OverloadDecl->setParams(Params);
5294 return OverloadDecl;
5297 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5298 FunctionDecl *Callee,
5299 MultiExprArg ArgExprs) {
5300 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5301 // similar attributes) really don't like it when functions are called with an
5302 // invalid number of args.
5303 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5304 /*PartialOverloading=*/false) &&
5305 !Callee->isVariadic())
5307 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5310 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5311 S.Diag(Fn->getBeginLoc(),
5312 isa<CXXMethodDecl>(Callee)
5313 ? diag::err_ovl_no_viable_member_function_in_call
5314 : diag::err_ovl_no_viable_function_in_call)
5315 << Callee << Callee->getSourceRange();
5316 S.Diag(Callee->getLocation(),
5317 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5318 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5323 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5324 const UnresolvedMemberExpr *const UME, Sema &S) {
5326 const auto GetFunctionLevelDCIfCXXClass =
5327 [](Sema &S) -> const CXXRecordDecl * {
5328 const DeclContext *const DC = S.getFunctionLevelDeclContext();
5329 if (!DC || !DC->getParent())
5332 // If the call to some member function was made from within a member
5333 // function body 'M' return return 'M's parent.
5334 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5335 return MD->getParent()->getCanonicalDecl();
5336 // else the call was made from within a default member initializer of a
5337 // class, so return the class.
5338 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5339 return RD->getCanonicalDecl();
5342 // If our DeclContext is neither a member function nor a class (in the
5343 // case of a lambda in a default member initializer), we can't have an
5344 // enclosing 'this'.
5346 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5347 if (!CurParentClass)
5350 // The naming class for implicit member functions call is the class in which
5351 // name lookup starts.
5352 const CXXRecordDecl *const NamingClass =
5353 UME->getNamingClass()->getCanonicalDecl();
5354 assert(NamingClass && "Must have naming class even for implicit access");
5356 // If the unresolved member functions were found in a 'naming class' that is
5357 // related (either the same or derived from) to the class that contains the
5358 // member function that itself contained the implicit member access.
5360 return CurParentClass == NamingClass ||
5361 CurParentClass->isDerivedFrom(NamingClass);
5365 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5366 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5371 LambdaScopeInfo *const CurLSI = S.getCurLambda();
5372 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5373 // already been captured, or if this is an implicit member function call (if
5374 // it isn't, an attempt to capture 'this' should already have been made).
5375 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5376 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5379 // Check if the naming class in which the unresolved members were found is
5380 // related (same as or is a base of) to the enclosing class.
5382 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5386 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5387 // If the enclosing function is not dependent, then this lambda is
5388 // capture ready, so if we can capture this, do so.
5389 if (!EnclosingFunctionCtx->isDependentContext()) {
5390 // If the current lambda and all enclosing lambdas can capture 'this' -
5391 // then go ahead and capture 'this' (since our unresolved overload set
5392 // contains at least one non-static member function).
5393 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5394 S.CheckCXXThisCapture(CallLoc);
5395 } else if (S.CurContext->isDependentContext()) {
5396 // ... since this is an implicit member reference, that might potentially
5397 // involve a 'this' capture, mark 'this' for potential capture in
5398 // enclosing lambdas.
5399 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5400 CurLSI->addPotentialThisCapture(CallLoc);
5404 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5405 /// This provides the location of the left/right parens and a list of comma
5407 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5408 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5409 Expr *ExecConfig, bool IsExecConfig) {
5410 // Since this might be a postfix expression, get rid of ParenListExprs.
5411 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5412 if (Result.isInvalid()) return ExprError();
5415 if (checkArgsForPlaceholders(*this, ArgExprs))
5418 if (getLangOpts().CPlusPlus) {
5419 // If this is a pseudo-destructor expression, build the call immediately.
5420 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5421 if (!ArgExprs.empty()) {
5422 // Pseudo-destructor calls should not have any arguments.
5423 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5424 << FixItHint::CreateRemoval(
5425 SourceRange(ArgExprs.front()->getBeginLoc(),
5426 ArgExprs.back()->getEndLoc()));
5429 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5430 VK_RValue, RParenLoc);
5432 if (Fn->getType() == Context.PseudoObjectTy) {
5433 ExprResult result = CheckPlaceholderExpr(Fn);
5434 if (result.isInvalid()) return ExprError();
5438 // Determine whether this is a dependent call inside a C++ template,
5439 // in which case we won't do any semantic analysis now.
5440 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5442 return CUDAKernelCallExpr::Create(
5443 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5444 Context.DependentTy, VK_RValue, RParenLoc);
5447 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5448 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5451 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5452 VK_RValue, RParenLoc);
5456 // Determine whether this is a call to an object (C++ [over.call.object]).
5457 if (Fn->getType()->isRecordType())
5458 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5461 if (Fn->getType() == Context.UnknownAnyTy) {
5462 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5463 if (result.isInvalid()) return ExprError();
5467 if (Fn->getType() == Context.BoundMemberTy) {
5468 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5473 // Check for overloaded calls. This can happen even in C due to extensions.
5474 if (Fn->getType() == Context.OverloadTy) {
5475 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5477 // We aren't supposed to apply this logic if there's an '&' involved.
5478 if (!find.HasFormOfMemberPointer) {
5479 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5480 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5481 VK_RValue, RParenLoc);
5482 OverloadExpr *ovl = find.Expression;
5483 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5484 return BuildOverloadedCallExpr(
5485 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5486 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5487 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5492 // If we're directly calling a function, get the appropriate declaration.
5493 if (Fn->getType() == Context.UnknownAnyTy) {
5494 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5495 if (result.isInvalid()) return ExprError();
5499 Expr *NakedFn = Fn->IgnoreParens();
5501 bool CallingNDeclIndirectly = false;
5502 NamedDecl *NDecl = nullptr;
5503 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5504 if (UnOp->getOpcode() == UO_AddrOf) {
5505 CallingNDeclIndirectly = true;
5506 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5510 if (isa<DeclRefExpr>(NakedFn)) {
5511 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5513 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5514 if (FDecl && FDecl->getBuiltinID()) {
5515 // Rewrite the function decl for this builtin by replacing parameters
5516 // with no explicit address space with the address space of the arguments
5519 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5521 Fn = DeclRefExpr::Create(
5522 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5523 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5526 } else if (isa<MemberExpr>(NakedFn))
5527 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5529 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5530 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5531 FD, /*Complain=*/true, Fn->getBeginLoc()))
5534 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5537 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5540 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5541 ExecConfig, IsExecConfig);
5544 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5546 /// __builtin_astype( value, dst type )
5548 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5549 SourceLocation BuiltinLoc,
5550 SourceLocation RParenLoc) {
5551 ExprValueKind VK = VK_RValue;
5552 ExprObjectKind OK = OK_Ordinary;
5553 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5554 QualType SrcTy = E->getType();
5555 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5556 return ExprError(Diag(BuiltinLoc,
5557 diag::err_invalid_astype_of_different_size)
5560 << E->getSourceRange());
5561 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5564 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5565 /// provided arguments.
5567 /// __builtin_convertvector( value, dst type )
5569 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5570 SourceLocation BuiltinLoc,
5571 SourceLocation RParenLoc) {
5572 TypeSourceInfo *TInfo;
5573 GetTypeFromParser(ParsedDestTy, &TInfo);
5574 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5577 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5578 /// i.e. an expression not of \p OverloadTy. The expression should
5579 /// unary-convert to an expression of function-pointer or
5580 /// block-pointer type.
5582 /// \param NDecl the declaration being called, if available
5583 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5584 SourceLocation LParenLoc,
5585 ArrayRef<Expr *> Args,
5586 SourceLocation RParenLoc, Expr *Config,
5587 bool IsExecConfig, ADLCallKind UsesADL) {
5588 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5589 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5591 // Functions with 'interrupt' attribute cannot be called directly.
5592 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5593 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5597 // Interrupt handlers don't save off the VFP regs automatically on ARM,
5598 // so there's some risk when calling out to non-interrupt handler functions
5599 // that the callee might not preserve them. This is easy to diagnose here,
5600 // but can be very challenging to debug.
5601 if (auto *Caller = getCurFunctionDecl())
5602 if (Caller->hasAttr<ARMInterruptAttr>()) {
5603 bool VFP = Context.getTargetInfo().hasFeature("vfp");
5604 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5605 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5608 // Promote the function operand.
5609 // We special-case function promotion here because we only allow promoting
5610 // builtin functions to function pointers in the callee of a call.
5614 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5615 // Extract the return type from the (builtin) function pointer type.
5616 // FIXME Several builtins still have setType in
5617 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5618 // Builtins.def to ensure they are correct before removing setType calls.
5619 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5620 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5621 ResultTy = FDecl->getCallResultType();
5623 Result = CallExprUnaryConversions(Fn);
5624 ResultTy = Context.BoolTy;
5626 if (Result.isInvalid())
5630 // Check for a valid function type, but only if it is not a builtin which
5631 // requires custom type checking. These will be handled by
5632 // CheckBuiltinFunctionCall below just after creation of the call expression.
5633 const FunctionType *FuncT = nullptr;
5634 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5636 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5637 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5638 // have type pointer to function".
5639 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5641 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5642 << Fn->getType() << Fn->getSourceRange());
5643 } else if (const BlockPointerType *BPT =
5644 Fn->getType()->getAs<BlockPointerType>()) {
5645 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5647 // Handle calls to expressions of unknown-any type.
5648 if (Fn->getType() == Context.UnknownAnyTy) {
5649 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5650 if (rewrite.isInvalid()) return ExprError();
5655 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5656 << Fn->getType() << Fn->getSourceRange());
5660 // Get the number of parameters in the function prototype, if any.
5661 // We will allocate space for max(Args.size(), NumParams) arguments
5662 // in the call expression.
5663 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5664 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5668 assert(UsesADL == ADLCallKind::NotADL &&
5669 "CUDAKernelCallExpr should not use ADL");
5671 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5672 ResultTy, VK_RValue, RParenLoc, NumParams);
5674 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5675 RParenLoc, NumParams, UsesADL);
5678 if (!getLangOpts().CPlusPlus) {
5679 // Forget about the nulled arguments since typo correction
5680 // do not handle them well.
5681 TheCall->shrinkNumArgs(Args.size());
5682 // C cannot always handle TypoExpr nodes in builtin calls and direct
5683 // function calls as their argument checking don't necessarily handle
5684 // dependent types properly, so make sure any TypoExprs have been
5686 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5687 if (!Result.isUsable()) return ExprError();
5688 CallExpr *TheOldCall = TheCall;
5689 TheCall = dyn_cast<CallExpr>(Result.get());
5690 bool CorrectedTypos = TheCall != TheOldCall;
5691 if (!TheCall) return Result;
5692 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5694 // A new call expression node was created if some typos were corrected.
5695 // However it may not have been constructed with enough storage. In this
5696 // case, rebuild the node with enough storage. The waste of space is
5697 // immaterial since this only happens when some typos were corrected.
5698 if (CorrectedTypos && Args.size() < NumParams) {
5700 TheCall = CUDAKernelCallExpr::Create(
5701 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5702 RParenLoc, NumParams);
5704 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5705 RParenLoc, NumParams, UsesADL);
5707 // We can now handle the nulled arguments for the default arguments.
5708 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5711 // Bail out early if calling a builtin with custom type checking.
5712 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5713 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5715 if (getLangOpts().CUDA) {
5717 // CUDA: Kernel calls must be to global functions
5718 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5719 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5720 << FDecl << Fn->getSourceRange());
5722 // CUDA: Kernel function must have 'void' return type
5723 if (!FuncT->getReturnType()->isVoidType())
5724 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5725 << Fn->getType() << Fn->getSourceRange());
5727 // CUDA: Calls to global functions must be configured
5728 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5729 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5730 << FDecl << Fn->getSourceRange());
5734 // Check for a valid return type
5735 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5739 // We know the result type of the call, set it.
5740 TheCall->setType(FuncT->getCallResultType(Context));
5741 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5744 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5748 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5751 // Check if we have too few/too many template arguments, based
5752 // on our knowledge of the function definition.
5753 const FunctionDecl *Def = nullptr;
5754 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5755 Proto = Def->getType()->getAs<FunctionProtoType>();
5756 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5757 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5758 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5761 // If the function we're calling isn't a function prototype, but we have
5762 // a function prototype from a prior declaratiom, use that prototype.
5763 if (!FDecl->hasPrototype())
5764 Proto = FDecl->getType()->getAs<FunctionProtoType>();
5767 // Promote the arguments (C99 6.5.2.2p6).
5768 for (unsigned i = 0, e = Args.size(); i != e; i++) {
5769 Expr *Arg = Args[i];
5771 if (Proto && i < Proto->getNumParams()) {
5772 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5773 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5775 PerformCopyInitialization(Entity, SourceLocation(), Arg);
5776 if (ArgE.isInvalid())
5779 Arg = ArgE.getAs<Expr>();
5782 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5784 if (ArgE.isInvalid())
5787 Arg = ArgE.getAs<Expr>();
5790 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5791 diag::err_call_incomplete_argument, Arg))
5794 TheCall->setArg(i, Arg);
5798 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5799 if (!Method->isStatic())
5800 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5801 << Fn->getSourceRange());
5803 // Check for sentinels
5805 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5807 // Do special checking on direct calls to functions.
5809 if (CheckFunctionCall(FDecl, TheCall, Proto))
5813 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5815 if (CheckPointerCall(NDecl, TheCall, Proto))
5818 if (CheckOtherCall(TheCall, Proto))
5822 return MaybeBindToTemporary(TheCall);
5826 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5827 SourceLocation RParenLoc, Expr *InitExpr) {
5828 assert(Ty && "ActOnCompoundLiteral(): missing type");
5829 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5831 TypeSourceInfo *TInfo;
5832 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5834 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5836 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5840 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5841 SourceLocation RParenLoc, Expr *LiteralExpr) {
5842 QualType literalType = TInfo->getType();
5844 if (literalType->isArrayType()) {
5845 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5846 diag::err_illegal_decl_array_incomplete_type,
5847 SourceRange(LParenLoc,
5848 LiteralExpr->getSourceRange().getEnd())))
5850 if (literalType->isVariableArrayType())
5851 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5852 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5853 } else if (!literalType->isDependentType() &&
5854 RequireCompleteType(LParenLoc, literalType,
5855 diag::err_typecheck_decl_incomplete_type,
5856 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5859 InitializedEntity Entity
5860 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5861 InitializationKind Kind
5862 = InitializationKind::CreateCStyleCast(LParenLoc,
5863 SourceRange(LParenLoc, RParenLoc),
5865 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5866 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5868 if (Result.isInvalid())
5870 LiteralExpr = Result.get();
5872 bool isFileScope = !CurContext->isFunctionOrMethod();
5874 // In C, compound literals are l-values for some reason.
5875 // For GCC compatibility, in C++, file-scope array compound literals with
5876 // constant initializers are also l-values, and compound literals are
5877 // otherwise prvalues.
5879 // (GCC also treats C++ list-initialized file-scope array prvalues with
5880 // constant initializers as l-values, but that's non-conforming, so we don't
5881 // follow it there.)
5883 // FIXME: It would be better to handle the lvalue cases as materializing and
5884 // lifetime-extending a temporary object, but our materialized temporaries
5885 // representation only supports lifetime extension from a variable, not "out
5887 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5888 // is bound to the result of applying array-to-pointer decay to the compound
5890 // FIXME: GCC supports compound literals of reference type, which should
5891 // obviously have a value kind derived from the kind of reference involved.
5893 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5898 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
5899 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
5900 Expr *Init = ILE->getInit(i);
5901 ILE->setInit(i, ConstantExpr::Create(Context, Init));
5904 Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5905 VK, LiteralExpr, isFileScope);
5907 if (!LiteralExpr->isTypeDependent() &&
5908 !LiteralExpr->isValueDependent() &&
5909 !literalType->isDependentType()) // C99 6.5.2.5p3
5910 if (CheckForConstantInitializer(LiteralExpr, literalType))
5912 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
5913 literalType.getAddressSpace() != LangAS::Default) {
5914 // Embedded-C extensions to C99 6.5.2.5:
5915 // "If the compound literal occurs inside the body of a function, the
5916 // type name shall not be qualified by an address-space qualifier."
5917 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
5918 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
5922 return MaybeBindToTemporary(E);
5926 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5927 SourceLocation RBraceLoc) {
5928 // Immediately handle non-overload placeholders. Overloads can be
5929 // resolved contextually, but everything else here can't.
5930 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5931 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5932 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5934 // Ignore failures; dropping the entire initializer list because
5935 // of one failure would be terrible for indexing/etc.
5936 if (result.isInvalid()) continue;
5938 InitArgList[I] = result.get();
5942 // Semantic analysis for initializers is done by ActOnDeclarator() and
5943 // CheckInitializer() - it requires knowledge of the object being initialized.
5945 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5947 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5951 /// Do an explicit extend of the given block pointer if we're in ARC.
5952 void Sema::maybeExtendBlockObject(ExprResult &E) {
5953 assert(E.get()->getType()->isBlockPointerType());
5954 assert(E.get()->isRValue());
5956 // Only do this in an r-value context.
5957 if (!getLangOpts().ObjCAutoRefCount) return;
5959 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5960 CK_ARCExtendBlockObject, E.get(),
5961 /*base path*/ nullptr, VK_RValue);
5962 Cleanup.setExprNeedsCleanups(true);
5965 /// Prepare a conversion of the given expression to an ObjC object
5967 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5968 QualType type = E.get()->getType();
5969 if (type->isObjCObjectPointerType()) {
5971 } else if (type->isBlockPointerType()) {
5972 maybeExtendBlockObject(E);
5973 return CK_BlockPointerToObjCPointerCast;
5975 assert(type->isPointerType());
5976 return CK_CPointerToObjCPointerCast;
5980 /// Prepares for a scalar cast, performing all the necessary stages
5981 /// except the final cast and returning the kind required.
5982 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5983 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5984 // Also, callers should have filtered out the invalid cases with
5985 // pointers. Everything else should be possible.
5987 QualType SrcTy = Src.get()->getType();
5988 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5991 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5992 case Type::STK_MemberPointer:
5993 llvm_unreachable("member pointer type in C");
5995 case Type::STK_CPointer:
5996 case Type::STK_BlockPointer:
5997 case Type::STK_ObjCObjectPointer:
5998 switch (DestTy->getScalarTypeKind()) {
5999 case Type::STK_CPointer: {
6000 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6001 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6002 if (SrcAS != DestAS)
6003 return CK_AddressSpaceConversion;
6004 if (Context.hasCvrSimilarType(SrcTy, DestTy))
6008 case Type::STK_BlockPointer:
6009 return (SrcKind == Type::STK_BlockPointer
6010 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6011 case Type::STK_ObjCObjectPointer:
6012 if (SrcKind == Type::STK_ObjCObjectPointer)
6014 if (SrcKind == Type::STK_CPointer)
6015 return CK_CPointerToObjCPointerCast;
6016 maybeExtendBlockObject(Src);
6017 return CK_BlockPointerToObjCPointerCast;
6018 case Type::STK_Bool:
6019 return CK_PointerToBoolean;
6020 case Type::STK_Integral:
6021 return CK_PointerToIntegral;
6022 case Type::STK_Floating:
6023 case Type::STK_FloatingComplex:
6024 case Type::STK_IntegralComplex:
6025 case Type::STK_MemberPointer:
6026 case Type::STK_FixedPoint:
6027 llvm_unreachable("illegal cast from pointer");
6029 llvm_unreachable("Should have returned before this");
6031 case Type::STK_FixedPoint:
6032 switch (DestTy->getScalarTypeKind()) {
6033 case Type::STK_FixedPoint:
6034 return CK_FixedPointCast;
6035 case Type::STK_Bool:
6036 return CK_FixedPointToBoolean;
6037 case Type::STK_Integral:
6038 case Type::STK_Floating:
6039 case Type::STK_IntegralComplex:
6040 case Type::STK_FloatingComplex:
6041 Diag(Src.get()->getExprLoc(),
6042 diag::err_unimplemented_conversion_with_fixed_point_type)
6044 return CK_IntegralCast;
6045 case Type::STK_CPointer:
6046 case Type::STK_ObjCObjectPointer:
6047 case Type::STK_BlockPointer:
6048 case Type::STK_MemberPointer:
6049 llvm_unreachable("illegal cast to pointer type");
6051 llvm_unreachable("Should have returned before this");
6053 case Type::STK_Bool: // casting from bool is like casting from an integer
6054 case Type::STK_Integral:
6055 switch (DestTy->getScalarTypeKind()) {
6056 case Type::STK_CPointer:
6057 case Type::STK_ObjCObjectPointer:
6058 case Type::STK_BlockPointer:
6059 if (Src.get()->isNullPointerConstant(Context,
6060 Expr::NPC_ValueDependentIsNull))
6061 return CK_NullToPointer;
6062 return CK_IntegralToPointer;
6063 case Type::STK_Bool:
6064 return CK_IntegralToBoolean;
6065 case Type::STK_Integral:
6066 return CK_IntegralCast;
6067 case Type::STK_Floating:
6068 return CK_IntegralToFloating;
6069 case Type::STK_IntegralComplex:
6070 Src = ImpCastExprToType(Src.get(),
6071 DestTy->castAs<ComplexType>()->getElementType(),
6073 return CK_IntegralRealToComplex;
6074 case Type::STK_FloatingComplex:
6075 Src = ImpCastExprToType(Src.get(),
6076 DestTy->castAs<ComplexType>()->getElementType(),
6077 CK_IntegralToFloating);
6078 return CK_FloatingRealToComplex;
6079 case Type::STK_MemberPointer:
6080 llvm_unreachable("member pointer type in C");
6081 case Type::STK_FixedPoint:
6082 Diag(Src.get()->getExprLoc(),
6083 diag::err_unimplemented_conversion_with_fixed_point_type)
6085 return CK_IntegralCast;
6087 llvm_unreachable("Should have returned before this");
6089 case Type::STK_Floating:
6090 switch (DestTy->getScalarTypeKind()) {
6091 case Type::STK_Floating:
6092 return CK_FloatingCast;
6093 case Type::STK_Bool:
6094 return CK_FloatingToBoolean;
6095 case Type::STK_Integral:
6096 return CK_FloatingToIntegral;
6097 case Type::STK_FloatingComplex:
6098 Src = ImpCastExprToType(Src.get(),
6099 DestTy->castAs<ComplexType>()->getElementType(),
6101 return CK_FloatingRealToComplex;
6102 case Type::STK_IntegralComplex:
6103 Src = ImpCastExprToType(Src.get(),
6104 DestTy->castAs<ComplexType>()->getElementType(),
6105 CK_FloatingToIntegral);
6106 return CK_IntegralRealToComplex;
6107 case Type::STK_CPointer:
6108 case Type::STK_ObjCObjectPointer:
6109 case Type::STK_BlockPointer:
6110 llvm_unreachable("valid float->pointer cast?");
6111 case Type::STK_MemberPointer:
6112 llvm_unreachable("member pointer type in C");
6113 case Type::STK_FixedPoint:
6114 Diag(Src.get()->getExprLoc(),
6115 diag::err_unimplemented_conversion_with_fixed_point_type)
6117 return CK_IntegralCast;
6119 llvm_unreachable("Should have returned before this");
6121 case Type::STK_FloatingComplex:
6122 switch (DestTy->getScalarTypeKind()) {
6123 case Type::STK_FloatingComplex:
6124 return CK_FloatingComplexCast;
6125 case Type::STK_IntegralComplex:
6126 return CK_FloatingComplexToIntegralComplex;
6127 case Type::STK_Floating: {
6128 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6129 if (Context.hasSameType(ET, DestTy))
6130 return CK_FloatingComplexToReal;
6131 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6132 return CK_FloatingCast;
6134 case Type::STK_Bool:
6135 return CK_FloatingComplexToBoolean;
6136 case Type::STK_Integral:
6137 Src = ImpCastExprToType(Src.get(),
6138 SrcTy->castAs<ComplexType>()->getElementType(),
6139 CK_FloatingComplexToReal);
6140 return CK_FloatingToIntegral;
6141 case Type::STK_CPointer:
6142 case Type::STK_ObjCObjectPointer:
6143 case Type::STK_BlockPointer:
6144 llvm_unreachable("valid complex float->pointer cast?");
6145 case Type::STK_MemberPointer:
6146 llvm_unreachable("member pointer type in C");
6147 case Type::STK_FixedPoint:
6148 Diag(Src.get()->getExprLoc(),
6149 diag::err_unimplemented_conversion_with_fixed_point_type)
6151 return CK_IntegralCast;
6153 llvm_unreachable("Should have returned before this");
6155 case Type::STK_IntegralComplex:
6156 switch (DestTy->getScalarTypeKind()) {
6157 case Type::STK_FloatingComplex:
6158 return CK_IntegralComplexToFloatingComplex;
6159 case Type::STK_IntegralComplex:
6160 return CK_IntegralComplexCast;
6161 case Type::STK_Integral: {
6162 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6163 if (Context.hasSameType(ET, DestTy))
6164 return CK_IntegralComplexToReal;
6165 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6166 return CK_IntegralCast;
6168 case Type::STK_Bool:
6169 return CK_IntegralComplexToBoolean;
6170 case Type::STK_Floating:
6171 Src = ImpCastExprToType(Src.get(),
6172 SrcTy->castAs<ComplexType>()->getElementType(),
6173 CK_IntegralComplexToReal);
6174 return CK_IntegralToFloating;
6175 case Type::STK_CPointer:
6176 case Type::STK_ObjCObjectPointer:
6177 case Type::STK_BlockPointer:
6178 llvm_unreachable("valid complex int->pointer cast?");
6179 case Type::STK_MemberPointer:
6180 llvm_unreachable("member pointer type in C");
6181 case Type::STK_FixedPoint:
6182 Diag(Src.get()->getExprLoc(),
6183 diag::err_unimplemented_conversion_with_fixed_point_type)
6185 return CK_IntegralCast;
6187 llvm_unreachable("Should have returned before this");
6190 llvm_unreachable("Unhandled scalar cast");
6193 static bool breakDownVectorType(QualType type, uint64_t &len,
6194 QualType &eltType) {
6195 // Vectors are simple.
6196 if (const VectorType *vecType = type->getAs<VectorType>()) {
6197 len = vecType->getNumElements();
6198 eltType = vecType->getElementType();
6199 assert(eltType->isScalarType());
6203 // We allow lax conversion to and from non-vector types, but only if
6204 // they're real types (i.e. non-complex, non-pointer scalar types).
6205 if (!type->isRealType()) return false;
6212 /// Are the two types lax-compatible vector types? That is, given
6213 /// that one of them is a vector, do they have equal storage sizes,
6214 /// where the storage size is the number of elements times the element
6217 /// This will also return false if either of the types is neither a
6218 /// vector nor a real type.
6219 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6220 assert(destTy->isVectorType() || srcTy->isVectorType());
6222 // Disallow lax conversions between scalars and ExtVectors (these
6223 // conversions are allowed for other vector types because common headers
6224 // depend on them). Most scalar OP ExtVector cases are handled by the
6225 // splat path anyway, which does what we want (convert, not bitcast).
6226 // What this rules out for ExtVectors is crazy things like char4*float.
6227 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6228 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6230 uint64_t srcLen, destLen;
6231 QualType srcEltTy, destEltTy;
6232 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6233 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6235 // ASTContext::getTypeSize will return the size rounded up to a
6236 // power of 2, so instead of using that, we need to use the raw
6237 // element size multiplied by the element count.
6238 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6239 uint64_t destEltSize = Context.getTypeSize(destEltTy);
6241 return (srcLen * srcEltSize == destLen * destEltSize);
6244 /// Is this a legal conversion between two types, one of which is
6245 /// known to be a vector type?
6246 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6247 assert(destTy->isVectorType() || srcTy->isVectorType());
6249 if (!Context.getLangOpts().LaxVectorConversions)
6251 return areLaxCompatibleVectorTypes(srcTy, destTy);
6254 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6256 assert(VectorTy->isVectorType() && "Not a vector type!");
6258 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6259 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6260 return Diag(R.getBegin(),
6261 Ty->isVectorType() ?
6262 diag::err_invalid_conversion_between_vectors :
6263 diag::err_invalid_conversion_between_vector_and_integer)
6264 << VectorTy << Ty << R;
6266 return Diag(R.getBegin(),
6267 diag::err_invalid_conversion_between_vector_and_scalar)
6268 << VectorTy << Ty << R;
6274 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6275 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6277 if (DestElemTy == SplattedExpr->getType())
6278 return SplattedExpr;
6280 assert(DestElemTy->isFloatingType() ||
6281 DestElemTy->isIntegralOrEnumerationType());
6284 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6285 // OpenCL requires that we convert `true` boolean expressions to -1, but
6286 // only when splatting vectors.
6287 if (DestElemTy->isFloatingType()) {
6288 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6289 // in two steps: boolean to signed integral, then to floating.
6290 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6291 CK_BooleanToSignedIntegral);
6292 SplattedExpr = CastExprRes.get();
6293 CK = CK_IntegralToFloating;
6295 CK = CK_BooleanToSignedIntegral;
6298 ExprResult CastExprRes = SplattedExpr;
6299 CK = PrepareScalarCast(CastExprRes, DestElemTy);
6300 if (CastExprRes.isInvalid())
6302 SplattedExpr = CastExprRes.get();
6304 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6307 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6308 Expr *CastExpr, CastKind &Kind) {
6309 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6311 QualType SrcTy = CastExpr->getType();
6313 // If SrcTy is a VectorType, the total size must match to explicitly cast to
6314 // an ExtVectorType.
6315 // In OpenCL, casts between vectors of different types are not allowed.
6316 // (See OpenCL 6.2).
6317 if (SrcTy->isVectorType()) {
6318 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6319 (getLangOpts().OpenCL &&
6320 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6321 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6322 << DestTy << SrcTy << R;
6329 // All non-pointer scalars can be cast to ExtVector type. The appropriate
6330 // conversion will take place first from scalar to elt type, and then
6331 // splat from elt type to vector.
6332 if (SrcTy->isPointerType())
6333 return Diag(R.getBegin(),
6334 diag::err_invalid_conversion_between_vector_and_scalar)
6335 << DestTy << SrcTy << R;
6337 Kind = CK_VectorSplat;
6338 return prepareVectorSplat(DestTy, CastExpr);
6342 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6343 Declarator &D, ParsedType &Ty,
6344 SourceLocation RParenLoc, Expr *CastExpr) {
6345 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6346 "ActOnCastExpr(): missing type or expr");
6348 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6349 if (D.isInvalidType())
6352 if (getLangOpts().CPlusPlus) {
6353 // Check that there are no default arguments (C++ only).
6354 CheckExtraCXXDefaultArguments(D);
6356 // Make sure any TypoExprs have been dealt with.
6357 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6358 if (!Res.isUsable())
6360 CastExpr = Res.get();
6363 checkUnusedDeclAttributes(D);
6365 QualType castType = castTInfo->getType();
6366 Ty = CreateParsedType(castType, castTInfo);
6368 bool isVectorLiteral = false;
6370 // Check for an altivec or OpenCL literal,
6371 // i.e. all the elements are integer constants.
6372 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6373 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6374 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6375 && castType->isVectorType() && (PE || PLE)) {
6376 if (PLE && PLE->getNumExprs() == 0) {
6377 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6380 if (PE || PLE->getNumExprs() == 1) {
6381 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6382 if (!E->getType()->isVectorType())
6383 isVectorLiteral = true;
6386 isVectorLiteral = true;
6389 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6390 // then handle it as such.
6391 if (isVectorLiteral)
6392 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6394 // If the Expr being casted is a ParenListExpr, handle it specially.
6395 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6396 // sequence of BinOp comma operators.
6397 if (isa<ParenListExpr>(CastExpr)) {
6398 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6399 if (Result.isInvalid()) return ExprError();
6400 CastExpr = Result.get();
6403 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6404 !getSourceManager().isInSystemMacro(LParenLoc))
6405 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6407 CheckTollFreeBridgeCast(castType, CastExpr);
6409 CheckObjCBridgeRelatedCast(castType, CastExpr);
6411 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6413 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6416 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6417 SourceLocation RParenLoc, Expr *E,
6418 TypeSourceInfo *TInfo) {
6419 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6420 "Expected paren or paren list expression");
6425 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6426 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6427 LiteralLParenLoc = PE->getLParenLoc();
6428 LiteralRParenLoc = PE->getRParenLoc();
6429 exprs = PE->getExprs();
6430 numExprs = PE->getNumExprs();
6431 } else { // isa<ParenExpr> by assertion at function entrance
6432 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6433 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6434 subExpr = cast<ParenExpr>(E)->getSubExpr();
6439 QualType Ty = TInfo->getType();
6440 assert(Ty->isVectorType() && "Expected vector type");
6442 SmallVector<Expr *, 8> initExprs;
6443 const VectorType *VTy = Ty->getAs<VectorType>();
6444 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6446 // '(...)' form of vector initialization in AltiVec: the number of
6447 // initializers must be one or must match the size of the vector.
6448 // If a single value is specified in the initializer then it will be
6449 // replicated to all the components of the vector
6450 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6451 // The number of initializers must be one or must match the size of the
6452 // vector. If a single value is specified in the initializer then it will
6453 // be replicated to all the components of the vector
6454 if (numExprs == 1) {
6455 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6456 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6457 if (Literal.isInvalid())
6459 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6460 PrepareScalarCast(Literal, ElemTy));
6461 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6463 else if (numExprs < numElems) {
6464 Diag(E->getExprLoc(),
6465 diag::err_incorrect_number_of_vector_initializers);
6469 initExprs.append(exprs, exprs + numExprs);
6472 // For OpenCL, when the number of initializers is a single value,
6473 // it will be replicated to all components of the vector.
6474 if (getLangOpts().OpenCL &&
6475 VTy->getVectorKind() == VectorType::GenericVector &&
6477 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6478 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6479 if (Literal.isInvalid())
6481 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6482 PrepareScalarCast(Literal, ElemTy));
6483 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6486 initExprs.append(exprs, exprs + numExprs);
6488 // FIXME: This means that pretty-printing the final AST will produce curly
6489 // braces instead of the original commas.
6490 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6491 initExprs, LiteralRParenLoc);
6493 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6496 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6497 /// the ParenListExpr into a sequence of comma binary operators.
6499 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6500 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6504 ExprResult Result(E->getExpr(0));
6506 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6507 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6510 if (Result.isInvalid()) return ExprError();
6512 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6515 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6518 return ParenListExpr::Create(Context, L, Val, R);
6521 /// Emit a specialized diagnostic when one expression is a null pointer
6522 /// constant and the other is not a pointer. Returns true if a diagnostic is
6524 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6525 SourceLocation QuestionLoc) {
6526 Expr *NullExpr = LHSExpr;
6527 Expr *NonPointerExpr = RHSExpr;
6528 Expr::NullPointerConstantKind NullKind =
6529 NullExpr->isNullPointerConstant(Context,
6530 Expr::NPC_ValueDependentIsNotNull);
6532 if (NullKind == Expr::NPCK_NotNull) {
6534 NonPointerExpr = LHSExpr;
6536 NullExpr->isNullPointerConstant(Context,
6537 Expr::NPC_ValueDependentIsNotNull);
6540 if (NullKind == Expr::NPCK_NotNull)
6543 if (NullKind == Expr::NPCK_ZeroExpression)
6546 if (NullKind == Expr::NPCK_ZeroLiteral) {
6547 // In this case, check to make sure that we got here from a "NULL"
6548 // string in the source code.
6549 NullExpr = NullExpr->IgnoreParenImpCasts();
6550 SourceLocation loc = NullExpr->getExprLoc();
6551 if (!findMacroSpelling(loc, "NULL"))
6555 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6556 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6557 << NonPointerExpr->getType() << DiagType
6558 << NonPointerExpr->getSourceRange();
6562 /// Return false if the condition expression is valid, true otherwise.
6563 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6564 QualType CondTy = Cond->getType();
6566 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6567 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6568 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6569 << CondTy << Cond->getSourceRange();
6574 if (CondTy->isScalarType()) return false;
6576 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6577 << CondTy << Cond->getSourceRange();
6581 /// Handle when one or both operands are void type.
6582 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6584 Expr *LHSExpr = LHS.get();
6585 Expr *RHSExpr = RHS.get();
6587 if (!LHSExpr->getType()->isVoidType())
6588 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6589 << RHSExpr->getSourceRange();
6590 if (!RHSExpr->getType()->isVoidType())
6591 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6592 << LHSExpr->getSourceRange();
6593 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6594 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6595 return S.Context.VoidTy;
6598 /// Return false if the NullExpr can be promoted to PointerTy,
6600 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6601 QualType PointerTy) {
6602 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6603 !NullExpr.get()->isNullPointerConstant(S.Context,
6604 Expr::NPC_ValueDependentIsNull))
6607 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6611 /// Checks compatibility between two pointers and return the resulting
6613 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6615 SourceLocation Loc) {
6616 QualType LHSTy = LHS.get()->getType();
6617 QualType RHSTy = RHS.get()->getType();
6619 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6620 // Two identical pointers types are always compatible.
6624 QualType lhptee, rhptee;
6626 // Get the pointee types.
6627 bool IsBlockPointer = false;
6628 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6629 lhptee = LHSBTy->getPointeeType();
6630 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6631 IsBlockPointer = true;
6633 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6634 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6637 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6638 // differently qualified versions of compatible types, the result type is
6639 // a pointer to an appropriately qualified version of the composite
6642 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6643 // clause doesn't make sense for our extensions. E.g. address space 2 should
6644 // be incompatible with address space 3: they may live on different devices or
6646 Qualifiers lhQual = lhptee.getQualifiers();
6647 Qualifiers rhQual = rhptee.getQualifiers();
6649 LangAS ResultAddrSpace = LangAS::Default;
6650 LangAS LAddrSpace = lhQual.getAddressSpace();
6651 LangAS RAddrSpace = rhQual.getAddressSpace();
6653 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6654 // spaces is disallowed.
6655 if (lhQual.isAddressSpaceSupersetOf(rhQual))
6656 ResultAddrSpace = LAddrSpace;
6657 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6658 ResultAddrSpace = RAddrSpace;
6660 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6661 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6662 << RHS.get()->getSourceRange();
6666 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6667 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6668 lhQual.removeCVRQualifiers();
6669 rhQual.removeCVRQualifiers();
6671 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6672 // (C99 6.7.3) for address spaces. We assume that the check should behave in
6673 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6674 // qual types are compatible iff
6675 // * corresponded types are compatible
6676 // * CVR qualifiers are equal
6677 // * address spaces are equal
6678 // Thus for conditional operator we merge CVR and address space unqualified
6679 // pointees and if there is a composite type we return a pointer to it with
6680 // merged qualifiers.
6682 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6684 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6685 lhQual.removeAddressSpace();
6686 rhQual.removeAddressSpace();
6688 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6689 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6691 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6693 if (CompositeTy.isNull()) {
6694 // In this situation, we assume void* type. No especially good
6695 // reason, but this is what gcc does, and we do have to pick
6696 // to get a consistent AST.
6697 QualType incompatTy;
6698 incompatTy = S.Context.getPointerType(
6699 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6700 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6701 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6703 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6704 // for casts between types with incompatible address space qualifiers.
6705 // For the following code the compiler produces casts between global and
6706 // local address spaces of the corresponded innermost pointees:
6707 // local int *global *a;
6708 // global int *global *b;
6709 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6710 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6711 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6712 << RHS.get()->getSourceRange();
6717 // The pointer types are compatible.
6718 // In case of OpenCL ResultTy should have the address space qualifier
6719 // which is a superset of address spaces of both the 2nd and the 3rd
6720 // operands of the conditional operator.
6721 QualType ResultTy = [&, ResultAddrSpace]() {
6722 if (S.getLangOpts().OpenCL) {
6723 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6724 CompositeQuals.setAddressSpace(ResultAddrSpace);
6726 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6727 .withCVRQualifiers(MergedCVRQual);
6729 return CompositeTy.withCVRQualifiers(MergedCVRQual);
6732 ResultTy = S.Context.getBlockPointerType(ResultTy);
6734 ResultTy = S.Context.getPointerType(ResultTy);
6736 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6737 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6741 /// Return the resulting type when the operands are both block pointers.
6742 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6745 SourceLocation Loc) {
6746 QualType LHSTy = LHS.get()->getType();
6747 QualType RHSTy = RHS.get()->getType();
6749 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6750 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6751 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6752 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6753 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6756 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6757 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6758 << RHS.get()->getSourceRange();
6762 // We have 2 block pointer types.
6763 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6766 /// Return the resulting type when the operands are both pointers.
6768 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6770 SourceLocation Loc) {
6771 // get the pointer types
6772 QualType LHSTy = LHS.get()->getType();
6773 QualType RHSTy = RHS.get()->getType();
6775 // get the "pointed to" types
6776 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6777 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6779 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6780 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6781 // Figure out necessary qualifiers (C99 6.5.15p6)
6782 QualType destPointee
6783 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6784 QualType destType = S.Context.getPointerType(destPointee);
6785 // Add qualifiers if necessary.
6786 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6787 // Promote to void*.
6788 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6791 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6792 QualType destPointee
6793 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6794 QualType destType = S.Context.getPointerType(destPointee);
6795 // Add qualifiers if necessary.
6796 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6797 // Promote to void*.
6798 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6802 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6805 /// Return false if the first expression is not an integer and the second
6806 /// expression is not a pointer, true otherwise.
6807 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6808 Expr* PointerExpr, SourceLocation Loc,
6809 bool IsIntFirstExpr) {
6810 if (!PointerExpr->getType()->isPointerType() ||
6811 !Int.get()->getType()->isIntegerType())
6814 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6815 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6817 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6818 << Expr1->getType() << Expr2->getType()
6819 << Expr1->getSourceRange() << Expr2->getSourceRange();
6820 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6821 CK_IntegralToPointer);
6825 /// Simple conversion between integer and floating point types.
6827 /// Used when handling the OpenCL conditional operator where the
6828 /// condition is a vector while the other operands are scalar.
6830 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6831 /// types are either integer or floating type. Between the two
6832 /// operands, the type with the higher rank is defined as the "result
6833 /// type". The other operand needs to be promoted to the same type. No
6834 /// other type promotion is allowed. We cannot use
6835 /// UsualArithmeticConversions() for this purpose, since it always
6836 /// promotes promotable types.
6837 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6839 SourceLocation QuestionLoc) {
6840 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6841 if (LHS.isInvalid())
6843 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6844 if (RHS.isInvalid())
6847 // For conversion purposes, we ignore any qualifiers.
6848 // For example, "const float" and "float" are equivalent.
6850 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6852 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6854 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6855 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6856 << LHSType << LHS.get()->getSourceRange();
6860 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6861 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6862 << RHSType << RHS.get()->getSourceRange();
6866 // If both types are identical, no conversion is needed.
6867 if (LHSType == RHSType)
6870 // Now handle "real" floating types (i.e. float, double, long double).
6871 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6872 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6873 /*IsCompAssign = */ false);
6875 // Finally, we have two differing integer types.
6876 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6877 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6880 /// Convert scalar operands to a vector that matches the
6881 /// condition in length.
6883 /// Used when handling the OpenCL conditional operator where the
6884 /// condition is a vector while the other operands are scalar.
6886 /// We first compute the "result type" for the scalar operands
6887 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6888 /// into a vector of that type where the length matches the condition
6889 /// vector type. s6.11.6 requires that the element types of the result
6890 /// and the condition must have the same number of bits.
6892 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6893 QualType CondTy, SourceLocation QuestionLoc) {
6894 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6895 if (ResTy.isNull()) return QualType();
6897 const VectorType *CV = CondTy->getAs<VectorType>();
6900 // Determine the vector result type
6901 unsigned NumElements = CV->getNumElements();
6902 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6904 // Ensure that all types have the same number of bits
6905 if (S.Context.getTypeSize(CV->getElementType())
6906 != S.Context.getTypeSize(ResTy)) {
6907 // Since VectorTy is created internally, it does not pretty print
6908 // with an OpenCL name. Instead, we just print a description.
6909 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6910 SmallString<64> Str;
6911 llvm::raw_svector_ostream OS(Str);
6912 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6913 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6914 << CondTy << OS.str();
6918 // Convert operands to the vector result type
6919 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6920 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6925 /// Return false if this is a valid OpenCL condition vector
6926 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6927 SourceLocation QuestionLoc) {
6928 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6930 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6932 QualType EleTy = CondTy->getElementType();
6933 if (EleTy->isIntegerType()) return false;
6935 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6936 << Cond->getType() << Cond->getSourceRange();
6940 /// Return false if the vector condition type and the vector
6941 /// result type are compatible.
6943 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6944 /// number of elements, and their element types have the same number
6946 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6947 SourceLocation QuestionLoc) {
6948 const VectorType *CV = CondTy->getAs<VectorType>();
6949 const VectorType *RV = VecResTy->getAs<VectorType>();
6952 if (CV->getNumElements() != RV->getNumElements()) {
6953 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6954 << CondTy << VecResTy;
6958 QualType CVE = CV->getElementType();
6959 QualType RVE = RV->getElementType();
6961 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6962 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6963 << CondTy << VecResTy;
6970 /// Return the resulting type for the conditional operator in
6971 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6972 /// s6.3.i) when the condition is a vector type.
6974 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6975 ExprResult &LHS, ExprResult &RHS,
6976 SourceLocation QuestionLoc) {
6977 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6978 if (Cond.isInvalid())
6980 QualType CondTy = Cond.get()->getType();
6982 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6985 // If either operand is a vector then find the vector type of the
6986 // result as specified in OpenCL v1.1 s6.3.i.
6987 if (LHS.get()->getType()->isVectorType() ||
6988 RHS.get()->getType()->isVectorType()) {
6989 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6990 /*isCompAssign*/false,
6991 /*AllowBothBool*/true,
6992 /*AllowBoolConversions*/false);
6993 if (VecResTy.isNull()) return QualType();
6994 // The result type must match the condition type as specified in
6995 // OpenCL v1.1 s6.11.6.
6996 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7001 // Both operands are scalar.
7002 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7005 /// Return true if the Expr is block type
7006 static bool checkBlockType(Sema &S, const Expr *E) {
7007 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7008 QualType Ty = CE->getCallee()->getType();
7009 if (Ty->isBlockPointerType()) {
7010 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7017 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7018 /// In that case, LHS = cond.
7020 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7021 ExprResult &RHS, ExprValueKind &VK,
7023 SourceLocation QuestionLoc) {
7025 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7026 if (!LHSResult.isUsable()) return QualType();
7029 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7030 if (!RHSResult.isUsable()) return QualType();
7033 // C++ is sufficiently different to merit its own checker.
7034 if (getLangOpts().CPlusPlus)
7035 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7040 // The OpenCL operator with a vector condition is sufficiently
7041 // different to merit its own checker.
7042 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7043 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7045 // First, check the condition.
7046 Cond = UsualUnaryConversions(Cond.get());
7047 if (Cond.isInvalid())
7049 if (checkCondition(*this, Cond.get(), QuestionLoc))
7052 // Now check the two expressions.
7053 if (LHS.get()->getType()->isVectorType() ||
7054 RHS.get()->getType()->isVectorType())
7055 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7056 /*AllowBothBool*/true,
7057 /*AllowBoolConversions*/false);
7059 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7060 if (LHS.isInvalid() || RHS.isInvalid())
7063 QualType LHSTy = LHS.get()->getType();
7064 QualType RHSTy = RHS.get()->getType();
7066 // Diagnose attempts to convert between __float128 and long double where
7067 // such conversions currently can't be handled.
7068 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7070 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7071 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7075 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7076 // selection operator (?:).
7077 if (getLangOpts().OpenCL &&
7078 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7082 // If both operands have arithmetic type, do the usual arithmetic conversions
7083 // to find a common type: C99 6.5.15p3,5.
7084 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7085 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7086 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7091 // If both operands are the same structure or union type, the result is that
7093 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
7094 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7095 if (LHSRT->getDecl() == RHSRT->getDecl())
7096 // "If both the operands have structure or union type, the result has
7097 // that type." This implies that CV qualifiers are dropped.
7098 return LHSTy.getUnqualifiedType();
7099 // FIXME: Type of conditional expression must be complete in C mode.
7102 // C99 6.5.15p5: "If both operands have void type, the result has void type."
7103 // The following || allows only one side to be void (a GCC-ism).
7104 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7105 return checkConditionalVoidType(*this, LHS, RHS);
7108 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7109 // the type of the other operand."
7110 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7111 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7113 // All objective-c pointer type analysis is done here.
7114 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7116 if (LHS.isInvalid() || RHS.isInvalid())
7118 if (!compositeType.isNull())
7119 return compositeType;
7122 // Handle block pointer types.
7123 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7124 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7127 // Check constraints for C object pointers types (C99 6.5.15p3,6).
7128 if (LHSTy->isPointerType() && RHSTy->isPointerType())
7129 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7132 // GCC compatibility: soften pointer/integer mismatch. Note that
7133 // null pointers have been filtered out by this point.
7134 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7135 /*isIntFirstExpr=*/true))
7137 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7138 /*isIntFirstExpr=*/false))
7141 // Emit a better diagnostic if one of the expressions is a null pointer
7142 // constant and the other is not a pointer type. In this case, the user most
7143 // likely forgot to take the address of the other expression.
7144 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7147 // Otherwise, the operands are not compatible.
7148 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7149 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7150 << RHS.get()->getSourceRange();
7154 /// FindCompositeObjCPointerType - Helper method to find composite type of
7155 /// two objective-c pointer types of the two input expressions.
7156 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7157 SourceLocation QuestionLoc) {
7158 QualType LHSTy = LHS.get()->getType();
7159 QualType RHSTy = RHS.get()->getType();
7161 // Handle things like Class and struct objc_class*. Here we case the result
7162 // to the pseudo-builtin, because that will be implicitly cast back to the
7163 // redefinition type if an attempt is made to access its fields.
7164 if (LHSTy->isObjCClassType() &&
7165 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7166 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7169 if (RHSTy->isObjCClassType() &&
7170 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7171 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7174 // And the same for struct objc_object* / id
7175 if (LHSTy->isObjCIdType() &&
7176 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7177 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7180 if (RHSTy->isObjCIdType() &&
7181 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7182 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7185 // And the same for struct objc_selector* / SEL
7186 if (Context.isObjCSelType(LHSTy) &&
7187 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7188 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7191 if (Context.isObjCSelType(RHSTy) &&
7192 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7193 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7196 // Check constraints for Objective-C object pointers types.
7197 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7199 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7200 // Two identical object pointer types are always compatible.
7203 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7204 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7205 QualType compositeType = LHSTy;
7207 // If both operands are interfaces and either operand can be
7208 // assigned to the other, use that type as the composite
7209 // type. This allows
7210 // xxx ? (A*) a : (B*) b
7211 // where B is a subclass of A.
7213 // Additionally, as for assignment, if either type is 'id'
7214 // allow silent coercion. Finally, if the types are
7215 // incompatible then make sure to use 'id' as the composite
7216 // type so the result is acceptable for sending messages to.
7218 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7219 // It could return the composite type.
7220 if (!(compositeType =
7221 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7222 // Nothing more to do.
7223 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7224 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7225 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7226 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7227 } else if ((LHSTy->isObjCQualifiedIdType() ||
7228 RHSTy->isObjCQualifiedIdType()) &&
7229 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7230 // Need to handle "id<xx>" explicitly.
7231 // GCC allows qualified id and any Objective-C type to devolve to
7232 // id. Currently localizing to here until clear this should be
7233 // part of ObjCQualifiedIdTypesAreCompatible.
7234 compositeType = Context.getObjCIdType();
7235 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7236 compositeType = Context.getObjCIdType();
7238 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7240 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7241 QualType incompatTy = Context.getObjCIdType();
7242 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7243 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7246 // The object pointer types are compatible.
7247 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7248 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7249 return compositeType;
7251 // Check Objective-C object pointer types and 'void *'
7252 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7253 if (getLangOpts().ObjCAutoRefCount) {
7254 // ARC forbids the implicit conversion of object pointers to 'void *',
7255 // so these types are not compatible.
7256 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7257 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7261 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7262 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7263 QualType destPointee
7264 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7265 QualType destType = Context.getPointerType(destPointee);
7266 // Add qualifiers if necessary.
7267 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7268 // Promote to void*.
7269 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7272 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7273 if (getLangOpts().ObjCAutoRefCount) {
7274 // ARC forbids the implicit conversion of object pointers to 'void *',
7275 // so these types are not compatible.
7276 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7277 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7281 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7282 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7283 QualType destPointee
7284 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7285 QualType destType = Context.getPointerType(destPointee);
7286 // Add qualifiers if necessary.
7287 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7288 // Promote to void*.
7289 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7295 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7296 /// ParenRange in parentheses.
7297 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7298 const PartialDiagnostic &Note,
7299 SourceRange ParenRange) {
7300 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7301 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7303 Self.Diag(Loc, Note)
7304 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7305 << FixItHint::CreateInsertion(EndLoc, ")");
7307 // We can't display the parentheses, so just show the bare note.
7308 Self.Diag(Loc, Note) << ParenRange;
7312 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7313 return BinaryOperator::isAdditiveOp(Opc) ||
7314 BinaryOperator::isMultiplicativeOp(Opc) ||
7315 BinaryOperator::isShiftOp(Opc);
7318 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7319 /// expression, either using a built-in or overloaded operator,
7320 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7322 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7324 // Don't strip parenthesis: we should not warn if E is in parenthesis.
7325 E = E->IgnoreImpCasts();
7326 E = E->IgnoreConversionOperator();
7327 E = E->IgnoreImpCasts();
7328 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7329 E = MTE->GetTemporaryExpr();
7330 E = E->IgnoreImpCasts();
7333 // Built-in binary operator.
7334 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7335 if (IsArithmeticOp(OP->getOpcode())) {
7336 *Opcode = OP->getOpcode();
7337 *RHSExprs = OP->getRHS();
7342 // Overloaded operator.
7343 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7344 if (Call->getNumArgs() != 2)
7347 // Make sure this is really a binary operator that is safe to pass into
7348 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7349 OverloadedOperatorKind OO = Call->getOperator();
7350 if (OO < OO_Plus || OO > OO_Arrow ||
7351 OO == OO_PlusPlus || OO == OO_MinusMinus)
7354 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7355 if (IsArithmeticOp(OpKind)) {
7357 *RHSExprs = Call->getArg(1);
7365 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7366 /// or is a logical expression such as (x==y) which has int type, but is
7367 /// commonly interpreted as boolean.
7368 static bool ExprLooksBoolean(Expr *E) {
7369 E = E->IgnoreParenImpCasts();
7371 if (E->getType()->isBooleanType())
7373 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7374 return OP->isComparisonOp() || OP->isLogicalOp();
7375 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7376 return OP->getOpcode() == UO_LNot;
7377 if (E->getType()->isPointerType())
7379 // FIXME: What about overloaded operator calls returning "unspecified boolean
7380 // type"s (commonly pointer-to-members)?
7385 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7386 /// and binary operator are mixed in a way that suggests the programmer assumed
7387 /// the conditional operator has higher precedence, for example:
7388 /// "int x = a + someBinaryCondition ? 1 : 2".
7389 static void DiagnoseConditionalPrecedence(Sema &Self,
7390 SourceLocation OpLoc,
7394 BinaryOperatorKind CondOpcode;
7397 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7399 if (!ExprLooksBoolean(CondRHS))
7402 // The condition is an arithmetic binary expression, with a right-
7403 // hand side that looks boolean, so warn.
7405 Self.Diag(OpLoc, diag::warn_precedence_conditional)
7406 << Condition->getSourceRange()
7407 << BinaryOperator::getOpcodeStr(CondOpcode);
7411 Self.PDiag(diag::note_precedence_silence)
7412 << BinaryOperator::getOpcodeStr(CondOpcode),
7413 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7415 SuggestParentheses(Self, OpLoc,
7416 Self.PDiag(diag::note_precedence_conditional_first),
7417 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7420 /// Compute the nullability of a conditional expression.
7421 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7422 QualType LHSTy, QualType RHSTy,
7424 if (!ResTy->isAnyPointerType())
7427 auto GetNullability = [&Ctx](QualType Ty) {
7428 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7431 return NullabilityKind::Unspecified;
7434 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7435 NullabilityKind MergedKind;
7437 // Compute nullability of a binary conditional expression.
7439 if (LHSKind == NullabilityKind::NonNull)
7440 MergedKind = NullabilityKind::NonNull;
7442 MergedKind = RHSKind;
7443 // Compute nullability of a normal conditional expression.
7445 if (LHSKind == NullabilityKind::Nullable ||
7446 RHSKind == NullabilityKind::Nullable)
7447 MergedKind = NullabilityKind::Nullable;
7448 else if (LHSKind == NullabilityKind::NonNull)
7449 MergedKind = RHSKind;
7450 else if (RHSKind == NullabilityKind::NonNull)
7451 MergedKind = LHSKind;
7453 MergedKind = NullabilityKind::Unspecified;
7456 // Return if ResTy already has the correct nullability.
7457 if (GetNullability(ResTy) == MergedKind)
7460 // Strip all nullability from ResTy.
7461 while (ResTy->getNullability(Ctx))
7462 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7464 // Create a new AttributedType with the new nullability kind.
7465 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7466 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7469 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7470 /// in the case of a the GNU conditional expr extension.
7471 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7472 SourceLocation ColonLoc,
7473 Expr *CondExpr, Expr *LHSExpr,
7475 if (!getLangOpts().CPlusPlus) {
7476 // C cannot handle TypoExpr nodes in the condition because it
7477 // doesn't handle dependent types properly, so make sure any TypoExprs have
7478 // been dealt with before checking the operands.
7479 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7480 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7481 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7483 if (!CondResult.isUsable())
7487 if (!LHSResult.isUsable())
7491 if (!RHSResult.isUsable())
7494 CondExpr = CondResult.get();
7495 LHSExpr = LHSResult.get();
7496 RHSExpr = RHSResult.get();
7499 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7500 // was the condition.
7501 OpaqueValueExpr *opaqueValue = nullptr;
7502 Expr *commonExpr = nullptr;
7504 commonExpr = CondExpr;
7505 // Lower out placeholder types first. This is important so that we don't
7506 // try to capture a placeholder. This happens in few cases in C++; such
7507 // as Objective-C++'s dictionary subscripting syntax.
7508 if (commonExpr->hasPlaceholderType()) {
7509 ExprResult result = CheckPlaceholderExpr(commonExpr);
7510 if (!result.isUsable()) return ExprError();
7511 commonExpr = result.get();
7513 // We usually want to apply unary conversions *before* saving, except
7514 // in the special case of a C++ l-value conditional.
7515 if (!(getLangOpts().CPlusPlus
7516 && !commonExpr->isTypeDependent()
7517 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7518 && commonExpr->isGLValue()
7519 && commonExpr->isOrdinaryOrBitFieldObject()
7520 && RHSExpr->isOrdinaryOrBitFieldObject()
7521 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7522 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7523 if (commonRes.isInvalid())
7525 commonExpr = commonRes.get();
7528 // If the common expression is a class or array prvalue, materialize it
7529 // so that we can safely refer to it multiple times.
7530 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7531 commonExpr->getType()->isArrayType())) {
7532 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7533 if (MatExpr.isInvalid())
7535 commonExpr = MatExpr.get();
7538 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7539 commonExpr->getType(),
7540 commonExpr->getValueKind(),
7541 commonExpr->getObjectKind(),
7543 LHSExpr = CondExpr = opaqueValue;
7546 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7547 ExprValueKind VK = VK_RValue;
7548 ExprObjectKind OK = OK_Ordinary;
7549 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7550 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7551 VK, OK, QuestionLoc);
7552 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7556 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7559 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7561 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7565 return new (Context)
7566 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7567 RHS.get(), result, VK, OK);
7569 return new (Context) BinaryConditionalOperator(
7570 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7571 ColonLoc, result, VK, OK);
7574 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7575 // being closely modeled after the C99 spec:-). The odd characteristic of this
7576 // routine is it effectively iqnores the qualifiers on the top level pointee.
7577 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7578 // FIXME: add a couple examples in this comment.
7579 static Sema::AssignConvertType
7580 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7581 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7582 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7584 // get the "pointed to" type (ignoring qualifiers at the top level)
7585 const Type *lhptee, *rhptee;
7586 Qualifiers lhq, rhq;
7587 std::tie(lhptee, lhq) =
7588 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7589 std::tie(rhptee, rhq) =
7590 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7592 Sema::AssignConvertType ConvTy = Sema::Compatible;
7594 // C99 6.5.16.1p1: This following citation is common to constraints
7595 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7596 // qualifiers of the type *pointed to* by the right;
7598 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7599 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7600 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7601 // Ignore lifetime for further calculation.
7602 lhq.removeObjCLifetime();
7603 rhq.removeObjCLifetime();
7606 if (!lhq.compatiblyIncludes(rhq)) {
7607 // Treat address-space mismatches as fatal. TODO: address subspaces
7608 if (!lhq.isAddressSpaceSupersetOf(rhq))
7609 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7611 // It's okay to add or remove GC or lifetime qualifiers when converting to
7613 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7614 .compatiblyIncludes(
7615 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7616 && (lhptee->isVoidType() || rhptee->isVoidType()))
7619 // Treat lifetime mismatches as fatal.
7620 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7621 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7623 // For GCC/MS compatibility, other qualifier mismatches are treated
7624 // as still compatible in C.
7625 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7628 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7629 // incomplete type and the other is a pointer to a qualified or unqualified
7630 // version of void...
7631 if (lhptee->isVoidType()) {
7632 if (rhptee->isIncompleteOrObjectType())
7635 // As an extension, we allow cast to/from void* to function pointer.
7636 assert(rhptee->isFunctionType());
7637 return Sema::FunctionVoidPointer;
7640 if (rhptee->isVoidType()) {
7641 if (lhptee->isIncompleteOrObjectType())
7644 // As an extension, we allow cast to/from void* to function pointer.
7645 assert(lhptee->isFunctionType());
7646 return Sema::FunctionVoidPointer;
7649 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7650 // unqualified versions of compatible types, ...
7651 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7652 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7653 // Check if the pointee types are compatible ignoring the sign.
7654 // We explicitly check for char so that we catch "char" vs
7655 // "unsigned char" on systems where "char" is unsigned.
7656 if (lhptee->isCharType())
7657 ltrans = S.Context.UnsignedCharTy;
7658 else if (lhptee->hasSignedIntegerRepresentation())
7659 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7661 if (rhptee->isCharType())
7662 rtrans = S.Context.UnsignedCharTy;
7663 else if (rhptee->hasSignedIntegerRepresentation())
7664 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7666 if (ltrans == rtrans) {
7667 // Types are compatible ignoring the sign. Qualifier incompatibility
7668 // takes priority over sign incompatibility because the sign
7669 // warning can be disabled.
7670 if (ConvTy != Sema::Compatible)
7673 return Sema::IncompatiblePointerSign;
7676 // If we are a multi-level pointer, it's possible that our issue is simply
7677 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7678 // the eventual target type is the same and the pointers have the same
7679 // level of indirection, this must be the issue.
7680 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7682 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7683 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7684 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7686 if (lhptee == rhptee)
7687 return Sema::IncompatibleNestedPointerQualifiers;
7690 // General pointer incompatibility takes priority over qualifiers.
7691 return Sema::IncompatiblePointer;
7693 if (!S.getLangOpts().CPlusPlus &&
7694 S.IsFunctionConversion(ltrans, rtrans, ltrans))
7695 return Sema::IncompatiblePointer;
7699 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7700 /// block pointer types are compatible or whether a block and normal pointer
7701 /// are compatible. It is more restrict than comparing two function pointer
7703 static Sema::AssignConvertType
7704 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7706 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7707 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7709 QualType lhptee, rhptee;
7711 // get the "pointed to" type (ignoring qualifiers at the top level)
7712 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7713 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7715 // In C++, the types have to match exactly.
7716 if (S.getLangOpts().CPlusPlus)
7717 return Sema::IncompatibleBlockPointer;
7719 Sema::AssignConvertType ConvTy = Sema::Compatible;
7721 // For blocks we enforce that qualifiers are identical.
7722 Qualifiers LQuals = lhptee.getLocalQualifiers();
7723 Qualifiers RQuals = rhptee.getLocalQualifiers();
7724 if (S.getLangOpts().OpenCL) {
7725 LQuals.removeAddressSpace();
7726 RQuals.removeAddressSpace();
7728 if (LQuals != RQuals)
7729 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7731 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7733 // The current behavior is similar to C++ lambdas. A block might be
7734 // assigned to a variable iff its return type and parameters are compatible
7735 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7736 // an assignment. Presumably it should behave in way that a function pointer
7737 // assignment does in C, so for each parameter and return type:
7738 // * CVR and address space of LHS should be a superset of CVR and address
7740 // * unqualified types should be compatible.
7741 if (S.getLangOpts().OpenCL) {
7742 if (!S.Context.typesAreBlockPointerCompatible(
7743 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7744 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7745 return Sema::IncompatibleBlockPointer;
7746 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7747 return Sema::IncompatibleBlockPointer;
7752 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7753 /// for assignment compatibility.
7754 static Sema::AssignConvertType
7755 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7757 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7758 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7760 if (LHSType->isObjCBuiltinType()) {
7761 // Class is not compatible with ObjC object pointers.
7762 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7763 !RHSType->isObjCQualifiedClassType())
7764 return Sema::IncompatiblePointer;
7765 return Sema::Compatible;
7767 if (RHSType->isObjCBuiltinType()) {
7768 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7769 !LHSType->isObjCQualifiedClassType())
7770 return Sema::IncompatiblePointer;
7771 return Sema::Compatible;
7773 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7774 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7776 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7777 // make an exception for id<P>
7778 !LHSType->isObjCQualifiedIdType())
7779 return Sema::CompatiblePointerDiscardsQualifiers;
7781 if (S.Context.typesAreCompatible(LHSType, RHSType))
7782 return Sema::Compatible;
7783 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7784 return Sema::IncompatibleObjCQualifiedId;
7785 return Sema::IncompatiblePointer;
7788 Sema::AssignConvertType
7789 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7790 QualType LHSType, QualType RHSType) {
7791 // Fake up an opaque expression. We don't actually care about what
7792 // cast operations are required, so if CheckAssignmentConstraints
7793 // adds casts to this they'll be wasted, but fortunately that doesn't
7794 // usually happen on valid code.
7795 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7796 ExprResult RHSPtr = &RHSExpr;
7799 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7802 /// This helper function returns true if QT is a vector type that has element
7803 /// type ElementType.
7804 static bool isVector(QualType QT, QualType ElementType) {
7805 if (const VectorType *VT = QT->getAs<VectorType>())
7806 return VT->getElementType() == ElementType;
7810 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7811 /// has code to accommodate several GCC extensions when type checking
7812 /// pointers. Here are some objectionable examples that GCC considers warnings:
7816 /// struct foo *pfoo;
7818 /// pint = pshort; // warning: assignment from incompatible pointer type
7819 /// a = pint; // warning: assignment makes integer from pointer without a cast
7820 /// pint = a; // warning: assignment makes pointer from integer without a cast
7821 /// pint = pfoo; // warning: assignment from incompatible pointer type
7823 /// As a result, the code for dealing with pointers is more complex than the
7824 /// C99 spec dictates.
7826 /// Sets 'Kind' for any result kind except Incompatible.
7827 Sema::AssignConvertType
7828 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7829 CastKind &Kind, bool ConvertRHS) {
7830 QualType RHSType = RHS.get()->getType();
7831 QualType OrigLHSType = LHSType;
7833 // Get canonical types. We're not formatting these types, just comparing
7835 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7836 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7838 // Common case: no conversion required.
7839 if (LHSType == RHSType) {
7844 // If we have an atomic type, try a non-atomic assignment, then just add an
7845 // atomic qualification step.
7846 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7847 Sema::AssignConvertType result =
7848 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7849 if (result != Compatible)
7851 if (Kind != CK_NoOp && ConvertRHS)
7852 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7853 Kind = CK_NonAtomicToAtomic;
7857 // If the left-hand side is a reference type, then we are in a
7858 // (rare!) case where we've allowed the use of references in C,
7859 // e.g., as a parameter type in a built-in function. In this case,
7860 // just make sure that the type referenced is compatible with the
7861 // right-hand side type. The caller is responsible for adjusting
7862 // LHSType so that the resulting expression does not have reference
7864 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7865 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7866 Kind = CK_LValueBitCast;
7869 return Incompatible;
7872 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7873 // to the same ExtVector type.
7874 if (LHSType->isExtVectorType()) {
7875 if (RHSType->isExtVectorType())
7876 return Incompatible;
7877 if (RHSType->isArithmeticType()) {
7878 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7880 RHS = prepareVectorSplat(LHSType, RHS.get());
7881 Kind = CK_VectorSplat;
7886 // Conversions to or from vector type.
7887 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7888 if (LHSType->isVectorType() && RHSType->isVectorType()) {
7889 // Allow assignments of an AltiVec vector type to an equivalent GCC
7890 // vector type and vice versa
7891 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7896 // If we are allowing lax vector conversions, and LHS and RHS are both
7897 // vectors, the total size only needs to be the same. This is a bitcast;
7898 // no bits are changed but the result type is different.
7899 if (isLaxVectorConversion(RHSType, LHSType)) {
7901 return IncompatibleVectors;
7905 // When the RHS comes from another lax conversion (e.g. binops between
7906 // scalars and vectors) the result is canonicalized as a vector. When the
7907 // LHS is also a vector, the lax is allowed by the condition above. Handle
7908 // the case where LHS is a scalar.
7909 if (LHSType->isScalarType()) {
7910 const VectorType *VecType = RHSType->getAs<VectorType>();
7911 if (VecType && VecType->getNumElements() == 1 &&
7912 isLaxVectorConversion(RHSType, LHSType)) {
7913 ExprResult *VecExpr = &RHS;
7914 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7920 return Incompatible;
7923 // Diagnose attempts to convert between __float128 and long double where
7924 // such conversions currently can't be handled.
7925 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7926 return Incompatible;
7928 // Disallow assigning a _Complex to a real type in C++ mode since it simply
7929 // discards the imaginary part.
7930 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7931 !LHSType->getAs<ComplexType>())
7932 return Incompatible;
7934 // Arithmetic conversions.
7935 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7936 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7938 Kind = PrepareScalarCast(RHS, LHSType);
7942 // Conversions to normal pointers.
7943 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7945 if (isa<PointerType>(RHSType)) {
7946 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7947 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7948 if (AddrSpaceL != AddrSpaceR)
7949 Kind = CK_AddressSpaceConversion;
7950 else if (Context.hasCvrSimilarType(RHSType, LHSType))
7954 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7958 if (RHSType->isIntegerType()) {
7959 Kind = CK_IntegralToPointer; // FIXME: null?
7960 return IntToPointer;
7963 // C pointers are not compatible with ObjC object pointers,
7964 // with two exceptions:
7965 if (isa<ObjCObjectPointerType>(RHSType)) {
7966 // - conversions to void*
7967 if (LHSPointer->getPointeeType()->isVoidType()) {
7972 // - conversions from 'Class' to the redefinition type
7973 if (RHSType->isObjCClassType() &&
7974 Context.hasSameType(LHSType,
7975 Context.getObjCClassRedefinitionType())) {
7981 return IncompatiblePointer;
7985 if (RHSType->getAs<BlockPointerType>()) {
7986 if (LHSPointer->getPointeeType()->isVoidType()) {
7987 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7988 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7992 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7997 return Incompatible;
8000 // Conversions to block pointers.
8001 if (isa<BlockPointerType>(LHSType)) {
8003 if (RHSType->isBlockPointerType()) {
8004 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8007 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8010 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8011 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8014 // int or null -> T^
8015 if (RHSType->isIntegerType()) {
8016 Kind = CK_IntegralToPointer; // FIXME: null
8017 return IntToBlockPointer;
8021 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8022 Kind = CK_AnyPointerToBlockPointerCast;
8027 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8028 if (RHSPT->getPointeeType()->isVoidType()) {
8029 Kind = CK_AnyPointerToBlockPointerCast;
8033 return Incompatible;
8036 // Conversions to Objective-C pointers.
8037 if (isa<ObjCObjectPointerType>(LHSType)) {
8039 if (RHSType->isObjCObjectPointerType()) {
8041 Sema::AssignConvertType result =
8042 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8043 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8044 result == Compatible &&
8045 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8046 result = IncompatibleObjCWeakRef;
8050 // int or null -> A*
8051 if (RHSType->isIntegerType()) {
8052 Kind = CK_IntegralToPointer; // FIXME: null
8053 return IntToPointer;
8056 // In general, C pointers are not compatible with ObjC object pointers,
8057 // with two exceptions:
8058 if (isa<PointerType>(RHSType)) {
8059 Kind = CK_CPointerToObjCPointerCast;
8061 // - conversions from 'void*'
8062 if (RHSType->isVoidPointerType()) {
8066 // - conversions to 'Class' from its redefinition type
8067 if (LHSType->isObjCClassType() &&
8068 Context.hasSameType(RHSType,
8069 Context.getObjCClassRedefinitionType())) {
8073 return IncompatiblePointer;
8076 // Only under strict condition T^ is compatible with an Objective-C pointer.
8077 if (RHSType->isBlockPointerType() &&
8078 LHSType->isBlockCompatibleObjCPointerType(Context)) {
8080 maybeExtendBlockObject(RHS);
8081 Kind = CK_BlockPointerToObjCPointerCast;
8085 return Incompatible;
8088 // Conversions from pointers that are not covered by the above.
8089 if (isa<PointerType>(RHSType)) {
8091 if (LHSType == Context.BoolTy) {
8092 Kind = CK_PointerToBoolean;
8097 if (LHSType->isIntegerType()) {
8098 Kind = CK_PointerToIntegral;
8099 return PointerToInt;
8102 return Incompatible;
8105 // Conversions from Objective-C pointers that are not covered by the above.
8106 if (isa<ObjCObjectPointerType>(RHSType)) {
8108 if (LHSType == Context.BoolTy) {
8109 Kind = CK_PointerToBoolean;
8114 if (LHSType->isIntegerType()) {
8115 Kind = CK_PointerToIntegral;
8116 return PointerToInt;
8119 return Incompatible;
8122 // struct A -> struct B
8123 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8124 if (Context.typesAreCompatible(LHSType, RHSType)) {
8130 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8131 Kind = CK_IntToOCLSampler;
8135 return Incompatible;
8138 /// Constructs a transparent union from an expression that is
8139 /// used to initialize the transparent union.
8140 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8141 ExprResult &EResult, QualType UnionType,
8143 // Build an initializer list that designates the appropriate member
8144 // of the transparent union.
8145 Expr *E = EResult.get();
8146 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8147 E, SourceLocation());
8148 Initializer->setType(UnionType);
8149 Initializer->setInitializedFieldInUnion(Field);
8151 // Build a compound literal constructing a value of the transparent
8152 // union type from this initializer list.
8153 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8154 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8155 VK_RValue, Initializer, false);
8158 Sema::AssignConvertType
8159 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8161 QualType RHSType = RHS.get()->getType();
8163 // If the ArgType is a Union type, we want to handle a potential
8164 // transparent_union GCC extension.
8165 const RecordType *UT = ArgType->getAsUnionType();
8166 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8167 return Incompatible;
8169 // The field to initialize within the transparent union.
8170 RecordDecl *UD = UT->getDecl();
8171 FieldDecl *InitField = nullptr;
8172 // It's compatible if the expression matches any of the fields.
8173 for (auto *it : UD->fields()) {
8174 if (it->getType()->isPointerType()) {
8175 // If the transparent union contains a pointer type, we allow:
8177 // 2) null pointer constant
8178 if (RHSType->isPointerType())
8179 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8180 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8185 if (RHS.get()->isNullPointerConstant(Context,
8186 Expr::NPC_ValueDependentIsNull)) {
8187 RHS = ImpCastExprToType(RHS.get(), it->getType(),
8195 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8197 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8204 return Incompatible;
8206 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8210 Sema::AssignConvertType
8211 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8213 bool DiagnoseCFAudited,
8215 // We need to be able to tell the caller whether we diagnosed a problem, if
8216 // they ask us to issue diagnostics.
8217 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8219 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8220 // we can't avoid *all* modifications at the moment, so we need some somewhere
8221 // to put the updated value.
8222 ExprResult LocalRHS = CallerRHS;
8223 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8225 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8226 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8227 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8228 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8229 Diag(RHS.get()->getExprLoc(),
8230 diag::warn_noderef_to_dereferenceable_pointer)
8231 << RHS.get()->getSourceRange();
8236 if (getLangOpts().CPlusPlus) {
8237 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8238 // C++ 5.17p3: If the left operand is not of class type, the
8239 // expression is implicitly converted (C++ 4) to the
8240 // cv-unqualified type of the left operand.
8241 QualType RHSType = RHS.get()->getType();
8243 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8246 ImplicitConversionSequence ICS =
8247 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8248 /*SuppressUserConversions=*/false,
8249 /*AllowExplicit=*/false,
8250 /*InOverloadResolution=*/false,
8252 /*AllowObjCWritebackConversion=*/false);
8253 if (ICS.isFailure())
8254 return Incompatible;
8255 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8258 if (RHS.isInvalid())
8259 return Incompatible;
8260 Sema::AssignConvertType result = Compatible;
8261 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8262 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8263 result = IncompatibleObjCWeakRef;
8267 // FIXME: Currently, we fall through and treat C++ classes like C
8269 // FIXME: We also fall through for atomics; not sure what should
8270 // happen there, though.
8271 } else if (RHS.get()->getType() == Context.OverloadTy) {
8272 // As a set of extensions to C, we support overloading on functions. These
8273 // functions need to be resolved here.
8275 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8276 RHS.get(), LHSType, /*Complain=*/false, DAP))
8277 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8279 return Incompatible;
8282 // C99 6.5.16.1p1: the left operand is a pointer and the right is
8283 // a null pointer constant.
8284 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8285 LHSType->isBlockPointerType()) &&
8286 RHS.get()->isNullPointerConstant(Context,
8287 Expr::NPC_ValueDependentIsNull)) {
8288 if (Diagnose || ConvertRHS) {
8291 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8292 /*IgnoreBaseAccess=*/false, Diagnose);
8294 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8299 // OpenCL queue_t type assignment.
8300 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8301 Context, Expr::NPC_ValueDependentIsNull)) {
8302 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8306 // This check seems unnatural, however it is necessary to ensure the proper
8307 // conversion of functions/arrays. If the conversion were done for all
8308 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8309 // expressions that suppress this implicit conversion (&, sizeof).
8311 // Suppress this for references: C++ 8.5.3p5.
8312 if (!LHSType->isReferenceType()) {
8313 // FIXME: We potentially allocate here even if ConvertRHS is false.
8314 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8315 if (RHS.isInvalid())
8316 return Incompatible;
8319 Sema::AssignConvertType result =
8320 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8322 // C99 6.5.16.1p2: The value of the right operand is converted to the
8323 // type of the assignment expression.
8324 // CheckAssignmentConstraints allows the left-hand side to be a reference,
8325 // so that we can use references in built-in functions even in C.
8326 // The getNonReferenceType() call makes sure that the resulting expression
8327 // does not have reference type.
8328 if (result != Incompatible && RHS.get()->getType() != LHSType) {
8329 QualType Ty = LHSType.getNonLValueExprType(Context);
8330 Expr *E = RHS.get();
8332 // Check for various Objective-C errors. If we are not reporting
8333 // diagnostics and just checking for errors, e.g., during overload
8334 // resolution, return Incompatible to indicate the failure.
8335 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8336 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8337 Diagnose, DiagnoseCFAudited) != ACR_okay) {
8339 return Incompatible;
8341 if (getLangOpts().ObjC &&
8342 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8343 E->getType(), E, Diagnose) ||
8344 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8346 return Incompatible;
8347 // Replace the expression with a corrected version and continue so we
8348 // can find further errors.
8354 RHS = ImpCastExprToType(E, Ty, Kind);
8361 /// The original operand to an operator, prior to the application of the usual
8362 /// arithmetic conversions and converting the arguments of a builtin operator
8364 struct OriginalOperand {
8365 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8366 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8367 Op = MTE->GetTemporaryExpr();
8368 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8369 Op = BTE->getSubExpr();
8370 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8371 Orig = ICE->getSubExprAsWritten();
8372 Conversion = ICE->getConversionFunction();
8376 QualType getType() const { return Orig->getType(); }
8379 NamedDecl *Conversion;
8383 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8385 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8387 Diag(Loc, diag::err_typecheck_invalid_operands)
8388 << OrigLHS.getType() << OrigRHS.getType()
8389 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8391 // If a user-defined conversion was applied to either of the operands prior
8392 // to applying the built-in operator rules, tell the user about it.
8393 if (OrigLHS.Conversion) {
8394 Diag(OrigLHS.Conversion->getLocation(),
8395 diag::note_typecheck_invalid_operands_converted)
8396 << 0 << LHS.get()->getType();
8398 if (OrigRHS.Conversion) {
8399 Diag(OrigRHS.Conversion->getLocation(),
8400 diag::note_typecheck_invalid_operands_converted)
8401 << 1 << RHS.get()->getType();
8407 // Diagnose cases where a scalar was implicitly converted to a vector and
8408 // diagnose the underlying types. Otherwise, diagnose the error
8409 // as invalid vector logical operands for non-C++ cases.
8410 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8412 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8413 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8415 bool LHSNatVec = LHSType->isVectorType();
8416 bool RHSNatVec = RHSType->isVectorType();
8418 if (!(LHSNatVec && RHSNatVec)) {
8419 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8420 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8421 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8422 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8423 << Vector->getSourceRange();
8427 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8428 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8429 << RHS.get()->getSourceRange();
8434 /// Try to convert a value of non-vector type to a vector type by converting
8435 /// the type to the element type of the vector and then performing a splat.
8436 /// If the language is OpenCL, we only use conversions that promote scalar
8437 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8440 /// OpenCL V2.0 6.2.6.p2:
8441 /// An error shall occur if any scalar operand type has greater rank
8442 /// than the type of the vector element.
8444 /// \param scalar - if non-null, actually perform the conversions
8445 /// \return true if the operation fails (but without diagnosing the failure)
8446 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8448 QualType vectorEltTy,
8451 // The conversion to apply to the scalar before splatting it,
8453 CastKind scalarCast = CK_NoOp;
8455 if (vectorEltTy->isIntegralType(S.Context)) {
8456 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8457 (scalarTy->isIntegerType() &&
8458 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8459 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8462 if (!scalarTy->isIntegralType(S.Context))
8464 scalarCast = CK_IntegralCast;
8465 } else if (vectorEltTy->isRealFloatingType()) {
8466 if (scalarTy->isRealFloatingType()) {
8467 if (S.getLangOpts().OpenCL &&
8468 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8469 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8472 scalarCast = CK_FloatingCast;
8474 else if (scalarTy->isIntegralType(S.Context))
8475 scalarCast = CK_IntegralToFloating;
8482 // Adjust scalar if desired.
8484 if (scalarCast != CK_NoOp)
8485 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8486 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8491 /// Convert vector E to a vector with the same number of elements but different
8493 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8494 const auto *VecTy = E->getType()->getAs<VectorType>();
8495 assert(VecTy && "Expression E must be a vector");
8496 QualType NewVecTy = S.Context.getVectorType(ElementType,
8497 VecTy->getNumElements(),
8498 VecTy->getVectorKind());
8500 // Look through the implicit cast. Return the subexpression if its type is
8502 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8503 if (ICE->getSubExpr()->getType() == NewVecTy)
8504 return ICE->getSubExpr();
8506 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8507 return S.ImpCastExprToType(E, NewVecTy, Cast);
8510 /// Test if a (constant) integer Int can be casted to another integer type
8511 /// IntTy without losing precision.
8512 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8513 QualType OtherIntTy) {
8514 QualType IntTy = Int->get()->getType().getUnqualifiedType();
8516 // Reject cases where the value of the Int is unknown as that would
8517 // possibly cause truncation, but accept cases where the scalar can be
8518 // demoted without loss of precision.
8519 Expr::EvalResult EVResult;
8520 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8521 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8522 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8523 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8526 // If the scalar is constant and is of a higher order and has more active
8527 // bits that the vector element type, reject it.
8528 llvm::APSInt Result = EVResult.Val.getInt();
8529 unsigned NumBits = IntSigned
8530 ? (Result.isNegative() ? Result.getMinSignedBits()
8531 : Result.getActiveBits())
8532 : Result.getActiveBits();
8533 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8536 // If the signedness of the scalar type and the vector element type
8537 // differs and the number of bits is greater than that of the vector
8538 // element reject it.
8539 return (IntSigned != OtherIntSigned &&
8540 NumBits > S.Context.getIntWidth(OtherIntTy));
8543 // Reject cases where the value of the scalar is not constant and it's
8544 // order is greater than that of the vector element type.
8548 /// Test if a (constant) integer Int can be casted to floating point type
8549 /// FloatTy without losing precision.
8550 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8552 QualType IntTy = Int->get()->getType().getUnqualifiedType();
8554 // Determine if the integer constant can be expressed as a floating point
8555 // number of the appropriate type.
8556 Expr::EvalResult EVResult;
8557 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8561 // Reject constants that would be truncated if they were converted to
8562 // the floating point type. Test by simple to/from conversion.
8563 // FIXME: Ideally the conversion to an APFloat and from an APFloat
8564 // could be avoided if there was a convertFromAPInt method
8565 // which could signal back if implicit truncation occurred.
8566 llvm::APSInt Result = EVResult.Val.getInt();
8567 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8568 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8569 llvm::APFloat::rmTowardZero);
8570 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8571 !IntTy->hasSignedIntegerRepresentation());
8572 bool Ignored = false;
8573 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8575 if (Result != ConvertBack)
8578 // Reject types that cannot be fully encoded into the mantissa of
8580 Bits = S.Context.getTypeSize(IntTy);
8581 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8582 S.Context.getFloatTypeSemantics(FloatTy));
8583 if (Bits > FloatPrec)
8590 /// Attempt to convert and splat Scalar into a vector whose types matches
8591 /// Vector following GCC conversion rules. The rule is that implicit
8592 /// conversion can occur when Scalar can be casted to match Vector's element
8593 /// type without causing truncation of Scalar.
8594 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8595 ExprResult *Vector) {
8596 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8597 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8598 const VectorType *VT = VectorTy->getAs<VectorType>();
8600 assert(!isa<ExtVectorType>(VT) &&
8601 "ExtVectorTypes should not be handled here!");
8603 QualType VectorEltTy = VT->getElementType();
8605 // Reject cases where the vector element type or the scalar element type are
8606 // not integral or floating point types.
8607 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8610 // The conversion to apply to the scalar before splatting it,
8612 CastKind ScalarCast = CK_NoOp;
8614 // Accept cases where the vector elements are integers and the scalar is
8616 // FIXME: Notionally if the scalar was a floating point value with a precise
8617 // integral representation, we could cast it to an appropriate integer
8618 // type and then perform the rest of the checks here. GCC will perform
8619 // this conversion in some cases as determined by the input language.
8620 // We should accept it on a language independent basis.
8621 if (VectorEltTy->isIntegralType(S.Context) &&
8622 ScalarTy->isIntegralType(S.Context) &&
8623 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8625 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8628 ScalarCast = CK_IntegralCast;
8629 } else if (VectorEltTy->isRealFloatingType()) {
8630 if (ScalarTy->isRealFloatingType()) {
8632 // Reject cases where the scalar type is not a constant and has a higher
8633 // Order than the vector element type.
8634 llvm::APFloat Result(0.0);
8635 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8636 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8637 if (!CstScalar && Order < 0)
8640 // If the scalar cannot be safely casted to the vector element type,
8643 bool Truncated = false;
8644 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8645 llvm::APFloat::rmNearestTiesToEven, &Truncated);
8650 ScalarCast = CK_FloatingCast;
8651 } else if (ScalarTy->isIntegralType(S.Context)) {
8652 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8655 ScalarCast = CK_IntegralToFloating;
8660 // Adjust scalar if desired.
8662 if (ScalarCast != CK_NoOp)
8663 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8664 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8669 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8670 SourceLocation Loc, bool IsCompAssign,
8672 bool AllowBoolConversions) {
8673 if (!IsCompAssign) {
8674 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8675 if (LHS.isInvalid())
8678 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8679 if (RHS.isInvalid())
8682 // For conversion purposes, we ignore any qualifiers.
8683 // For example, "const float" and "float" are equivalent.
8684 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8685 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8687 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8688 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8689 assert(LHSVecType || RHSVecType);
8691 // AltiVec-style "vector bool op vector bool" combinations are allowed
8692 // for some operators but not others.
8693 if (!AllowBothBool &&
8694 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8695 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8696 return InvalidOperands(Loc, LHS, RHS);
8698 // If the vector types are identical, return.
8699 if (Context.hasSameType(LHSType, RHSType))
8702 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8703 if (LHSVecType && RHSVecType &&
8704 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8705 if (isa<ExtVectorType>(LHSVecType)) {
8706 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8711 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8715 // AllowBoolConversions says that bool and non-bool AltiVec vectors
8716 // can be mixed, with the result being the non-bool type. The non-bool
8717 // operand must have integer element type.
8718 if (AllowBoolConversions && LHSVecType && RHSVecType &&
8719 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8720 (Context.getTypeSize(LHSVecType->getElementType()) ==
8721 Context.getTypeSize(RHSVecType->getElementType()))) {
8722 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8723 LHSVecType->getElementType()->isIntegerType() &&
8724 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8725 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8728 if (!IsCompAssign &&
8729 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8730 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8731 RHSVecType->getElementType()->isIntegerType()) {
8732 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8737 // If there's a vector type and a scalar, try to convert the scalar to
8738 // the vector element type and splat.
8739 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8741 if (isa<ExtVectorType>(LHSVecType)) {
8742 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8743 LHSVecType->getElementType(), LHSType,
8747 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8752 if (isa<ExtVectorType>(RHSVecType)) {
8753 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8754 LHSType, RHSVecType->getElementType(),
8758 if (LHS.get()->getValueKind() == VK_LValue ||
8759 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8764 // FIXME: The code below also handles conversion between vectors and
8765 // non-scalars, we should break this down into fine grained specific checks
8766 // and emit proper diagnostics.
8767 QualType VecType = LHSVecType ? LHSType : RHSType;
8768 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8769 QualType OtherType = LHSVecType ? RHSType : LHSType;
8770 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8771 if (isLaxVectorConversion(OtherType, VecType)) {
8772 // If we're allowing lax vector conversions, only the total (data) size
8773 // needs to be the same. For non compound assignment, if one of the types is
8774 // scalar, the result is always the vector type.
8775 if (!IsCompAssign) {
8776 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8778 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8779 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8780 // type. Note that this is already done by non-compound assignments in
8781 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8782 // <1 x T> -> T. The result is also a vector type.
8783 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8784 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8785 ExprResult *RHSExpr = &RHS;
8786 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8791 // Okay, the expression is invalid.
8793 // If there's a non-vector, non-real operand, diagnose that.
8794 if ((!RHSVecType && !RHSType->isRealType()) ||
8795 (!LHSVecType && !LHSType->isRealType())) {
8796 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8797 << LHSType << RHSType
8798 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8802 // OpenCL V1.1 6.2.6.p1:
8803 // If the operands are of more than one vector type, then an error shall
8804 // occur. Implicit conversions between vector types are not permitted, per
8806 if (getLangOpts().OpenCL &&
8807 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8808 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8809 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8815 // If there is a vector type that is not a ExtVector and a scalar, we reach
8816 // this point if scalar could not be converted to the vector's element type
8817 // without truncation.
8818 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8819 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8820 QualType Scalar = LHSVecType ? RHSType : LHSType;
8821 QualType Vector = LHSVecType ? LHSType : RHSType;
8822 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8824 diag::err_typecheck_vector_not_convertable_implict_truncation)
8825 << ScalarOrVector << Scalar << Vector;
8830 // Otherwise, use the generic diagnostic.
8832 << LHSType << RHSType
8833 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8837 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8838 // expression. These are mainly cases where the null pointer is used as an
8839 // integer instead of a pointer.
8840 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8841 SourceLocation Loc, bool IsCompare) {
8842 // The canonical way to check for a GNU null is with isNullPointerConstant,
8843 // but we use a bit of a hack here for speed; this is a relatively
8844 // hot path, and isNullPointerConstant is slow.
8845 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8846 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8848 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8850 // Avoid analyzing cases where the result will either be invalid (and
8851 // diagnosed as such) or entirely valid and not something to warn about.
8852 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8853 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8856 // Comparison operations would not make sense with a null pointer no matter
8857 // what the other expression is.
8859 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8860 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8861 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8865 // The rest of the operations only make sense with a null pointer
8866 // if the other expression is a pointer.
8867 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8868 NonNullType->canDecayToPointerType())
8871 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8872 << LHSNull /* LHS is NULL */ << NonNullType
8873 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8876 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
8877 SourceLocation Loc) {
8878 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
8879 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
8882 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
8883 RUE->getKind() != UETT_SizeOf)
8886 QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
8889 if (RUE->isArgumentType())
8890 RHSTy = RUE->getArgumentType();
8892 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
8894 if (!LHSTy->isPointerType() || RHSTy->isPointerType())
8896 if (LHSTy->getPointeeType() != RHSTy)
8899 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
8902 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8904 SourceLocation Loc, bool IsDiv) {
8905 // Check for division/remainder by zero.
8906 Expr::EvalResult RHSValue;
8907 if (!RHS.get()->isValueDependent() &&
8908 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
8909 RHSValue.Val.getInt() == 0)
8910 S.DiagRuntimeBehavior(Loc, RHS.get(),
8911 S.PDiag(diag::warn_remainder_division_by_zero)
8912 << IsDiv << RHS.get()->getSourceRange());
8915 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8917 bool IsCompAssign, bool IsDiv) {
8918 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8920 if (LHS.get()->getType()->isVectorType() ||
8921 RHS.get()->getType()->isVectorType())
8922 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8923 /*AllowBothBool*/getLangOpts().AltiVec,
8924 /*AllowBoolConversions*/false);
8926 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8927 if (LHS.isInvalid() || RHS.isInvalid())
8931 if (compType.isNull() || !compType->isArithmeticType())
8932 return InvalidOperands(Loc, LHS, RHS);
8934 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8935 DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
8940 QualType Sema::CheckRemainderOperands(
8941 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8942 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8944 if (LHS.get()->getType()->isVectorType() ||
8945 RHS.get()->getType()->isVectorType()) {
8946 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8947 RHS.get()->getType()->hasIntegerRepresentation())
8948 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8949 /*AllowBothBool*/getLangOpts().AltiVec,
8950 /*AllowBoolConversions*/false);
8951 return InvalidOperands(Loc, LHS, RHS);
8954 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8955 if (LHS.isInvalid() || RHS.isInvalid())
8958 if (compType.isNull() || !compType->isIntegerType())
8959 return InvalidOperands(Loc, LHS, RHS);
8960 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8964 /// Diagnose invalid arithmetic on two void pointers.
8965 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8966 Expr *LHSExpr, Expr *RHSExpr) {
8967 S.Diag(Loc, S.getLangOpts().CPlusPlus
8968 ? diag::err_typecheck_pointer_arith_void_type
8969 : diag::ext_gnu_void_ptr)
8970 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8971 << RHSExpr->getSourceRange();
8974 /// Diagnose invalid arithmetic on a void pointer.
8975 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8977 S.Diag(Loc, S.getLangOpts().CPlusPlus
8978 ? diag::err_typecheck_pointer_arith_void_type
8979 : diag::ext_gnu_void_ptr)
8980 << 0 /* one pointer */ << Pointer->getSourceRange();
8983 /// Diagnose invalid arithmetic on a null pointer.
8985 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8986 /// idiom, which we recognize as a GNU extension.
8988 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8989 Expr *Pointer, bool IsGNUIdiom) {
8991 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8992 << Pointer->getSourceRange();
8994 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8995 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8998 /// Diagnose invalid arithmetic on two function pointers.
8999 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9000 Expr *LHS, Expr *RHS) {
9001 assert(LHS->getType()->isAnyPointerType());
9002 assert(RHS->getType()->isAnyPointerType());
9003 S.Diag(Loc, S.getLangOpts().CPlusPlus
9004 ? diag::err_typecheck_pointer_arith_function_type
9005 : diag::ext_gnu_ptr_func_arith)
9006 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9007 // We only show the second type if it differs from the first.
9008 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9010 << RHS->getType()->getPointeeType()
9011 << LHS->getSourceRange() << RHS->getSourceRange();
9014 /// Diagnose invalid arithmetic on a function pointer.
9015 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9017 assert(Pointer->getType()->isAnyPointerType());
9018 S.Diag(Loc, S.getLangOpts().CPlusPlus
9019 ? diag::err_typecheck_pointer_arith_function_type
9020 : diag::ext_gnu_ptr_func_arith)
9021 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9022 << 0 /* one pointer, so only one type */
9023 << Pointer->getSourceRange();
9026 /// Emit error if Operand is incomplete pointer type
9028 /// \returns True if pointer has incomplete type
9029 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9031 QualType ResType = Operand->getType();
9032 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9033 ResType = ResAtomicType->getValueType();
9035 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9036 QualType PointeeTy = ResType->getPointeeType();
9037 return S.RequireCompleteType(Loc, PointeeTy,
9038 diag::err_typecheck_arithmetic_incomplete_type,
9039 PointeeTy, Operand->getSourceRange());
9042 /// Check the validity of an arithmetic pointer operand.
9044 /// If the operand has pointer type, this code will check for pointer types
9045 /// which are invalid in arithmetic operations. These will be diagnosed
9046 /// appropriately, including whether or not the use is supported as an
9049 /// \returns True when the operand is valid to use (even if as an extension).
9050 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9052 QualType ResType = Operand->getType();
9053 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9054 ResType = ResAtomicType->getValueType();
9056 if (!ResType->isAnyPointerType()) return true;
9058 QualType PointeeTy = ResType->getPointeeType();
9059 if (PointeeTy->isVoidType()) {
9060 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9061 return !S.getLangOpts().CPlusPlus;
9063 if (PointeeTy->isFunctionType()) {
9064 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9065 return !S.getLangOpts().CPlusPlus;
9068 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9073 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9076 /// This routine will diagnose any invalid arithmetic on pointer operands much
9077 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9078 /// for emitting a single diagnostic even for operations where both LHS and RHS
9079 /// are (potentially problematic) pointers.
9081 /// \returns True when the operand is valid to use (even if as an extension).
9082 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9083 Expr *LHSExpr, Expr *RHSExpr) {
9084 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9085 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9086 if (!isLHSPointer && !isRHSPointer) return true;
9088 QualType LHSPointeeTy, RHSPointeeTy;
9089 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9090 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9092 // if both are pointers check if operation is valid wrt address spaces
9093 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9094 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9095 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9096 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9098 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9099 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9100 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9105 // Check for arithmetic on pointers to incomplete types.
9106 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9107 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9108 if (isLHSVoidPtr || isRHSVoidPtr) {
9109 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9110 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9111 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9113 return !S.getLangOpts().CPlusPlus;
9116 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9117 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9118 if (isLHSFuncPtr || isRHSFuncPtr) {
9119 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9120 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9122 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9124 return !S.getLangOpts().CPlusPlus;
9127 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9129 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9135 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9137 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9138 Expr *LHSExpr, Expr *RHSExpr) {
9139 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9140 Expr* IndexExpr = RHSExpr;
9142 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9143 IndexExpr = LHSExpr;
9146 bool IsStringPlusInt = StrExpr &&
9147 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9148 if (!IsStringPlusInt || IndexExpr->isValueDependent())
9151 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9152 Self.Diag(OpLoc, diag::warn_string_plus_int)
9153 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9155 // Only print a fixit for "str" + int, not for int + "str".
9156 if (IndexExpr == RHSExpr) {
9157 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9158 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9159 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9160 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9161 << FixItHint::CreateInsertion(EndLoc, "]");
9163 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9166 /// Emit a warning when adding a char literal to a string.
9167 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9168 Expr *LHSExpr, Expr *RHSExpr) {
9169 const Expr *StringRefExpr = LHSExpr;
9170 const CharacterLiteral *CharExpr =
9171 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9174 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9175 StringRefExpr = RHSExpr;
9178 if (!CharExpr || !StringRefExpr)
9181 const QualType StringType = StringRefExpr->getType();
9183 // Return if not a PointerType.
9184 if (!StringType->isAnyPointerType())
9187 // Return if not a CharacterType.
9188 if (!StringType->getPointeeType()->isAnyCharacterType())
9191 ASTContext &Ctx = Self.getASTContext();
9192 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9194 const QualType CharType = CharExpr->getType();
9195 if (!CharType->isAnyCharacterType() &&
9196 CharType->isIntegerType() &&
9197 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9198 Self.Diag(OpLoc, diag::warn_string_plus_char)
9199 << DiagRange << Ctx.CharTy;
9201 Self.Diag(OpLoc, diag::warn_string_plus_char)
9202 << DiagRange << CharExpr->getType();
9205 // Only print a fixit for str + char, not for char + str.
9206 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9207 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9208 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9209 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9210 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9211 << FixItHint::CreateInsertion(EndLoc, "]");
9213 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9217 /// Emit error when two pointers are incompatible.
9218 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9219 Expr *LHSExpr, Expr *RHSExpr) {
9220 assert(LHSExpr->getType()->isAnyPointerType());
9221 assert(RHSExpr->getType()->isAnyPointerType());
9222 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9223 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9224 << RHSExpr->getSourceRange();
9228 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9229 SourceLocation Loc, BinaryOperatorKind Opc,
9230 QualType* CompLHSTy) {
9231 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9233 if (LHS.get()->getType()->isVectorType() ||
9234 RHS.get()->getType()->isVectorType()) {
9235 QualType compType = CheckVectorOperands(
9236 LHS, RHS, Loc, CompLHSTy,
9237 /*AllowBothBool*/getLangOpts().AltiVec,
9238 /*AllowBoolConversions*/getLangOpts().ZVector);
9239 if (CompLHSTy) *CompLHSTy = compType;
9243 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9244 if (LHS.isInvalid() || RHS.isInvalid())
9247 // Diagnose "string literal" '+' int and string '+' "char literal".
9248 if (Opc == BO_Add) {
9249 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9250 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9253 // handle the common case first (both operands are arithmetic).
9254 if (!compType.isNull() && compType->isArithmeticType()) {
9255 if (CompLHSTy) *CompLHSTy = compType;
9259 // Type-checking. Ultimately the pointer's going to be in PExp;
9260 // note that we bias towards the LHS being the pointer.
9261 Expr *PExp = LHS.get(), *IExp = RHS.get();
9264 if (PExp->getType()->isPointerType()) {
9265 isObjCPointer = false;
9266 } else if (PExp->getType()->isObjCObjectPointerType()) {
9267 isObjCPointer = true;
9269 std::swap(PExp, IExp);
9270 if (PExp->getType()->isPointerType()) {
9271 isObjCPointer = false;
9272 } else if (PExp->getType()->isObjCObjectPointerType()) {
9273 isObjCPointer = true;
9275 return InvalidOperands(Loc, LHS, RHS);
9278 assert(PExp->getType()->isAnyPointerType());
9280 if (!IExp->getType()->isIntegerType())
9281 return InvalidOperands(Loc, LHS, RHS);
9283 // Adding to a null pointer results in undefined behavior.
9284 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9285 Context, Expr::NPC_ValueDependentIsNotNull)) {
9286 // In C++ adding zero to a null pointer is defined.
9287 Expr::EvalResult KnownVal;
9288 if (!getLangOpts().CPlusPlus ||
9289 (!IExp->isValueDependent() &&
9290 (!IExp->EvaluateAsInt(KnownVal, Context) ||
9291 KnownVal.Val.getInt() != 0))) {
9292 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9293 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9294 Context, BO_Add, PExp, IExp);
9295 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9299 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9302 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9305 // Check array bounds for pointer arithemtic
9306 CheckArrayAccess(PExp, IExp);
9309 QualType LHSTy = Context.isPromotableBitField(LHS.get());
9310 if (LHSTy.isNull()) {
9311 LHSTy = LHS.get()->getType();
9312 if (LHSTy->isPromotableIntegerType())
9313 LHSTy = Context.getPromotedIntegerType(LHSTy);
9318 return PExp->getType();
9322 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9324 QualType* CompLHSTy) {
9325 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9327 if (LHS.get()->getType()->isVectorType() ||
9328 RHS.get()->getType()->isVectorType()) {
9329 QualType compType = CheckVectorOperands(
9330 LHS, RHS, Loc, CompLHSTy,
9331 /*AllowBothBool*/getLangOpts().AltiVec,
9332 /*AllowBoolConversions*/getLangOpts().ZVector);
9333 if (CompLHSTy) *CompLHSTy = compType;
9337 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9338 if (LHS.isInvalid() || RHS.isInvalid())
9341 // Enforce type constraints: C99 6.5.6p3.
9343 // Handle the common case first (both operands are arithmetic).
9344 if (!compType.isNull() && compType->isArithmeticType()) {
9345 if (CompLHSTy) *CompLHSTy = compType;
9349 // Either ptr - int or ptr - ptr.
9350 if (LHS.get()->getType()->isAnyPointerType()) {
9351 QualType lpointee = LHS.get()->getType()->getPointeeType();
9353 // Diagnose bad cases where we step over interface counts.
9354 if (LHS.get()->getType()->isObjCObjectPointerType() &&
9355 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9358 // The result type of a pointer-int computation is the pointer type.
9359 if (RHS.get()->getType()->isIntegerType()) {
9360 // Subtracting from a null pointer should produce a warning.
9361 // The last argument to the diagnose call says this doesn't match the
9362 // GNU int-to-pointer idiom.
9363 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9364 Expr::NPC_ValueDependentIsNotNull)) {
9365 // In C++ adding zero to a null pointer is defined.
9366 Expr::EvalResult KnownVal;
9367 if (!getLangOpts().CPlusPlus ||
9368 (!RHS.get()->isValueDependent() &&
9369 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9370 KnownVal.Val.getInt() != 0))) {
9371 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9375 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9378 // Check array bounds for pointer arithemtic
9379 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9380 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9382 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9383 return LHS.get()->getType();
9386 // Handle pointer-pointer subtractions.
9387 if (const PointerType *RHSPTy
9388 = RHS.get()->getType()->getAs<PointerType>()) {
9389 QualType rpointee = RHSPTy->getPointeeType();
9391 if (getLangOpts().CPlusPlus) {
9392 // Pointee types must be the same: C++ [expr.add]
9393 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9394 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9397 // Pointee types must be compatible C99 6.5.6p3
9398 if (!Context.typesAreCompatible(
9399 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9400 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9401 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9406 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9407 LHS.get(), RHS.get()))
9410 // FIXME: Add warnings for nullptr - ptr.
9412 // The pointee type may have zero size. As an extension, a structure or
9413 // union may have zero size or an array may have zero length. In this
9414 // case subtraction does not make sense.
9415 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9416 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9417 if (ElementSize.isZero()) {
9418 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9419 << rpointee.getUnqualifiedType()
9420 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9424 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9425 return Context.getPointerDiffType();
9429 return InvalidOperands(Loc, LHS, RHS);
9432 static bool isScopedEnumerationType(QualType T) {
9433 if (const EnumType *ET = T->getAs<EnumType>())
9434 return ET->getDecl()->isScoped();
9438 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9439 SourceLocation Loc, BinaryOperatorKind Opc,
9441 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9442 // so skip remaining warnings as we don't want to modify values within Sema.
9443 if (S.getLangOpts().OpenCL)
9446 // Check right/shifter operand
9447 Expr::EvalResult RHSResult;
9448 if (RHS.get()->isValueDependent() ||
9449 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9451 llvm::APSInt Right = RHSResult.Val.getInt();
9453 if (Right.isNegative()) {
9454 S.DiagRuntimeBehavior(Loc, RHS.get(),
9455 S.PDiag(diag::warn_shift_negative)
9456 << RHS.get()->getSourceRange());
9459 llvm::APInt LeftBits(Right.getBitWidth(),
9460 S.Context.getTypeSize(LHS.get()->getType()));
9461 if (Right.uge(LeftBits)) {
9462 S.DiagRuntimeBehavior(Loc, RHS.get(),
9463 S.PDiag(diag::warn_shift_gt_typewidth)
9464 << RHS.get()->getSourceRange());
9470 // When left shifting an ICE which is signed, we can check for overflow which
9471 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9472 // integers have defined behavior modulo one more than the maximum value
9473 // representable in the result type, so never warn for those.
9474 Expr::EvalResult LHSResult;
9475 if (LHS.get()->isValueDependent() ||
9476 LHSType->hasUnsignedIntegerRepresentation() ||
9477 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9479 llvm::APSInt Left = LHSResult.Val.getInt();
9481 // If LHS does not have a signed type and non-negative value
9482 // then, the behavior is undefined. Warn about it.
9483 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9484 S.DiagRuntimeBehavior(Loc, LHS.get(),
9485 S.PDiag(diag::warn_shift_lhs_negative)
9486 << LHS.get()->getSourceRange());
9490 llvm::APInt ResultBits =
9491 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9492 if (LeftBits.uge(ResultBits))
9494 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9495 Result = Result.shl(Right);
9497 // Print the bit representation of the signed integer as an unsigned
9498 // hexadecimal number.
9499 SmallString<40> HexResult;
9500 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9502 // If we are only missing a sign bit, this is less likely to result in actual
9503 // bugs -- if the result is cast back to an unsigned type, it will have the
9504 // expected value. Thus we place this behind a different warning that can be
9505 // turned off separately if needed.
9506 if (LeftBits == ResultBits - 1) {
9507 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9508 << HexResult << LHSType
9509 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9513 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9514 << HexResult.str() << Result.getMinSignedBits() << LHSType
9515 << Left.getBitWidth() << LHS.get()->getSourceRange()
9516 << RHS.get()->getSourceRange();
9519 /// Return the resulting type when a vector is shifted
9520 /// by a scalar or vector shift amount.
9521 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9522 SourceLocation Loc, bool IsCompAssign) {
9523 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9524 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9525 !LHS.get()->getType()->isVectorType()) {
9526 S.Diag(Loc, diag::err_shift_rhs_only_vector)
9527 << RHS.get()->getType() << LHS.get()->getType()
9528 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9532 if (!IsCompAssign) {
9533 LHS = S.UsualUnaryConversions(LHS.get());
9534 if (LHS.isInvalid()) return QualType();
9537 RHS = S.UsualUnaryConversions(RHS.get());
9538 if (RHS.isInvalid()) return QualType();
9540 QualType LHSType = LHS.get()->getType();
9541 // Note that LHS might be a scalar because the routine calls not only in
9543 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9544 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9546 // Note that RHS might not be a vector.
9547 QualType RHSType = RHS.get()->getType();
9548 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9549 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9551 // The operands need to be integers.
9552 if (!LHSEleType->isIntegerType()) {
9553 S.Diag(Loc, diag::err_typecheck_expect_int)
9554 << LHS.get()->getType() << LHS.get()->getSourceRange();
9558 if (!RHSEleType->isIntegerType()) {
9559 S.Diag(Loc, diag::err_typecheck_expect_int)
9560 << RHS.get()->getType() << RHS.get()->getSourceRange();
9568 if (LHSEleType != RHSEleType) {
9569 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9570 LHSEleType = RHSEleType;
9573 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9574 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9576 } else if (RHSVecTy) {
9577 // OpenCL v1.1 s6.3.j says that for vector types, the operators
9578 // are applied component-wise. So if RHS is a vector, then ensure
9579 // that the number of elements is the same as LHS...
9580 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9581 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9582 << LHS.get()->getType() << RHS.get()->getType()
9583 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9586 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9587 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9588 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9589 if (LHSBT != RHSBT &&
9590 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9591 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9592 << LHS.get()->getType() << RHS.get()->getType()
9593 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9597 // ...else expand RHS to match the number of elements in LHS.
9599 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9600 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9607 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9608 SourceLocation Loc, BinaryOperatorKind Opc,
9609 bool IsCompAssign) {
9610 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9612 // Vector shifts promote their scalar inputs to vector type.
9613 if (LHS.get()->getType()->isVectorType() ||
9614 RHS.get()->getType()->isVectorType()) {
9615 if (LangOpts.ZVector) {
9616 // The shift operators for the z vector extensions work basically
9617 // like general shifts, except that neither the LHS nor the RHS is
9618 // allowed to be a "vector bool".
9619 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9620 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9621 return InvalidOperands(Loc, LHS, RHS);
9622 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9623 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9624 return InvalidOperands(Loc, LHS, RHS);
9626 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9629 // Shifts don't perform usual arithmetic conversions, they just do integer
9630 // promotions on each operand. C99 6.5.7p3
9632 // For the LHS, do usual unary conversions, but then reset them away
9633 // if this is a compound assignment.
9634 ExprResult OldLHS = LHS;
9635 LHS = UsualUnaryConversions(LHS.get());
9636 if (LHS.isInvalid())
9638 QualType LHSType = LHS.get()->getType();
9639 if (IsCompAssign) LHS = OldLHS;
9641 // The RHS is simpler.
9642 RHS = UsualUnaryConversions(RHS.get());
9643 if (RHS.isInvalid())
9645 QualType RHSType = RHS.get()->getType();
9647 // C99 6.5.7p2: Each of the operands shall have integer type.
9648 if (!LHSType->hasIntegerRepresentation() ||
9649 !RHSType->hasIntegerRepresentation())
9650 return InvalidOperands(Loc, LHS, RHS);
9652 // C++0x: Don't allow scoped enums. FIXME: Use something better than
9653 // hasIntegerRepresentation() above instead of this.
9654 if (isScopedEnumerationType(LHSType) ||
9655 isScopedEnumerationType(RHSType)) {
9656 return InvalidOperands(Loc, LHS, RHS);
9658 // Sanity-check shift operands
9659 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9661 // "The type of the result is that of the promoted left operand."
9665 /// If two different enums are compared, raise a warning.
9666 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9668 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9669 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9671 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9674 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9678 // Ignore anonymous enums.
9679 if (!LHSEnumType->getDecl()->getIdentifier() &&
9680 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9682 if (!RHSEnumType->getDecl()->getIdentifier() &&
9683 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9686 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9689 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9690 << LHSStrippedType << RHSStrippedType
9691 << LHS->getSourceRange() << RHS->getSourceRange();
9694 /// Diagnose bad pointer comparisons.
9695 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9696 ExprResult &LHS, ExprResult &RHS,
9698 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9699 : diag::ext_typecheck_comparison_of_distinct_pointers)
9700 << LHS.get()->getType() << RHS.get()->getType()
9701 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9704 /// Returns false if the pointers are converted to a composite type,
9706 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9707 ExprResult &LHS, ExprResult &RHS) {
9708 // C++ [expr.rel]p2:
9709 // [...] Pointer conversions (4.10) and qualification
9710 // conversions (4.4) are performed on pointer operands (or on
9711 // a pointer operand and a null pointer constant) to bring
9712 // them to their composite pointer type. [...]
9714 // C++ [expr.eq]p1 uses the same notion for (in)equality
9715 // comparisons of pointers.
9717 QualType LHSType = LHS.get()->getType();
9718 QualType RHSType = RHS.get()->getType();
9719 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9720 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9722 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9724 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9725 (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9726 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9728 S.InvalidOperands(Loc, LHS, RHS);
9732 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9733 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9737 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9741 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9742 : diag::ext_typecheck_comparison_of_fptr_to_void)
9743 << LHS.get()->getType() << RHS.get()->getType()
9744 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9747 static bool isObjCObjectLiteral(ExprResult &E) {
9748 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9749 case Stmt::ObjCArrayLiteralClass:
9750 case Stmt::ObjCDictionaryLiteralClass:
9751 case Stmt::ObjCStringLiteralClass:
9752 case Stmt::ObjCBoxedExprClass:
9755 // Note that ObjCBoolLiteral is NOT an object literal!
9760 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9761 const ObjCObjectPointerType *Type =
9762 LHS->getType()->getAs<ObjCObjectPointerType>();
9764 // If this is not actually an Objective-C object, bail out.
9768 // Get the LHS object's interface type.
9769 QualType InterfaceType = Type->getPointeeType();
9771 // If the RHS isn't an Objective-C object, bail out.
9772 if (!RHS->getType()->isObjCObjectPointerType())
9775 // Try to find the -isEqual: method.
9776 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9777 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9781 if (Type->isObjCIdType()) {
9782 // For 'id', just check the global pool.
9783 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9784 /*receiverId=*/true);
9787 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9795 QualType T = Method->parameters()[0]->getType();
9796 if (!T->isObjCObjectPointerType())
9799 QualType R = Method->getReturnType();
9800 if (!R->isScalarType())
9806 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9807 FromE = FromE->IgnoreParenImpCasts();
9808 switch (FromE->getStmtClass()) {
9811 case Stmt::ObjCStringLiteralClass:
9814 case Stmt::ObjCArrayLiteralClass:
9817 case Stmt::ObjCDictionaryLiteralClass:
9818 // "dictionary literal"
9819 return LK_Dictionary;
9820 case Stmt::BlockExprClass:
9822 case Stmt::ObjCBoxedExprClass: {
9823 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9824 switch (Inner->getStmtClass()) {
9825 case Stmt::IntegerLiteralClass:
9826 case Stmt::FloatingLiteralClass:
9827 case Stmt::CharacterLiteralClass:
9828 case Stmt::ObjCBoolLiteralExprClass:
9829 case Stmt::CXXBoolLiteralExprClass:
9830 // "numeric literal"
9832 case Stmt::ImplicitCastExprClass: {
9833 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9834 // Boolean literals can be represented by implicit casts.
9835 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9848 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9849 ExprResult &LHS, ExprResult &RHS,
9850 BinaryOperator::Opcode Opc){
9853 if (isObjCObjectLiteral(LHS)) {
9854 Literal = LHS.get();
9857 Literal = RHS.get();
9861 // Don't warn on comparisons against nil.
9862 Other = Other->IgnoreParenCasts();
9863 if (Other->isNullPointerConstant(S.getASTContext(),
9864 Expr::NPC_ValueDependentIsNotNull))
9867 // This should be kept in sync with warn_objc_literal_comparison.
9868 // LK_String should always be after the other literals, since it has its own
9870 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9871 assert(LiteralKind != Sema::LK_Block);
9872 if (LiteralKind == Sema::LK_None) {
9873 llvm_unreachable("Unknown Objective-C object literal kind");
9876 if (LiteralKind == Sema::LK_String)
9877 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9878 << Literal->getSourceRange();
9880 S.Diag(Loc, diag::warn_objc_literal_comparison)
9881 << LiteralKind << Literal->getSourceRange();
9883 if (BinaryOperator::isEqualityOp(Opc) &&
9884 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9885 SourceLocation Start = LHS.get()->getBeginLoc();
9886 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
9887 CharSourceRange OpRange =
9888 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9890 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9891 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9892 << FixItHint::CreateReplacement(OpRange, " isEqual:")
9893 << FixItHint::CreateInsertion(End, "]");
9897 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9898 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9899 ExprResult &RHS, SourceLocation Loc,
9900 BinaryOperatorKind Opc) {
9901 // Check that left hand side is !something.
9902 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9903 if (!UO || UO->getOpcode() != UO_LNot) return;
9905 // Only check if the right hand side is non-bool arithmetic type.
9906 if (RHS.get()->isKnownToHaveBooleanValue()) return;
9908 // Make sure that the something in !something is not bool.
9909 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9910 if (SubExpr->isKnownToHaveBooleanValue()) return;
9913 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9914 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9915 << Loc << IsBitwiseOp;
9917 // First note suggest !(x < y)
9918 SourceLocation FirstOpen = SubExpr->getBeginLoc();
9919 SourceLocation FirstClose = RHS.get()->getEndLoc();
9920 FirstClose = S.getLocForEndOfToken(FirstClose);
9921 if (FirstClose.isInvalid())
9922 FirstOpen = SourceLocation();
9923 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9925 << FixItHint::CreateInsertion(FirstOpen, "(")
9926 << FixItHint::CreateInsertion(FirstClose, ")");
9928 // Second note suggests (!x) < y
9929 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
9930 SourceLocation SecondClose = LHS.get()->getEndLoc();
9931 SecondClose = S.getLocForEndOfToken(SecondClose);
9932 if (SecondClose.isInvalid())
9933 SecondOpen = SourceLocation();
9934 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9935 << FixItHint::CreateInsertion(SecondOpen, "(")
9936 << FixItHint::CreateInsertion(SecondClose, ")");
9939 // Get the decl for a simple expression: a reference to a variable,
9940 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9941 static ValueDecl *getCompareDecl(Expr *E) {
9942 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9943 return DR->getDecl();
9944 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9945 if (Ivar->isFreeIvar())
9946 return Ivar->getDecl();
9948 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9949 if (Mem->isImplicitAccess())
9950 return Mem->getMemberDecl();
9955 /// Diagnose some forms of syntactically-obvious tautological comparison.
9956 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9957 Expr *LHS, Expr *RHS,
9958 BinaryOperatorKind Opc) {
9959 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9960 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9962 QualType LHSType = LHS->getType();
9963 QualType RHSType = RHS->getType();
9964 if (LHSType->hasFloatingRepresentation() ||
9965 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9966 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
9967 S.inTemplateInstantiation())
9970 // Comparisons between two array types are ill-formed for operator<=>, so
9971 // we shouldn't emit any additional warnings about it.
9972 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9975 // For non-floating point types, check for self-comparisons of the form
9976 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9977 // often indicate logic errors in the program.
9979 // NOTE: Don't warn about comparison expressions resulting from macro
9980 // expansion. Also don't warn about comparisons which are only self
9981 // comparisons within a template instantiation. The warnings should catch
9982 // obvious cases in the definition of the template anyways. The idea is to
9983 // warn when the typed comparison operator will always evaluate to the same
9985 ValueDecl *DL = getCompareDecl(LHSStripped);
9986 ValueDecl *DR = getCompareDecl(RHSStripped);
9987 if (DL && DR && declaresSameEntity(DL, DR)) {
9990 case BO_EQ: case BO_LE: case BO_GE:
9993 case BO_NE: case BO_LT: case BO_GT:
9997 Result = "'std::strong_ordering::equal'";
10002 S.DiagRuntimeBehavior(Loc, nullptr,
10003 S.PDiag(diag::warn_comparison_always)
10004 << 0 /*self-comparison*/ << !Result.empty()
10006 } else if (DL && DR &&
10007 DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10008 !DL->isWeak() && !DR->isWeak()) {
10009 // What is it always going to evaluate to?
10012 case BO_EQ: // e.g. array1 == array2
10015 case BO_NE: // e.g. array1 != array2
10018 default: // e.g. array1 <= array2
10019 // The best we can say is 'a constant'
10022 S.DiagRuntimeBehavior(Loc, nullptr,
10023 S.PDiag(diag::warn_comparison_always)
10024 << 1 /*array comparison*/
10025 << !Result.empty() << Result);
10028 if (isa<CastExpr>(LHSStripped))
10029 LHSStripped = LHSStripped->IgnoreParenCasts();
10030 if (isa<CastExpr>(RHSStripped))
10031 RHSStripped = RHSStripped->IgnoreParenCasts();
10033 // Warn about comparisons against a string constant (unless the other
10034 // operand is null); the user probably wants strcmp.
10035 Expr *LiteralString = nullptr;
10036 Expr *LiteralStringStripped = nullptr;
10037 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10038 !RHSStripped->isNullPointerConstant(S.Context,
10039 Expr::NPC_ValueDependentIsNull)) {
10040 LiteralString = LHS;
10041 LiteralStringStripped = LHSStripped;
10042 } else if ((isa<StringLiteral>(RHSStripped) ||
10043 isa<ObjCEncodeExpr>(RHSStripped)) &&
10044 !LHSStripped->isNullPointerConstant(S.Context,
10045 Expr::NPC_ValueDependentIsNull)) {
10046 LiteralString = RHS;
10047 LiteralStringStripped = RHSStripped;
10050 if (LiteralString) {
10051 S.DiagRuntimeBehavior(Loc, nullptr,
10052 S.PDiag(diag::warn_stringcompare)
10053 << isa<ObjCEncodeExpr>(LiteralStringStripped)
10054 << LiteralString->getSourceRange());
10058 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10062 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10065 llvm_unreachable("unhandled cast kind");
10067 case CK_UserDefinedConversion:
10068 return ICK_Identity;
10069 case CK_LValueToRValue:
10070 return ICK_Lvalue_To_Rvalue;
10071 case CK_ArrayToPointerDecay:
10072 return ICK_Array_To_Pointer;
10073 case CK_FunctionToPointerDecay:
10074 return ICK_Function_To_Pointer;
10075 case CK_IntegralCast:
10076 return ICK_Integral_Conversion;
10077 case CK_FloatingCast:
10078 return ICK_Floating_Conversion;
10079 case CK_IntegralToFloating:
10080 case CK_FloatingToIntegral:
10081 return ICK_Floating_Integral;
10082 case CK_IntegralComplexCast:
10083 case CK_FloatingComplexCast:
10084 case CK_FloatingComplexToIntegralComplex:
10085 case CK_IntegralComplexToFloatingComplex:
10086 return ICK_Complex_Conversion;
10087 case CK_FloatingComplexToReal:
10088 case CK_FloatingRealToComplex:
10089 case CK_IntegralComplexToReal:
10090 case CK_IntegralRealToComplex:
10091 return ICK_Complex_Real;
10095 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10097 SourceLocation Loc) {
10098 // Check for a narrowing implicit conversion.
10099 StandardConversionSequence SCS;
10100 SCS.setAsIdentityConversion();
10101 SCS.setToType(0, FromType);
10102 SCS.setToType(1, ToType);
10103 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10104 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10106 APValue PreNarrowingValue;
10107 QualType PreNarrowingType;
10108 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10110 /*IgnoreFloatToIntegralConversion*/ true)) {
10111 case NK_Dependent_Narrowing:
10112 // Implicit conversion to a narrower type, but the expression is
10113 // value-dependent so we can't tell whether it's actually narrowing.
10114 case NK_Not_Narrowing:
10117 case NK_Constant_Narrowing:
10118 // Implicit conversion to a narrower type, and the value is not a constant
10120 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10122 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10125 case NK_Variable_Narrowing:
10126 // Implicit conversion to a narrower type, and the value is not a constant
10128 case NK_Type_Narrowing:
10129 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10130 << /*Constant*/ 0 << FromType << ToType;
10131 // TODO: It's not a constant expression, but what if the user intended it
10132 // to be? Can we produce notes to help them figure out why it isn't?
10135 llvm_unreachable("unhandled case in switch");
10138 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10141 SourceLocation Loc) {
10142 using CCT = ComparisonCategoryType;
10144 QualType LHSType = LHS.get()->getType();
10145 QualType RHSType = RHS.get()->getType();
10146 // Dig out the original argument type and expression before implicit casts
10147 // were applied. These are the types/expressions we need to check the
10148 // [expr.spaceship] requirements against.
10149 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10150 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10151 QualType LHSStrippedType = LHSStripped.get()->getType();
10152 QualType RHSStrippedType = RHSStripped.get()->getType();
10154 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10155 // other is not, the program is ill-formed.
10156 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10157 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10161 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10162 RHSStrippedType->isEnumeralType();
10163 if (NumEnumArgs == 1) {
10164 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10165 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10166 if (OtherTy->hasFloatingRepresentation()) {
10167 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10171 if (NumEnumArgs == 2) {
10172 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10173 // type E, the operator yields the result of converting the operands
10174 // to the underlying type of E and applying <=> to the converted operands.
10175 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10176 S.InvalidOperands(Loc, LHS, RHS);
10180 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10181 assert(IntType->isArithmeticType());
10183 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10184 // promote the boolean type, and all other promotable integer types, to
10186 if (IntType->isPromotableIntegerType())
10187 IntType = S.Context.getPromotedIntegerType(IntType);
10189 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10190 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10191 LHSType = RHSType = IntType;
10194 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10195 // usual arithmetic conversions are applied to the operands.
10196 QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10197 if (LHS.isInvalid() || RHS.isInvalid())
10200 return S.InvalidOperands(Loc, LHS, RHS);
10201 assert(Type->isArithmeticType() || Type->isEnumeralType());
10203 bool HasNarrowing = checkThreeWayNarrowingConversion(
10204 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10205 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10206 RHS.get()->getBeginLoc());
10210 assert(!Type.isNull() && "composite type for <=> has not been set");
10212 auto TypeKind = [&]() {
10213 if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10214 if (CT->getElementType()->hasFloatingRepresentation())
10215 return CCT::WeakEquality;
10216 return CCT::StrongEquality;
10218 if (Type->isIntegralOrEnumerationType())
10219 return CCT::StrongOrdering;
10220 if (Type->hasFloatingRepresentation())
10221 return CCT::PartialOrdering;
10222 llvm_unreachable("other types are unimplemented");
10225 return S.CheckComparisonCategoryType(TypeKind, Loc);
10228 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10230 SourceLocation Loc,
10231 BinaryOperatorKind Opc) {
10233 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10235 // C99 6.5.8p3 / C99 6.5.9p4
10236 QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10237 if (LHS.isInvalid() || RHS.isInvalid())
10240 return S.InvalidOperands(Loc, LHS, RHS);
10241 assert(Type->isArithmeticType() || Type->isEnumeralType());
10243 checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10245 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10246 return S.InvalidOperands(Loc, LHS, RHS);
10248 // Check for comparisons of floating point operands using != and ==.
10249 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10250 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10252 // The result of comparisons is 'bool' in C++, 'int' in C.
10253 return S.Context.getLogicalOperationType();
10256 // C99 6.5.8, C++ [expr.rel]
10257 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10258 SourceLocation Loc,
10259 BinaryOperatorKind Opc) {
10260 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10261 bool IsThreeWay = Opc == BO_Cmp;
10262 auto IsAnyPointerType = [](ExprResult E) {
10263 QualType Ty = E.get()->getType();
10264 return Ty->isPointerType() || Ty->isMemberPointerType();
10267 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10268 // type, array-to-pointer, ..., conversions are performed on both operands to
10269 // bring them to their composite type.
10270 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10271 // any type-related checks.
10272 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10273 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10274 if (LHS.isInvalid())
10276 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10277 if (RHS.isInvalid())
10280 LHS = DefaultLvalueConversion(LHS.get());
10281 if (LHS.isInvalid())
10283 RHS = DefaultLvalueConversion(RHS.get());
10284 if (RHS.isInvalid())
10288 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10290 // Handle vector comparisons separately.
10291 if (LHS.get()->getType()->isVectorType() ||
10292 RHS.get()->getType()->isVectorType())
10293 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10295 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10296 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10298 QualType LHSType = LHS.get()->getType();
10299 QualType RHSType = RHS.get()->getType();
10300 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10301 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10302 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10304 const Expr::NullPointerConstantKind LHSNullKind =
10305 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10306 const Expr::NullPointerConstantKind RHSNullKind =
10307 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10308 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10309 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10311 auto computeResultTy = [&]() {
10313 return Context.getLogicalOperationType();
10314 assert(getLangOpts().CPlusPlus);
10315 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10317 QualType CompositeTy = LHS.get()->getType();
10318 assert(!CompositeTy->isReferenceType());
10320 auto buildResultTy = [&](ComparisonCategoryType Kind) {
10321 return CheckComparisonCategoryType(Kind, Loc);
10324 // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10325 // pointer type, a pointer-to-member type, or std::nullptr_t, the
10326 // result is of type std::strong_equality
10327 if (CompositeTy->isFunctionPointerType() ||
10328 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10329 // FIXME: consider making the function pointer case produce
10330 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10331 // and direction polls
10332 return buildResultTy(ComparisonCategoryType::StrongEquality);
10334 // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10335 // pointer type, p <=> q is of type std::strong_ordering.
10336 if (CompositeTy->isPointerType()) {
10337 // P0946R0: Comparisons between a null pointer constant and an object
10338 // pointer result in std::strong_equality
10339 if (LHSIsNull != RHSIsNull)
10340 return buildResultTy(ComparisonCategoryType::StrongEquality);
10341 return buildResultTy(ComparisonCategoryType::StrongOrdering);
10343 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10344 // TODO: Extend support for operator<=> to ObjC types.
10345 return InvalidOperands(Loc, LHS, RHS);
10349 if (!IsRelational && LHSIsNull != RHSIsNull) {
10350 bool IsEquality = Opc == BO_EQ;
10352 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10353 RHS.get()->getSourceRange());
10355 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10356 LHS.get()->getSourceRange());
10359 if ((LHSType->isIntegerType() && !LHSIsNull) ||
10360 (RHSType->isIntegerType() && !RHSIsNull)) {
10361 // Skip normal pointer conversion checks in this case; we have better
10362 // diagnostics for this below.
10363 } else if (getLangOpts().CPlusPlus) {
10364 // Equality comparison of a function pointer to a void pointer is invalid,
10365 // but we allow it as an extension.
10366 // FIXME: If we really want to allow this, should it be part of composite
10367 // pointer type computation so it works in conditionals too?
10368 if (!IsRelational &&
10369 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10370 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10371 // This is a gcc extension compatibility comparison.
10372 // In a SFINAE context, we treat this as a hard error to maintain
10373 // conformance with the C++ standard.
10374 diagnoseFunctionPointerToVoidComparison(
10375 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10377 if (isSFINAEContext())
10380 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10381 return computeResultTy();
10384 // C++ [expr.eq]p2:
10385 // If at least one operand is a pointer [...] bring them to their
10386 // composite pointer type.
10387 // C++ [expr.spaceship]p6
10388 // If at least one of the operands is of pointer type, [...] bring them
10389 // to their composite pointer type.
10390 // C++ [expr.rel]p2:
10391 // If both operands are pointers, [...] bring them to their composite
10393 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10394 (IsRelational ? 2 : 1) &&
10395 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10396 RHSType->isObjCObjectPointerType()))) {
10397 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10399 return computeResultTy();
10401 } else if (LHSType->isPointerType() &&
10402 RHSType->isPointerType()) { // C99 6.5.8p2
10403 // All of the following pointer-related warnings are GCC extensions, except
10404 // when handling null pointer constants.
10405 QualType LCanPointeeTy =
10406 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10407 QualType RCanPointeeTy =
10408 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10410 // C99 6.5.9p2 and C99 6.5.8p2
10411 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10412 RCanPointeeTy.getUnqualifiedType())) {
10413 // Valid unless a relational comparison of function pointers
10414 if (IsRelational && LCanPointeeTy->isFunctionType()) {
10415 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10416 << LHSType << RHSType << LHS.get()->getSourceRange()
10417 << RHS.get()->getSourceRange();
10419 } else if (!IsRelational &&
10420 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10421 // Valid unless comparison between non-null pointer and function pointer
10422 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10423 && !LHSIsNull && !RHSIsNull)
10424 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10428 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10430 if (LCanPointeeTy != RCanPointeeTy) {
10431 // Treat NULL constant as a special case in OpenCL.
10432 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10433 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10434 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10436 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10437 << LHSType << RHSType << 0 /* comparison */
10438 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10441 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10442 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10443 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10445 if (LHSIsNull && !RHSIsNull)
10446 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10448 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10450 return computeResultTy();
10453 if (getLangOpts().CPlusPlus) {
10454 // C++ [expr.eq]p4:
10455 // Two operands of type std::nullptr_t or one operand of type
10456 // std::nullptr_t and the other a null pointer constant compare equal.
10457 if (!IsRelational && LHSIsNull && RHSIsNull) {
10458 if (LHSType->isNullPtrType()) {
10459 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10460 return computeResultTy();
10462 if (RHSType->isNullPtrType()) {
10463 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10464 return computeResultTy();
10468 // Comparison of Objective-C pointers and block pointers against nullptr_t.
10469 // These aren't covered by the composite pointer type rules.
10470 if (!IsRelational && RHSType->isNullPtrType() &&
10471 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10472 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10473 return computeResultTy();
10475 if (!IsRelational && LHSType->isNullPtrType() &&
10476 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10477 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10478 return computeResultTy();
10481 if (IsRelational &&
10482 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10483 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10484 // HACK: Relational comparison of nullptr_t against a pointer type is
10485 // invalid per DR583, but we allow it within std::less<> and friends,
10486 // since otherwise common uses of it break.
10487 // FIXME: Consider removing this hack once LWG fixes std::less<> and
10488 // friends to have std::nullptr_t overload candidates.
10489 DeclContext *DC = CurContext;
10490 if (isa<FunctionDecl>(DC))
10491 DC = DC->getParent();
10492 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10493 if (CTSD->isInStdNamespace() &&
10494 llvm::StringSwitch<bool>(CTSD->getName())
10495 .Cases("less", "less_equal", "greater", "greater_equal", true)
10497 if (RHSType->isNullPtrType())
10498 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10500 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10501 return computeResultTy();
10506 // C++ [expr.eq]p2:
10507 // If at least one operand is a pointer to member, [...] bring them to
10508 // their composite pointer type.
10509 if (!IsRelational &&
10510 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10511 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10514 return computeResultTy();
10518 // Handle block pointer types.
10519 if (!IsRelational && LHSType->isBlockPointerType() &&
10520 RHSType->isBlockPointerType()) {
10521 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10522 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10524 if (!LHSIsNull && !RHSIsNull &&
10525 !Context.typesAreCompatible(lpointee, rpointee)) {
10526 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10527 << LHSType << RHSType << LHS.get()->getSourceRange()
10528 << RHS.get()->getSourceRange();
10530 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10531 return computeResultTy();
10534 // Allow block pointers to be compared with null pointer constants.
10536 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10537 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10538 if (!LHSIsNull && !RHSIsNull) {
10539 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10540 ->getPointeeType()->isVoidType())
10541 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10542 ->getPointeeType()->isVoidType())))
10543 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10544 << LHSType << RHSType << LHS.get()->getSourceRange()
10545 << RHS.get()->getSourceRange();
10547 if (LHSIsNull && !RHSIsNull)
10548 LHS = ImpCastExprToType(LHS.get(), RHSType,
10549 RHSType->isPointerType() ? CK_BitCast
10550 : CK_AnyPointerToBlockPointerCast);
10552 RHS = ImpCastExprToType(RHS.get(), LHSType,
10553 LHSType->isPointerType() ? CK_BitCast
10554 : CK_AnyPointerToBlockPointerCast);
10555 return computeResultTy();
10558 if (LHSType->isObjCObjectPointerType() ||
10559 RHSType->isObjCObjectPointerType()) {
10560 const PointerType *LPT = LHSType->getAs<PointerType>();
10561 const PointerType *RPT = RHSType->getAs<PointerType>();
10563 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10564 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10566 if (!LPtrToVoid && !RPtrToVoid &&
10567 !Context.typesAreCompatible(LHSType, RHSType)) {
10568 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10571 if (LHSIsNull && !RHSIsNull) {
10572 Expr *E = LHS.get();
10573 if (getLangOpts().ObjCAutoRefCount)
10574 CheckObjCConversion(SourceRange(), RHSType, E,
10575 CCK_ImplicitConversion);
10576 LHS = ImpCastExprToType(E, RHSType,
10577 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10580 Expr *E = RHS.get();
10581 if (getLangOpts().ObjCAutoRefCount)
10582 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10584 /*DiagnoseCFAudited=*/false, Opc);
10585 RHS = ImpCastExprToType(E, LHSType,
10586 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10588 return computeResultTy();
10590 if (LHSType->isObjCObjectPointerType() &&
10591 RHSType->isObjCObjectPointerType()) {
10592 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10593 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10595 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10596 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10598 if (LHSIsNull && !RHSIsNull)
10599 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10601 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10602 return computeResultTy();
10605 if (!IsRelational && LHSType->isBlockPointerType() &&
10606 RHSType->isBlockCompatibleObjCPointerType(Context)) {
10607 LHS = ImpCastExprToType(LHS.get(), RHSType,
10608 CK_BlockPointerToObjCPointerCast);
10609 return computeResultTy();
10610 } else if (!IsRelational &&
10611 LHSType->isBlockCompatibleObjCPointerType(Context) &&
10612 RHSType->isBlockPointerType()) {
10613 RHS = ImpCastExprToType(RHS.get(), LHSType,
10614 CK_BlockPointerToObjCPointerCast);
10615 return computeResultTy();
10618 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10619 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10620 unsigned DiagID = 0;
10621 bool isError = false;
10622 if (LangOpts.DebuggerSupport) {
10623 // Under a debugger, allow the comparison of pointers to integers,
10624 // since users tend to want to compare addresses.
10625 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10626 (RHSIsNull && RHSType->isIntegerType())) {
10627 if (IsRelational) {
10628 isError = getLangOpts().CPlusPlus;
10630 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10631 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10633 } else if (getLangOpts().CPlusPlus) {
10634 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10636 } else if (IsRelational)
10637 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10639 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10643 << LHSType << RHSType << LHS.get()->getSourceRange()
10644 << RHS.get()->getSourceRange();
10649 if (LHSType->isIntegerType())
10650 LHS = ImpCastExprToType(LHS.get(), RHSType,
10651 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10653 RHS = ImpCastExprToType(RHS.get(), LHSType,
10654 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10655 return computeResultTy();
10658 // Handle block pointers.
10659 if (!IsRelational && RHSIsNull
10660 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10661 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10662 return computeResultTy();
10664 if (!IsRelational && LHSIsNull
10665 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10666 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10667 return computeResultTy();
10670 if (getLangOpts().OpenCLVersion >= 200) {
10671 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10672 return computeResultTy();
10675 if (LHSType->isQueueT() && RHSType->isQueueT()) {
10676 return computeResultTy();
10679 if (LHSIsNull && RHSType->isQueueT()) {
10680 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10681 return computeResultTy();
10684 if (LHSType->isQueueT() && RHSIsNull) {
10685 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10686 return computeResultTy();
10690 return InvalidOperands(Loc, LHS, RHS);
10693 // Return a signed ext_vector_type that is of identical size and number of
10694 // elements. For floating point vectors, return an integer type of identical
10695 // size and number of elements. In the non ext_vector_type case, search from
10696 // the largest type to the smallest type to avoid cases where long long == long,
10697 // where long gets picked over long long.
10698 QualType Sema::GetSignedVectorType(QualType V) {
10699 const VectorType *VTy = V->getAs<VectorType>();
10700 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10702 if (isa<ExtVectorType>(VTy)) {
10703 if (TypeSize == Context.getTypeSize(Context.CharTy))
10704 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10705 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10706 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10707 else if (TypeSize == Context.getTypeSize(Context.IntTy))
10708 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10709 else if (TypeSize == Context.getTypeSize(Context.LongTy))
10710 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10711 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10712 "Unhandled vector element size in vector compare");
10713 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10716 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10717 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10718 VectorType::GenericVector);
10719 else if (TypeSize == Context.getTypeSize(Context.LongTy))
10720 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10721 VectorType::GenericVector);
10722 else if (TypeSize == Context.getTypeSize(Context.IntTy))
10723 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10724 VectorType::GenericVector);
10725 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10726 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10727 VectorType::GenericVector);
10728 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10729 "Unhandled vector element size in vector compare");
10730 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10731 VectorType::GenericVector);
10734 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10735 /// operates on extended vector types. Instead of producing an IntTy result,
10736 /// like a scalar comparison, a vector comparison produces a vector of integer
10738 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10739 SourceLocation Loc,
10740 BinaryOperatorKind Opc) {
10741 // Check to make sure we're operating on vectors of the same type and width,
10742 // Allowing one side to be a scalar of element type.
10743 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10744 /*AllowBothBool*/true,
10745 /*AllowBoolConversions*/getLangOpts().ZVector);
10746 if (vType.isNull())
10749 QualType LHSType = LHS.get()->getType();
10751 // If AltiVec, the comparison results in a numeric type, i.e.
10752 // bool for C++, int for C
10753 if (getLangOpts().AltiVec &&
10754 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10755 return Context.getLogicalOperationType();
10757 // For non-floating point types, check for self-comparisons of the form
10758 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
10759 // often indicate logic errors in the program.
10760 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10762 // Check for comparisons of floating point operands using != and ==.
10763 if (BinaryOperator::isEqualityOp(Opc) &&
10764 LHSType->hasFloatingRepresentation()) {
10765 assert(RHS.get()->getType()->hasFloatingRepresentation());
10766 CheckFloatComparison(Loc, LHS.get(), RHS.get());
10769 // Return a signed type for the vector.
10770 return GetSignedVectorType(vType);
10773 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10774 SourceLocation Loc) {
10775 // Ensure that either both operands are of the same vector type, or
10776 // one operand is of a vector type and the other is of its element type.
10777 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10778 /*AllowBothBool*/true,
10779 /*AllowBoolConversions*/false);
10780 if (vType.isNull())
10781 return InvalidOperands(Loc, LHS, RHS);
10782 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10783 vType->hasFloatingRepresentation())
10784 return InvalidOperands(Loc, LHS, RHS);
10785 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10786 // usage of the logical operators && and || with vectors in C. This
10787 // check could be notionally dropped.
10788 if (!getLangOpts().CPlusPlus &&
10789 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10790 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10792 return GetSignedVectorType(LHS.get()->getType());
10795 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10796 SourceLocation Loc,
10797 BinaryOperatorKind Opc) {
10798 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10800 bool IsCompAssign =
10801 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10803 if (LHS.get()->getType()->isVectorType() ||
10804 RHS.get()->getType()->isVectorType()) {
10805 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10806 RHS.get()->getType()->hasIntegerRepresentation())
10807 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10808 /*AllowBothBool*/true,
10809 /*AllowBoolConversions*/getLangOpts().ZVector);
10810 return InvalidOperands(Loc, LHS, RHS);
10814 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10816 ExprResult LHSResult = LHS, RHSResult = RHS;
10817 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10819 if (LHSResult.isInvalid() || RHSResult.isInvalid())
10821 LHS = LHSResult.get();
10822 RHS = RHSResult.get();
10824 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10826 return InvalidOperands(Loc, LHS, RHS);
10830 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10831 SourceLocation Loc,
10832 BinaryOperatorKind Opc) {
10833 // Check vector operands differently.
10834 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10835 return CheckVectorLogicalOperands(LHS, RHS, Loc);
10837 // Diagnose cases where the user write a logical and/or but probably meant a
10838 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
10840 if (LHS.get()->getType()->isIntegerType() &&
10841 !LHS.get()->getType()->isBooleanType() &&
10842 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10843 // Don't warn in macros or template instantiations.
10844 !Loc.isMacroID() && !inTemplateInstantiation()) {
10845 // If the RHS can be constant folded, and if it constant folds to something
10846 // that isn't 0 or 1 (which indicate a potential logical operation that
10847 // happened to fold to true/false) then warn.
10848 // Parens on the RHS are ignored.
10849 Expr::EvalResult EVResult;
10850 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
10851 llvm::APSInt Result = EVResult.Val.getInt();
10852 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10853 !RHS.get()->getExprLoc().isMacroID()) ||
10854 (Result != 0 && Result != 1)) {
10855 Diag(Loc, diag::warn_logical_instead_of_bitwise)
10856 << RHS.get()->getSourceRange()
10857 << (Opc == BO_LAnd ? "&&" : "||");
10858 // Suggest replacing the logical operator with the bitwise version
10859 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10860 << (Opc == BO_LAnd ? "&" : "|")
10861 << FixItHint::CreateReplacement(SourceRange(
10862 Loc, getLocForEndOfToken(Loc)),
10863 Opc == BO_LAnd ? "&" : "|");
10864 if (Opc == BO_LAnd)
10865 // Suggest replacing "Foo() && kNonZero" with "Foo()"
10866 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10867 << FixItHint::CreateRemoval(
10868 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10869 RHS.get()->getEndLoc()));
10874 if (!Context.getLangOpts().CPlusPlus) {
10875 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10876 // not operate on the built-in scalar and vector float types.
10877 if (Context.getLangOpts().OpenCL &&
10878 Context.getLangOpts().OpenCLVersion < 120) {
10879 if (LHS.get()->getType()->isFloatingType() ||
10880 RHS.get()->getType()->isFloatingType())
10881 return InvalidOperands(Loc, LHS, RHS);
10884 LHS = UsualUnaryConversions(LHS.get());
10885 if (LHS.isInvalid())
10888 RHS = UsualUnaryConversions(RHS.get());
10889 if (RHS.isInvalid())
10892 if (!LHS.get()->getType()->isScalarType() ||
10893 !RHS.get()->getType()->isScalarType())
10894 return InvalidOperands(Loc, LHS, RHS);
10896 return Context.IntTy;
10899 // The following is safe because we only use this method for
10900 // non-overloadable operands.
10902 // C++ [expr.log.and]p1
10903 // C++ [expr.log.or]p1
10904 // The operands are both contextually converted to type bool.
10905 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10906 if (LHSRes.isInvalid())
10907 return InvalidOperands(Loc, LHS, RHS);
10910 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10911 if (RHSRes.isInvalid())
10912 return InvalidOperands(Loc, LHS, RHS);
10915 // C++ [expr.log.and]p2
10916 // C++ [expr.log.or]p2
10917 // The result is a bool.
10918 return Context.BoolTy;
10921 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10922 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10923 if (!ME) return false;
10924 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10925 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10926 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10927 if (!Base) return false;
10928 return Base->getMethodDecl() != nullptr;
10931 /// Is the given expression (which must be 'const') a reference to a
10932 /// variable which was originally non-const, but which has become
10933 /// 'const' due to being captured within a block?
10934 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10935 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10936 assert(E->isLValue() && E->getType().isConstQualified());
10937 E = E->IgnoreParens();
10939 // Must be a reference to a declaration from an enclosing scope.
10940 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10941 if (!DRE) return NCCK_None;
10942 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10944 // The declaration must be a variable which is not declared 'const'.
10945 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10946 if (!var) return NCCK_None;
10947 if (var->getType().isConstQualified()) return NCCK_None;
10948 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10950 // Decide whether the first capture was for a block or a lambda.
10951 DeclContext *DC = S.CurContext, *Prev = nullptr;
10952 // Decide whether the first capture was for a block or a lambda.
10954 // For init-capture, it is possible that the variable belongs to the
10955 // template pattern of the current context.
10956 if (auto *FD = dyn_cast<FunctionDecl>(DC))
10957 if (var->isInitCapture() &&
10958 FD->getTemplateInstantiationPattern() == var->getDeclContext())
10960 if (DC == var->getDeclContext())
10963 DC = DC->getParent();
10965 // Unless we have an init-capture, we've gone one step too far.
10966 if (!var->isInitCapture())
10968 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10971 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10972 Ty = Ty.getNonReferenceType();
10973 if (IsDereference && Ty->isPointerType())
10974 Ty = Ty->getPointeeType();
10975 return !Ty.isConstQualified();
10978 // Update err_typecheck_assign_const and note_typecheck_assign_const
10979 // when this enum is changed.
10986 ConstUnknown, // Keep as last element
10989 /// Emit the "read-only variable not assignable" error and print notes to give
10990 /// more information about why the variable is not assignable, such as pointing
10991 /// to the declaration of a const variable, showing that a method is const, or
10992 /// that the function is returning a const reference.
10993 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10994 SourceLocation Loc) {
10995 SourceRange ExprRange = E->getSourceRange();
10997 // Only emit one error on the first const found. All other consts will emit
10998 // a note to the error.
10999 bool DiagnosticEmitted = false;
11001 // Track if the current expression is the result of a dereference, and if the
11002 // next checked expression is the result of a dereference.
11003 bool IsDereference = false;
11004 bool NextIsDereference = false;
11006 // Loop to process MemberExpr chains.
11008 IsDereference = NextIsDereference;
11010 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11011 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11012 NextIsDereference = ME->isArrow();
11013 const ValueDecl *VD = ME->getMemberDecl();
11014 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11015 // Mutable fields can be modified even if the class is const.
11016 if (Field->isMutable()) {
11017 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11021 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11022 if (!DiagnosticEmitted) {
11023 S.Diag(Loc, diag::err_typecheck_assign_const)
11024 << ExprRange << ConstMember << false /*static*/ << Field
11025 << Field->getType();
11026 DiagnosticEmitted = true;
11028 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11029 << ConstMember << false /*static*/ << Field << Field->getType()
11030 << Field->getSourceRange();
11034 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11035 if (VDecl->getType().isConstQualified()) {
11036 if (!DiagnosticEmitted) {
11037 S.Diag(Loc, diag::err_typecheck_assign_const)
11038 << ExprRange << ConstMember << true /*static*/ << VDecl
11039 << VDecl->getType();
11040 DiagnosticEmitted = true;
11042 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11043 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11044 << VDecl->getSourceRange();
11046 // Static fields do not inherit constness from parents.
11049 break; // End MemberExpr
11050 } else if (const ArraySubscriptExpr *ASE =
11051 dyn_cast<ArraySubscriptExpr>(E)) {
11052 E = ASE->getBase()->IgnoreParenImpCasts();
11054 } else if (const ExtVectorElementExpr *EVE =
11055 dyn_cast<ExtVectorElementExpr>(E)) {
11056 E = EVE->getBase()->IgnoreParenImpCasts();
11062 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11064 const FunctionDecl *FD = CE->getDirectCallee();
11065 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11066 if (!DiagnosticEmitted) {
11067 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11068 << ConstFunction << FD;
11069 DiagnosticEmitted = true;
11071 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11072 diag::note_typecheck_assign_const)
11073 << ConstFunction << FD << FD->getReturnType()
11074 << FD->getReturnTypeSourceRange();
11076 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11077 // Point to variable declaration.
11078 if (const ValueDecl *VD = DRE->getDecl()) {
11079 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11080 if (!DiagnosticEmitted) {
11081 S.Diag(Loc, diag::err_typecheck_assign_const)
11082 << ExprRange << ConstVariable << VD << VD->getType();
11083 DiagnosticEmitted = true;
11085 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11086 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11089 } else if (isa<CXXThisExpr>(E)) {
11090 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11091 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11092 if (MD->isConst()) {
11093 if (!DiagnosticEmitted) {
11094 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11095 << ConstMethod << MD;
11096 DiagnosticEmitted = true;
11098 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11099 << ConstMethod << MD << MD->getSourceRange();
11105 if (DiagnosticEmitted)
11108 // Can't determine a more specific message, so display the generic error.
11109 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11112 enum OriginalExprKind {
11118 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11119 const RecordType *Ty,
11120 SourceLocation Loc, SourceRange Range,
11121 OriginalExprKind OEK,
11122 bool &DiagnosticEmitted) {
11123 std::vector<const RecordType *> RecordTypeList;
11124 RecordTypeList.push_back(Ty);
11125 unsigned NextToCheckIndex = 0;
11126 // We walk the record hierarchy breadth-first to ensure that we print
11127 // diagnostics in field nesting order.
11128 while (RecordTypeList.size() > NextToCheckIndex) {
11129 bool IsNested = NextToCheckIndex > 0;
11130 for (const FieldDecl *Field :
11131 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11132 // First, check every field for constness.
11133 QualType FieldTy = Field->getType();
11134 if (FieldTy.isConstQualified()) {
11135 if (!DiagnosticEmitted) {
11136 S.Diag(Loc, diag::err_typecheck_assign_const)
11137 << Range << NestedConstMember << OEK << VD
11138 << IsNested << Field;
11139 DiagnosticEmitted = true;
11141 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11142 << NestedConstMember << IsNested << Field
11143 << FieldTy << Field->getSourceRange();
11146 // Then we append it to the list to check next in order.
11147 FieldTy = FieldTy.getCanonicalType();
11148 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11149 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11150 RecordTypeList.push_back(FieldRecTy);
11153 ++NextToCheckIndex;
11157 /// Emit an error for the case where a record we are trying to assign to has a
11158 /// const-qualified field somewhere in its hierarchy.
11159 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11160 SourceLocation Loc) {
11161 QualType Ty = E->getType();
11162 assert(Ty->isRecordType() && "lvalue was not record?");
11163 SourceRange Range = E->getSourceRange();
11164 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11165 bool DiagEmitted = false;
11167 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11168 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11169 Range, OEK_Member, DiagEmitted);
11170 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11171 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11172 Range, OEK_Variable, DiagEmitted);
11174 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11175 Range, OEK_LValue, DiagEmitted);
11177 DiagnoseConstAssignment(S, E, Loc);
11180 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
11181 /// emit an error and return true. If so, return false.
11182 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11183 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11185 S.CheckShadowingDeclModification(E, Loc);
11187 SourceLocation OrigLoc = Loc;
11188 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11190 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11191 IsLV = Expr::MLV_InvalidMessageExpression;
11192 if (IsLV == Expr::MLV_Valid)
11195 unsigned DiagID = 0;
11196 bool NeedType = false;
11197 switch (IsLV) { // C99 6.5.16p2
11198 case Expr::MLV_ConstQualified:
11199 // Use a specialized diagnostic when we're assigning to an object
11200 // from an enclosing function or block.
11201 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11202 if (NCCK == NCCK_Block)
11203 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11205 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11209 // In ARC, use some specialized diagnostics for occasions where we
11210 // infer 'const'. These are always pseudo-strong variables.
11211 if (S.getLangOpts().ObjCAutoRefCount) {
11212 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11213 if (declRef && isa<VarDecl>(declRef->getDecl())) {
11214 VarDecl *var = cast<VarDecl>(declRef->getDecl());
11216 // Use the normal diagnostic if it's pseudo-__strong but the
11217 // user actually wrote 'const'.
11218 if (var->isARCPseudoStrong() &&
11219 (!var->getTypeSourceInfo() ||
11220 !var->getTypeSourceInfo()->getType().isConstQualified())) {
11221 // There are three pseudo-strong cases:
11223 ObjCMethodDecl *method = S.getCurMethodDecl();
11224 if (method && var == method->getSelfDecl()) {
11225 DiagID = method->isClassMethod()
11226 ? diag::err_typecheck_arc_assign_self_class_method
11227 : diag::err_typecheck_arc_assign_self;
11229 // - Objective-C externally_retained attribute.
11230 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11231 isa<ParmVarDecl>(var)) {
11232 DiagID = diag::err_typecheck_arc_assign_externally_retained;
11234 // - fast enumeration variables
11236 DiagID = diag::err_typecheck_arr_assign_enumeration;
11239 SourceRange Assign;
11240 if (Loc != OrigLoc)
11241 Assign = SourceRange(OrigLoc, OrigLoc);
11242 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11243 // We need to preserve the AST regardless, so migration tool
11250 // If none of the special cases above are triggered, then this is a
11251 // simple const assignment.
11253 DiagnoseConstAssignment(S, E, Loc);
11258 case Expr::MLV_ConstAddrSpace:
11259 DiagnoseConstAssignment(S, E, Loc);
11261 case Expr::MLV_ConstQualifiedField:
11262 DiagnoseRecursiveConstFields(S, E, Loc);
11264 case Expr::MLV_ArrayType:
11265 case Expr::MLV_ArrayTemporary:
11266 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11269 case Expr::MLV_NotObjectType:
11270 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11273 case Expr::MLV_LValueCast:
11274 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11276 case Expr::MLV_Valid:
11277 llvm_unreachable("did not take early return for MLV_Valid");
11278 case Expr::MLV_InvalidExpression:
11279 case Expr::MLV_MemberFunction:
11280 case Expr::MLV_ClassTemporary:
11281 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11283 case Expr::MLV_IncompleteType:
11284 case Expr::MLV_IncompleteVoidType:
11285 return S.RequireCompleteType(Loc, E->getType(),
11286 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11287 case Expr::MLV_DuplicateVectorComponents:
11288 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11290 case Expr::MLV_NoSetterProperty:
11291 llvm_unreachable("readonly properties should be processed differently");
11292 case Expr::MLV_InvalidMessageExpression:
11293 DiagID = diag::err_readonly_message_assignment;
11295 case Expr::MLV_SubObjCPropertySetting:
11296 DiagID = diag::err_no_subobject_property_setting;
11300 SourceRange Assign;
11301 if (Loc != OrigLoc)
11302 Assign = SourceRange(OrigLoc, OrigLoc);
11304 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11306 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11310 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11311 SourceLocation Loc,
11313 if (Sema.inTemplateInstantiation())
11315 if (Sema.isUnevaluatedContext())
11317 if (Loc.isInvalid() || Loc.isMacroID())
11319 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11323 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11324 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11326 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11328 const ValueDecl *LHSDecl =
11329 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11330 const ValueDecl *RHSDecl =
11331 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11332 if (LHSDecl != RHSDecl)
11334 if (LHSDecl->getType().isVolatileQualified())
11336 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11337 if (RefTy->getPointeeType().isVolatileQualified())
11340 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11343 // Objective-C instance variables
11344 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11345 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11346 if (OL && OR && OL->getDecl() == OR->getDecl()) {
11347 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11348 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11349 if (RL && RR && RL->getDecl() == RR->getDecl())
11350 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11355 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11356 SourceLocation Loc,
11357 QualType CompoundType) {
11358 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11360 // Verify that LHS is a modifiable lvalue, and emit error if not.
11361 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11364 QualType LHSType = LHSExpr->getType();
11365 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11367 // OpenCL v1.2 s6.1.1.1 p2:
11368 // The half data type can only be used to declare a pointer to a buffer that
11369 // contains half values
11370 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11371 LHSType->isHalfType()) {
11372 Diag(Loc, diag::err_opencl_half_load_store) << 1
11373 << LHSType.getUnqualifiedType();
11377 AssignConvertType ConvTy;
11378 if (CompoundType.isNull()) {
11379 Expr *RHSCheck = RHS.get();
11381 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11383 QualType LHSTy(LHSType);
11384 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11385 if (RHS.isInvalid())
11387 // Special case of NSObject attributes on c-style pointer types.
11388 if (ConvTy == IncompatiblePointer &&
11389 ((Context.isObjCNSObjectType(LHSType) &&
11390 RHSType->isObjCObjectPointerType()) ||
11391 (Context.isObjCNSObjectType(RHSType) &&
11392 LHSType->isObjCObjectPointerType())))
11393 ConvTy = Compatible;
11395 if (ConvTy == Compatible &&
11396 LHSType->isObjCObjectType())
11397 Diag(Loc, diag::err_objc_object_assignment)
11400 // If the RHS is a unary plus or minus, check to see if they = and + are
11401 // right next to each other. If so, the user may have typo'd "x =+ 4"
11402 // instead of "x += 4".
11403 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11404 RHSCheck = ICE->getSubExpr();
11405 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11406 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11407 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11408 // Only if the two operators are exactly adjacent.
11409 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11410 // And there is a space or other character before the subexpr of the
11411 // unary +/-. We don't want to warn on "x=-1".
11412 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11413 UO->getSubExpr()->getBeginLoc().isFileID()) {
11414 Diag(Loc, diag::warn_not_compound_assign)
11415 << (UO->getOpcode() == UO_Plus ? "+" : "-")
11416 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11420 if (ConvTy == Compatible) {
11421 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11422 // Warn about retain cycles where a block captures the LHS, but
11423 // not if the LHS is a simple variable into which the block is
11424 // being stored...unless that variable can be captured by reference!
11425 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11426 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11427 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11428 checkRetainCycles(LHSExpr, RHS.get());
11431 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11432 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11433 // It is safe to assign a weak reference into a strong variable.
11434 // Although this code can still have problems:
11435 // id x = self.weakProp;
11436 // id y = self.weakProp;
11437 // we do not warn to warn spuriously when 'x' and 'y' are on separate
11438 // paths through the function. This should be revisited if
11439 // -Wrepeated-use-of-weak is made flow-sensitive.
11440 // For ObjCWeak only, we do not warn if the assign is to a non-weak
11441 // variable, which will be valid for the current autorelease scope.
11442 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11443 RHS.get()->getBeginLoc()))
11444 getCurFunction()->markSafeWeakUse(RHS.get());
11446 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11447 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11451 // Compound assignment "x += y"
11452 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11455 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11456 RHS.get(), AA_Assigning))
11459 CheckForNullPointerDereference(*this, LHSExpr);
11461 // C99 6.5.16p3: The type of an assignment expression is the type of the
11462 // left operand unless the left operand has qualified type, in which case
11463 // it is the unqualified version of the type of the left operand.
11464 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11465 // is converted to the type of the assignment expression (above).
11466 // C++ 5.17p1: the type of the assignment expression is that of its left
11468 return (getLangOpts().CPlusPlus
11469 ? LHSType : LHSType.getUnqualifiedType());
11472 // Only ignore explicit casts to void.
11473 static bool IgnoreCommaOperand(const Expr *E) {
11474 E = E->IgnoreParens();
11476 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11477 if (CE->getCastKind() == CK_ToVoid) {
11481 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11482 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11483 CE->getSubExpr()->getType()->isDependentType()) {
11491 // Look for instances where it is likely the comma operator is confused with
11492 // another operator. There is a whitelist of acceptable expressions for the
11493 // left hand side of the comma operator, otherwise emit a warning.
11494 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11495 // No warnings in macros
11496 if (Loc.isMacroID())
11499 // Don't warn in template instantiations.
11500 if (inTemplateInstantiation())
11503 // Scope isn't fine-grained enough to whitelist the specific cases, so
11504 // instead, skip more than needed, then call back into here with the
11505 // CommaVisitor in SemaStmt.cpp.
11506 // The whitelisted locations are the initialization and increment portions
11507 // of a for loop. The additional checks are on the condition of
11508 // if statements, do/while loops, and for loops.
11509 // Differences in scope flags for C89 mode requires the extra logic.
11510 const unsigned ForIncrementFlags =
11511 getLangOpts().C99 || getLangOpts().CPlusPlus
11512 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11513 : Scope::ContinueScope | Scope::BreakScope;
11514 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11515 const unsigned ScopeFlags = getCurScope()->getFlags();
11516 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11517 (ScopeFlags & ForInitFlags) == ForInitFlags)
11520 // If there are multiple comma operators used together, get the RHS of the
11521 // of the comma operator as the LHS.
11522 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11523 if (BO->getOpcode() != BO_Comma)
11525 LHS = BO->getRHS();
11528 // Only allow some expressions on LHS to not warn.
11529 if (IgnoreCommaOperand(LHS))
11532 Diag(Loc, diag::warn_comma_operator);
11533 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11534 << LHS->getSourceRange()
11535 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11536 LangOpts.CPlusPlus ? "static_cast<void>("
11538 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11543 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11544 SourceLocation Loc) {
11545 LHS = S.CheckPlaceholderExpr(LHS.get());
11546 RHS = S.CheckPlaceholderExpr(RHS.get());
11547 if (LHS.isInvalid() || RHS.isInvalid())
11550 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11551 // operands, but not unary promotions.
11552 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11554 // So we treat the LHS as a ignored value, and in C++ we allow the
11555 // containing site to determine what should be done with the RHS.
11556 LHS = S.IgnoredValueConversions(LHS.get());
11557 if (LHS.isInvalid())
11560 S.DiagnoseUnusedExprResult(LHS.get());
11562 if (!S.getLangOpts().CPlusPlus) {
11563 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11564 if (RHS.isInvalid())
11566 if (!RHS.get()->getType()->isVoidType())
11567 S.RequireCompleteType(Loc, RHS.get()->getType(),
11568 diag::err_incomplete_type);
11571 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11572 S.DiagnoseCommaOperator(LHS.get(), Loc);
11574 return RHS.get()->getType();
11577 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11578 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11579 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11581 ExprObjectKind &OK,
11582 SourceLocation OpLoc,
11583 bool IsInc, bool IsPrefix) {
11584 if (Op->isTypeDependent())
11585 return S.Context.DependentTy;
11587 QualType ResType = Op->getType();
11588 // Atomic types can be used for increment / decrement where the non-atomic
11589 // versions can, so ignore the _Atomic() specifier for the purpose of
11591 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11592 ResType = ResAtomicType->getValueType();
11594 assert(!ResType.isNull() && "no type for increment/decrement expression");
11596 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11597 // Decrement of bool is not allowed.
11599 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11602 // Increment of bool sets it to true, but is deprecated.
11603 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11604 : diag::warn_increment_bool)
11605 << Op->getSourceRange();
11606 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11607 // Error on enum increments and decrements in C++ mode
11608 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11610 } else if (ResType->isRealType()) {
11612 } else if (ResType->isPointerType()) {
11613 // C99 6.5.2.4p2, 6.5.6p2
11614 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11616 } else if (ResType->isObjCObjectPointerType()) {
11617 // On modern runtimes, ObjC pointer arithmetic is forbidden.
11618 // Otherwise, we just need a complete type.
11619 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11620 checkArithmeticOnObjCPointer(S, OpLoc, Op))
11622 } else if (ResType->isAnyComplexType()) {
11623 // C99 does not support ++/-- on complex types, we allow as an extension.
11624 S.Diag(OpLoc, diag::ext_integer_increment_complex)
11625 << ResType << Op->getSourceRange();
11626 } else if (ResType->isPlaceholderType()) {
11627 ExprResult PR = S.CheckPlaceholderExpr(Op);
11628 if (PR.isInvalid()) return QualType();
11629 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11631 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11632 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11633 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11634 (ResType->getAs<VectorType>()->getVectorKind() !=
11635 VectorType::AltiVecBool)) {
11636 // The z vector extensions allow ++ and -- for non-bool vectors.
11637 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11638 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11639 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11641 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11642 << ResType << int(IsInc) << Op->getSourceRange();
11645 // At this point, we know we have a real, complex or pointer type.
11646 // Now make sure the operand is a modifiable lvalue.
11647 if (CheckForModifiableLvalue(Op, OpLoc, S))
11649 // In C++, a prefix increment is the same type as the operand. Otherwise
11650 // (in C or with postfix), the increment is the unqualified type of the
11652 if (IsPrefix && S.getLangOpts().CPlusPlus) {
11654 OK = Op->getObjectKind();
11658 return ResType.getUnqualifiedType();
11663 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11664 /// This routine allows us to typecheck complex/recursive expressions
11665 /// where the declaration is needed for type checking. We only need to
11666 /// handle cases when the expression references a function designator
11667 /// or is an lvalue. Here are some examples:
11669 /// - &*****f => f for f a function designator.
11671 /// - &s.zz[1].yy -> s, if zz is an array
11672 /// - *(x + 1) -> x, if x is an array
11673 /// - &"123"[2] -> 0
11674 /// - & __real__ x -> x
11675 static ValueDecl *getPrimaryDecl(Expr *E) {
11676 switch (E->getStmtClass()) {
11677 case Stmt::DeclRefExprClass:
11678 return cast<DeclRefExpr>(E)->getDecl();
11679 case Stmt::MemberExprClass:
11680 // If this is an arrow operator, the address is an offset from
11681 // the base's value, so the object the base refers to is
11683 if (cast<MemberExpr>(E)->isArrow())
11685 // Otherwise, the expression refers to a part of the base
11686 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11687 case Stmt::ArraySubscriptExprClass: {
11688 // FIXME: This code shouldn't be necessary! We should catch the implicit
11689 // promotion of register arrays earlier.
11690 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11691 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11692 if (ICE->getSubExpr()->getType()->isArrayType())
11693 return getPrimaryDecl(ICE->getSubExpr());
11697 case Stmt::UnaryOperatorClass: {
11698 UnaryOperator *UO = cast<UnaryOperator>(E);
11700 switch(UO->getOpcode()) {
11704 return getPrimaryDecl(UO->getSubExpr());
11709 case Stmt::ParenExprClass:
11710 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11711 case Stmt::ImplicitCastExprClass:
11712 // If the result of an implicit cast is an l-value, we care about
11713 // the sub-expression; otherwise, the result here doesn't matter.
11714 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11723 AO_Vector_Element = 1,
11724 AO_Property_Expansion = 2,
11725 AO_Register_Variable = 3,
11729 /// Diagnose invalid operand for address of operations.
11731 /// \param Type The type of operand which cannot have its address taken.
11732 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11733 Expr *E, unsigned Type) {
11734 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11737 /// CheckAddressOfOperand - The operand of & must be either a function
11738 /// designator or an lvalue designating an object. If it is an lvalue, the
11739 /// object cannot be declared with storage class register or be a bit field.
11740 /// Note: The usual conversions are *not* applied to the operand of the &
11741 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11742 /// In C++, the operand might be an overloaded function name, in which case
11743 /// we allow the '&' but retain the overloaded-function type.
11744 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11745 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11746 if (PTy->getKind() == BuiltinType::Overload) {
11747 Expr *E = OrigOp.get()->IgnoreParens();
11748 if (!isa<OverloadExpr>(E)) {
11749 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11750 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11751 << OrigOp.get()->getSourceRange();
11755 OverloadExpr *Ovl = cast<OverloadExpr>(E);
11756 if (isa<UnresolvedMemberExpr>(Ovl))
11757 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11758 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11759 << OrigOp.get()->getSourceRange();
11763 return Context.OverloadTy;
11766 if (PTy->getKind() == BuiltinType::UnknownAny)
11767 return Context.UnknownAnyTy;
11769 if (PTy->getKind() == BuiltinType::BoundMember) {
11770 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11771 << OrigOp.get()->getSourceRange();
11775 OrigOp = CheckPlaceholderExpr(OrigOp.get());
11776 if (OrigOp.isInvalid()) return QualType();
11779 if (OrigOp.get()->isTypeDependent())
11780 return Context.DependentTy;
11782 assert(!OrigOp.get()->getType()->isPlaceholderType());
11784 // Make sure to ignore parentheses in subsequent checks
11785 Expr *op = OrigOp.get()->IgnoreParens();
11787 // In OpenCL captures for blocks called as lambda functions
11788 // are located in the private address space. Blocks used in
11789 // enqueue_kernel can be located in a different address space
11790 // depending on a vendor implementation. Thus preventing
11791 // taking an address of the capture to avoid invalid AS casts.
11792 if (LangOpts.OpenCL) {
11793 auto* VarRef = dyn_cast<DeclRefExpr>(op);
11794 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11795 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11800 if (getLangOpts().C99) {
11801 // Implement C99-only parts of addressof rules.
11802 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11803 if (uOp->getOpcode() == UO_Deref)
11804 // Per C99 6.5.3.2, the address of a deref always returns a valid result
11805 // (assuming the deref expression is valid).
11806 return uOp->getSubExpr()->getType();
11808 // Technically, there should be a check for array subscript
11809 // expressions here, but the result of one is always an lvalue anyway.
11811 ValueDecl *dcl = getPrimaryDecl(op);
11813 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11814 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11815 op->getBeginLoc()))
11818 Expr::LValueClassification lval = op->ClassifyLValue(Context);
11819 unsigned AddressOfError = AO_No_Error;
11821 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11822 bool sfinae = (bool)isSFINAEContext();
11823 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11824 : diag::ext_typecheck_addrof_temporary)
11825 << op->getType() << op->getSourceRange();
11828 // Materialize the temporary as an lvalue so that we can take its address.
11830 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11831 } else if (isa<ObjCSelectorExpr>(op)) {
11832 return Context.getPointerType(op->getType());
11833 } else if (lval == Expr::LV_MemberFunction) {
11834 // If it's an instance method, make a member pointer.
11835 // The expression must have exactly the form &A::foo.
11837 // If the underlying expression isn't a decl ref, give up.
11838 if (!isa<DeclRefExpr>(op)) {
11839 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11840 << OrigOp.get()->getSourceRange();
11843 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11844 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11846 // The id-expression was parenthesized.
11847 if (OrigOp.get() != DRE) {
11848 Diag(OpLoc, diag::err_parens_pointer_member_function)
11849 << OrigOp.get()->getSourceRange();
11851 // The method was named without a qualifier.
11852 } else if (!DRE->getQualifier()) {
11853 if (MD->getParent()->getName().empty())
11854 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11855 << op->getSourceRange();
11857 SmallString<32> Str;
11858 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11859 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11860 << op->getSourceRange()
11861 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11865 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11866 if (isa<CXXDestructorDecl>(MD))
11867 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11869 QualType MPTy = Context.getMemberPointerType(
11870 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11871 // Under the MS ABI, lock down the inheritance model now.
11872 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11873 (void)isCompleteType(OpLoc, MPTy);
11875 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11877 // The operand must be either an l-value or a function designator
11878 if (!op->getType()->isFunctionType()) {
11879 // Use a special diagnostic for loads from property references.
11880 if (isa<PseudoObjectExpr>(op)) {
11881 AddressOfError = AO_Property_Expansion;
11883 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11884 << op->getType() << op->getSourceRange();
11888 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11889 // The operand cannot be a bit-field
11890 AddressOfError = AO_Bit_Field;
11891 } else if (op->getObjectKind() == OK_VectorComponent) {
11892 // The operand cannot be an element of a vector
11893 AddressOfError = AO_Vector_Element;
11894 } else if (dcl) { // C99 6.5.3.2p1
11895 // We have an lvalue with a decl. Make sure the decl is not declared
11896 // with the register storage-class specifier.
11897 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11898 // in C++ it is not error to take address of a register
11899 // variable (c++03 7.1.1P3)
11900 if (vd->getStorageClass() == SC_Register &&
11901 !getLangOpts().CPlusPlus) {
11902 AddressOfError = AO_Register_Variable;
11904 } else if (isa<MSPropertyDecl>(dcl)) {
11905 AddressOfError = AO_Property_Expansion;
11906 } else if (isa<FunctionTemplateDecl>(dcl)) {
11907 return Context.OverloadTy;
11908 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11909 // Okay: we can take the address of a field.
11910 // Could be a pointer to member, though, if there is an explicit
11911 // scope qualifier for the class.
11912 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11913 DeclContext *Ctx = dcl->getDeclContext();
11914 if (Ctx && Ctx->isRecord()) {
11915 if (dcl->getType()->isReferenceType()) {
11917 diag::err_cannot_form_pointer_to_member_of_reference_type)
11918 << dcl->getDeclName() << dcl->getType();
11922 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11923 Ctx = Ctx->getParent();
11925 QualType MPTy = Context.getMemberPointerType(
11927 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11928 // Under the MS ABI, lock down the inheritance model now.
11929 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11930 (void)isCompleteType(OpLoc, MPTy);
11934 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11935 !isa<BindingDecl>(dcl))
11936 llvm_unreachable("Unknown/unexpected decl type");
11939 if (AddressOfError != AO_No_Error) {
11940 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11944 if (lval == Expr::LV_IncompleteVoidType) {
11945 // Taking the address of a void variable is technically illegal, but we
11946 // allow it in cases which are otherwise valid.
11947 // Example: "extern void x; void* y = &x;".
11948 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11951 // If the operand has type "type", the result has type "pointer to type".
11952 if (op->getType()->isObjCObjectType())
11953 return Context.getObjCObjectPointerType(op->getType());
11955 CheckAddressOfPackedMember(op);
11957 return Context.getPointerType(op->getType());
11960 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11961 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11964 const Decl *D = DRE->getDecl();
11967 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11970 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11971 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11973 if (FunctionScopeInfo *FD = S.getCurFunction())
11974 if (!FD->ModifiedNonNullParams.count(Param))
11975 FD->ModifiedNonNullParams.insert(Param);
11978 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11979 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11980 SourceLocation OpLoc) {
11981 if (Op->isTypeDependent())
11982 return S.Context.DependentTy;
11984 ExprResult ConvResult = S.UsualUnaryConversions(Op);
11985 if (ConvResult.isInvalid())
11987 Op = ConvResult.get();
11988 QualType OpTy = Op->getType();
11991 if (isa<CXXReinterpretCastExpr>(Op)) {
11992 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11993 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11994 Op->getSourceRange());
11997 if (const PointerType *PT = OpTy->getAs<PointerType>())
11999 Result = PT->getPointeeType();
12001 else if (const ObjCObjectPointerType *OPT =
12002 OpTy->getAs<ObjCObjectPointerType>())
12003 Result = OPT->getPointeeType();
12005 ExprResult PR = S.CheckPlaceholderExpr(Op);
12006 if (PR.isInvalid()) return QualType();
12007 if (PR.get() != Op)
12008 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12011 if (Result.isNull()) {
12012 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12013 << OpTy << Op->getSourceRange();
12017 // Note that per both C89 and C99, indirection is always legal, even if Result
12018 // is an incomplete type or void. It would be possible to warn about
12019 // dereferencing a void pointer, but it's completely well-defined, and such a
12020 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12021 // for pointers to 'void' but is fine for any other pointer type:
12023 // C++ [expr.unary.op]p1:
12024 // [...] the expression to which [the unary * operator] is applied shall
12025 // be a pointer to an object type, or a pointer to a function type
12026 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12027 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12028 << OpTy << Op->getSourceRange();
12030 // Dereferences are usually l-values...
12033 // ...except that certain expressions are never l-values in C.
12034 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12040 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12041 BinaryOperatorKind Opc;
12043 default: llvm_unreachable("Unknown binop!");
12044 case tok::periodstar: Opc = BO_PtrMemD; break;
12045 case tok::arrowstar: Opc = BO_PtrMemI; break;
12046 case tok::star: Opc = BO_Mul; break;
12047 case tok::slash: Opc = BO_Div; break;
12048 case tok::percent: Opc = BO_Rem; break;
12049 case tok::plus: Opc = BO_Add; break;
12050 case tok::minus: Opc = BO_Sub; break;
12051 case tok::lessless: Opc = BO_Shl; break;
12052 case tok::greatergreater: Opc = BO_Shr; break;
12053 case tok::lessequal: Opc = BO_LE; break;
12054 case tok::less: Opc = BO_LT; break;
12055 case tok::greaterequal: Opc = BO_GE; break;
12056 case tok::greater: Opc = BO_GT; break;
12057 case tok::exclaimequal: Opc = BO_NE; break;
12058 case tok::equalequal: Opc = BO_EQ; break;
12059 case tok::spaceship: Opc = BO_Cmp; break;
12060 case tok::amp: Opc = BO_And; break;
12061 case tok::caret: Opc = BO_Xor; break;
12062 case tok::pipe: Opc = BO_Or; break;
12063 case tok::ampamp: Opc = BO_LAnd; break;
12064 case tok::pipepipe: Opc = BO_LOr; break;
12065 case tok::equal: Opc = BO_Assign; break;
12066 case tok::starequal: Opc = BO_MulAssign; break;
12067 case tok::slashequal: Opc = BO_DivAssign; break;
12068 case tok::percentequal: Opc = BO_RemAssign; break;
12069 case tok::plusequal: Opc = BO_AddAssign; break;
12070 case tok::minusequal: Opc = BO_SubAssign; break;
12071 case tok::lesslessequal: Opc = BO_ShlAssign; break;
12072 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
12073 case tok::ampequal: Opc = BO_AndAssign; break;
12074 case tok::caretequal: Opc = BO_XorAssign; break;
12075 case tok::pipeequal: Opc = BO_OrAssign; break;
12076 case tok::comma: Opc = BO_Comma; break;
12081 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12082 tok::TokenKind Kind) {
12083 UnaryOperatorKind Opc;
12085 default: llvm_unreachable("Unknown unary op!");
12086 case tok::plusplus: Opc = UO_PreInc; break;
12087 case tok::minusminus: Opc = UO_PreDec; break;
12088 case tok::amp: Opc = UO_AddrOf; break;
12089 case tok::star: Opc = UO_Deref; break;
12090 case tok::plus: Opc = UO_Plus; break;
12091 case tok::minus: Opc = UO_Minus; break;
12092 case tok::tilde: Opc = UO_Not; break;
12093 case tok::exclaim: Opc = UO_LNot; break;
12094 case tok::kw___real: Opc = UO_Real; break;
12095 case tok::kw___imag: Opc = UO_Imag; break;
12096 case tok::kw___extension__: Opc = UO_Extension; break;
12101 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12102 /// This warning suppressed in the event of macro expansions.
12103 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12104 SourceLocation OpLoc, bool IsBuiltin) {
12105 if (S.inTemplateInstantiation())
12107 if (S.isUnevaluatedContext())
12109 if (OpLoc.isInvalid() || OpLoc.isMacroID())
12111 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12112 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12113 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12114 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12115 if (!LHSDeclRef || !RHSDeclRef ||
12116 LHSDeclRef->getLocation().isMacroID() ||
12117 RHSDeclRef->getLocation().isMacroID())
12119 const ValueDecl *LHSDecl =
12120 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12121 const ValueDecl *RHSDecl =
12122 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12123 if (LHSDecl != RHSDecl)
12125 if (LHSDecl->getType().isVolatileQualified())
12127 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12128 if (RefTy->getPointeeType().isVolatileQualified())
12131 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12132 : diag::warn_self_assignment_overloaded)
12133 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12134 << RHSExpr->getSourceRange();
12137 /// Check if a bitwise-& is performed on an Objective-C pointer. This
12138 /// is usually indicative of introspection within the Objective-C pointer.
12139 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12140 SourceLocation OpLoc) {
12141 if (!S.getLangOpts().ObjC)
12144 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12145 const Expr *LHS = L.get();
12146 const Expr *RHS = R.get();
12148 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12149 ObjCPointerExpr = LHS;
12152 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12153 ObjCPointerExpr = RHS;
12157 // This warning is deliberately made very specific to reduce false
12158 // positives with logic that uses '&' for hashing. This logic mainly
12159 // looks for code trying to introspect into tagged pointers, which
12160 // code should generally never do.
12161 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12162 unsigned Diag = diag::warn_objc_pointer_masking;
12163 // Determine if we are introspecting the result of performSelectorXXX.
12164 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12165 // Special case messages to -performSelector and friends, which
12166 // can return non-pointer values boxed in a pointer value.
12167 // Some clients may wish to silence warnings in this subcase.
12168 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12169 Selector S = ME->getSelector();
12170 StringRef SelArg0 = S.getNameForSlot(0);
12171 if (SelArg0.startswith("performSelector"))
12172 Diag = diag::warn_objc_pointer_masking_performSelector;
12175 S.Diag(OpLoc, Diag)
12176 << ObjCPointerExpr->getSourceRange();
12180 static NamedDecl *getDeclFromExpr(Expr *E) {
12183 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12184 return DRE->getDecl();
12185 if (auto *ME = dyn_cast<MemberExpr>(E))
12186 return ME->getMemberDecl();
12187 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12188 return IRE->getDecl();
12192 // This helper function promotes a binary operator's operands (which are of a
12193 // half vector type) to a vector of floats and then truncates the result to
12194 // a vector of either half or short.
12195 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12196 BinaryOperatorKind Opc, QualType ResultTy,
12197 ExprValueKind VK, ExprObjectKind OK,
12198 bool IsCompAssign, SourceLocation OpLoc,
12199 FPOptions FPFeatures) {
12200 auto &Context = S.getASTContext();
12201 assert((isVector(ResultTy, Context.HalfTy) ||
12202 isVector(ResultTy, Context.ShortTy)) &&
12203 "Result must be a vector of half or short");
12204 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12205 isVector(RHS.get()->getType(), Context.HalfTy) &&
12206 "both operands expected to be a half vector");
12208 RHS = convertVector(RHS.get(), Context.FloatTy, S);
12209 QualType BinOpResTy = RHS.get()->getType();
12211 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12212 // change BinOpResTy to a vector of ints.
12213 if (isVector(ResultTy, Context.ShortTy))
12214 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12217 return new (Context) CompoundAssignOperator(
12218 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12219 OpLoc, FPFeatures);
12221 LHS = convertVector(LHS.get(), Context.FloatTy, S);
12222 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12223 VK, OK, OpLoc, FPFeatures);
12224 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12227 static std::pair<ExprResult, ExprResult>
12228 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12230 ExprResult LHS = LHSExpr, RHS = RHSExpr;
12231 if (!S.getLangOpts().CPlusPlus) {
12232 // C cannot handle TypoExpr nodes on either side of a binop because it
12233 // doesn't handle dependent types properly, so make sure any TypoExprs have
12234 // been dealt with before checking the operands.
12235 LHS = S.CorrectDelayedTyposInExpr(LHS);
12236 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12237 if (Opc != BO_Assign)
12238 return ExprResult(E);
12239 // Avoid correcting the RHS to the same Expr as the LHS.
12240 Decl *D = getDeclFromExpr(E);
12241 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12244 return std::make_pair(LHS, RHS);
12247 /// Returns true if conversion between vectors of halfs and vectors of floats
12249 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12250 QualType SrcType) {
12251 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12252 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12253 isVector(SrcType, Ctx.HalfTy);
12256 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12257 /// operator @p Opc at location @c TokLoc. This routine only supports
12258 /// built-in operations; ActOnBinOp handles overloaded operators.
12259 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12260 BinaryOperatorKind Opc,
12261 Expr *LHSExpr, Expr *RHSExpr) {
12262 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12263 // The syntax only allows initializer lists on the RHS of assignment,
12264 // so we don't need to worry about accepting invalid code for
12265 // non-assignment operators.
12267 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12268 // of x = {} is x = T().
12269 InitializationKind Kind = InitializationKind::CreateDirectList(
12270 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12271 InitializedEntity Entity =
12272 InitializedEntity::InitializeTemporary(LHSExpr->getType());
12273 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12274 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12275 if (Init.isInvalid())
12277 RHSExpr = Init.get();
12280 ExprResult LHS = LHSExpr, RHS = RHSExpr;
12281 QualType ResultTy; // Result type of the binary operator.
12282 // The following two variables are used for compound assignment operators
12283 QualType CompLHSTy; // Type of LHS after promotions for computation
12284 QualType CompResultTy; // Type of computation result
12285 ExprValueKind VK = VK_RValue;
12286 ExprObjectKind OK = OK_Ordinary;
12287 bool ConvertHalfVec = false;
12289 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12290 if (!LHS.isUsable() || !RHS.isUsable())
12291 return ExprError();
12293 if (getLangOpts().OpenCL) {
12294 QualType LHSTy = LHSExpr->getType();
12295 QualType RHSTy = RHSExpr->getType();
12296 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12297 // the ATOMIC_VAR_INIT macro.
12298 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12299 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12300 if (BO_Assign == Opc)
12301 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12303 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12304 return ExprError();
12307 // OpenCL special types - image, sampler, pipe, and blocks are to be used
12308 // only with a builtin functions and therefore should be disallowed here.
12309 if (LHSTy->isImageType() || RHSTy->isImageType() ||
12310 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12311 LHSTy->isPipeType() || RHSTy->isPipeType() ||
12312 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12313 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12314 return ExprError();
12320 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12321 if (getLangOpts().CPlusPlus &&
12322 LHS.get()->getObjectKind() != OK_ObjCProperty) {
12323 VK = LHS.get()->getValueKind();
12324 OK = LHS.get()->getObjectKind();
12326 if (!ResultTy.isNull()) {
12327 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12328 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12330 RecordModifiableNonNullParam(*this, LHS.get());
12334 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12335 Opc == BO_PtrMemI);
12339 ConvertHalfVec = true;
12340 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12344 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12347 ConvertHalfVec = true;
12348 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12351 ConvertHalfVec = true;
12352 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12356 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12362 ConvertHalfVec = true;
12363 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12367 ConvertHalfVec = true;
12368 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12371 ConvertHalfVec = true;
12372 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12373 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12376 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12380 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12384 ConvertHalfVec = true;
12385 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12389 ConvertHalfVec = true;
12390 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12391 Opc == BO_DivAssign);
12392 CompLHSTy = CompResultTy;
12393 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12394 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12397 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12398 CompLHSTy = CompResultTy;
12399 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12400 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12403 ConvertHalfVec = true;
12404 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12405 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12406 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12409 ConvertHalfVec = true;
12410 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12411 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12412 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12416 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12417 CompLHSTy = CompResultTy;
12418 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12419 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12422 case BO_OrAssign: // fallthrough
12423 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12426 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12427 CompLHSTy = CompResultTy;
12428 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12429 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12432 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12433 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12434 VK = RHS.get()->getValueKind();
12435 OK = RHS.get()->getObjectKind();
12439 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12440 return ExprError();
12442 // Some of the binary operations require promoting operands of half vector to
12443 // float vectors and truncating the result back to half vector. For now, we do
12444 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12446 assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12447 isVector(LHS.get()->getType(), Context.HalfTy) &&
12448 "both sides are half vectors or neither sides are");
12449 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12450 LHS.get()->getType());
12452 // Check for array bounds violations for both sides of the BinaryOperator
12453 CheckArrayAccess(LHS.get());
12454 CheckArrayAccess(RHS.get());
12456 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12457 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12458 &Context.Idents.get("object_setClass"),
12459 SourceLocation(), LookupOrdinaryName);
12460 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12461 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12462 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12463 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12464 "object_setClass(")
12465 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12467 << FixItHint::CreateInsertion(RHSLocEnd, ")");
12470 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12472 else if (const ObjCIvarRefExpr *OIRE =
12473 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12474 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12476 // Opc is not a compound assignment if CompResultTy is null.
12477 if (CompResultTy.isNull()) {
12478 if (ConvertHalfVec)
12479 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12480 OpLoc, FPFeatures);
12481 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12482 OK, OpLoc, FPFeatures);
12485 // Handle compound assignments.
12486 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12489 OK = LHS.get()->getObjectKind();
12492 if (ConvertHalfVec)
12493 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12494 OpLoc, FPFeatures);
12496 return new (Context) CompoundAssignOperator(
12497 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12498 OpLoc, FPFeatures);
12501 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12502 /// operators are mixed in a way that suggests that the programmer forgot that
12503 /// comparison operators have higher precedence. The most typical example of
12504 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12505 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12506 SourceLocation OpLoc, Expr *LHSExpr,
12508 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12509 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12511 // Check that one of the sides is a comparison operator and the other isn't.
12512 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12513 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12514 if (isLeftComp == isRightComp)
12517 // Bitwise operations are sometimes used as eager logical ops.
12518 // Don't diagnose this.
12519 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12520 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12521 if (isLeftBitwise || isRightBitwise)
12524 SourceRange DiagRange = isLeftComp
12525 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12526 : SourceRange(OpLoc, RHSExpr->getEndLoc());
12527 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12528 SourceRange ParensRange =
12530 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12531 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12533 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12534 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12535 SuggestParentheses(Self, OpLoc,
12536 Self.PDiag(diag::note_precedence_silence) << OpStr,
12537 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12538 SuggestParentheses(Self, OpLoc,
12539 Self.PDiag(diag::note_precedence_bitwise_first)
12540 << BinaryOperator::getOpcodeStr(Opc),
12544 /// It accepts a '&&' expr that is inside a '||' one.
12545 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12546 /// in parentheses.
12548 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12549 BinaryOperator *Bop) {
12550 assert(Bop->getOpcode() == BO_LAnd);
12551 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12552 << Bop->getSourceRange() << OpLoc;
12553 SuggestParentheses(Self, Bop->getOperatorLoc(),
12554 Self.PDiag(diag::note_precedence_silence)
12555 << Bop->getOpcodeStr(),
12556 Bop->getSourceRange());
12559 /// Returns true if the given expression can be evaluated as a constant
12561 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12563 return !E->isValueDependent() &&
12564 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12567 /// Returns true if the given expression can be evaluated as a constant
12569 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12571 return !E->isValueDependent() &&
12572 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12575 /// Look for '&&' in the left hand of a '||' expr.
12576 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12577 Expr *LHSExpr, Expr *RHSExpr) {
12578 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12579 if (Bop->getOpcode() == BO_LAnd) {
12580 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12581 if (EvaluatesAsFalse(S, RHSExpr))
12583 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12584 if (!EvaluatesAsTrue(S, Bop->getLHS()))
12585 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12586 } else if (Bop->getOpcode() == BO_LOr) {
12587 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12588 // If it's "a || b && 1 || c" we didn't warn earlier for
12589 // "a || b && 1", but warn now.
12590 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12591 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12597 /// Look for '&&' in the right hand of a '||' expr.
12598 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12599 Expr *LHSExpr, Expr *RHSExpr) {
12600 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12601 if (Bop->getOpcode() == BO_LAnd) {
12602 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12603 if (EvaluatesAsFalse(S, LHSExpr))
12605 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12606 if (!EvaluatesAsTrue(S, Bop->getRHS()))
12607 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12612 /// Look for bitwise op in the left or right hand of a bitwise op with
12613 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12614 /// the '&' expression in parentheses.
12615 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12616 SourceLocation OpLoc, Expr *SubExpr) {
12617 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12618 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12619 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12620 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12621 << Bop->getSourceRange() << OpLoc;
12622 SuggestParentheses(S, Bop->getOperatorLoc(),
12623 S.PDiag(diag::note_precedence_silence)
12624 << Bop->getOpcodeStr(),
12625 Bop->getSourceRange());
12630 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12631 Expr *SubExpr, StringRef Shift) {
12632 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12633 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12634 StringRef Op = Bop->getOpcodeStr();
12635 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12636 << Bop->getSourceRange() << OpLoc << Shift << Op;
12637 SuggestParentheses(S, Bop->getOperatorLoc(),
12638 S.PDiag(diag::note_precedence_silence) << Op,
12639 Bop->getSourceRange());
12644 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12645 Expr *LHSExpr, Expr *RHSExpr) {
12646 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12650 FunctionDecl *FD = OCE->getDirectCallee();
12651 if (!FD || !FD->isOverloadedOperator())
12654 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12655 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12658 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12659 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12660 << (Kind == OO_LessLess);
12661 SuggestParentheses(S, OCE->getOperatorLoc(),
12662 S.PDiag(diag::note_precedence_silence)
12663 << (Kind == OO_LessLess ? "<<" : ">>"),
12664 OCE->getSourceRange());
12665 SuggestParentheses(
12666 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12667 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12670 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12672 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12673 SourceLocation OpLoc, Expr *LHSExpr,
12675 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12676 if (BinaryOperator::isBitwiseOp(Opc))
12677 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12679 // Diagnose "arg1 & arg2 | arg3"
12680 if ((Opc == BO_Or || Opc == BO_Xor) &&
12681 !OpLoc.isMacroID()/* Don't warn in macros. */) {
12682 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12683 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12686 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12687 // We don't warn for 'assert(a || b && "bad")' since this is safe.
12688 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12689 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12690 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12693 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12694 || Opc == BO_Shr) {
12695 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12696 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12697 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12700 // Warn on overloaded shift operators and comparisons, such as:
12702 if (BinaryOperator::isComparisonOp(Opc))
12703 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12706 // Binary Operators. 'Tok' is the token for the operator.
12707 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12708 tok::TokenKind Kind,
12709 Expr *LHSExpr, Expr *RHSExpr) {
12710 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12711 assert(LHSExpr && "ActOnBinOp(): missing left expression");
12712 assert(RHSExpr && "ActOnBinOp(): missing right expression");
12714 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12715 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12717 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12720 /// Build an overloaded binary operator expression in the given scope.
12721 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12722 BinaryOperatorKind Opc,
12723 Expr *LHS, Expr *RHS) {
12732 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12733 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12739 // Find all of the overloaded operators visible from this
12740 // point. We perform both an operator-name lookup from the local
12741 // scope and an argument-dependent lookup based on the types of
12743 UnresolvedSet<16> Functions;
12744 OverloadedOperatorKind OverOp
12745 = BinaryOperator::getOverloadedOperator(Opc);
12746 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12747 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12748 RHS->getType(), Functions);
12750 // Build the (potentially-overloaded, potentially-dependent)
12751 // binary operation.
12752 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12755 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12756 BinaryOperatorKind Opc,
12757 Expr *LHSExpr, Expr *RHSExpr) {
12758 ExprResult LHS, RHS;
12759 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12760 if (!LHS.isUsable() || !RHS.isUsable())
12761 return ExprError();
12762 LHSExpr = LHS.get();
12763 RHSExpr = RHS.get();
12765 // We want to end up calling one of checkPseudoObjectAssignment
12766 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12767 // both expressions are overloadable or either is type-dependent),
12768 // or CreateBuiltinBinOp (in any other case). We also want to get
12769 // any placeholder types out of the way.
12771 // Handle pseudo-objects in the LHS.
12772 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12773 // Assignments with a pseudo-object l-value need special analysis.
12774 if (pty->getKind() == BuiltinType::PseudoObject &&
12775 BinaryOperator::isAssignmentOp(Opc))
12776 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12778 // Don't resolve overloads if the other type is overloadable.
12779 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12780 // We can't actually test that if we still have a placeholder,
12781 // though. Fortunately, none of the exceptions we see in that
12782 // code below are valid when the LHS is an overload set. Note
12783 // that an overload set can be dependently-typed, but it never
12784 // instantiates to having an overloadable type.
12785 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12786 if (resolvedRHS.isInvalid()) return ExprError();
12787 RHSExpr = resolvedRHS.get();
12789 if (RHSExpr->isTypeDependent() ||
12790 RHSExpr->getType()->isOverloadableType())
12791 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12794 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12795 // template, diagnose the missing 'template' keyword instead of diagnosing
12796 // an invalid use of a bound member function.
12798 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12799 // to C++1z [over.over]/1.4, but we already checked for that case above.
12800 if (Opc == BO_LT && inTemplateInstantiation() &&
12801 (pty->getKind() == BuiltinType::BoundMember ||
12802 pty->getKind() == BuiltinType::Overload)) {
12803 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12804 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12805 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12806 return isa<FunctionTemplateDecl>(ND);
12808 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12809 : OE->getNameLoc(),
12810 diag::err_template_kw_missing)
12811 << OE->getName().getAsString() << "";
12812 return ExprError();
12816 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12817 if (LHS.isInvalid()) return ExprError();
12818 LHSExpr = LHS.get();
12821 // Handle pseudo-objects in the RHS.
12822 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12823 // An overload in the RHS can potentially be resolved by the type
12824 // being assigned to.
12825 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12826 if (getLangOpts().CPlusPlus &&
12827 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12828 LHSExpr->getType()->isOverloadableType()))
12829 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12831 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12834 // Don't resolve overloads if the other type is overloadable.
12835 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12836 LHSExpr->getType()->isOverloadableType())
12837 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12839 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12840 if (!resolvedRHS.isUsable()) return ExprError();
12841 RHSExpr = resolvedRHS.get();
12844 if (getLangOpts().CPlusPlus) {
12845 // If either expression is type-dependent, always build an
12847 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12848 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12850 // Otherwise, build an overloaded op if either expression has an
12851 // overloadable type.
12852 if (LHSExpr->getType()->isOverloadableType() ||
12853 RHSExpr->getType()->isOverloadableType())
12854 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12857 // Build a built-in binary operation.
12858 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12861 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12862 if (T.isNull() || T->isDependentType())
12865 if (!T->isPromotableIntegerType())
12868 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12871 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12872 UnaryOperatorKind Opc,
12874 ExprResult Input = InputExpr;
12875 ExprValueKind VK = VK_RValue;
12876 ExprObjectKind OK = OK_Ordinary;
12877 QualType resultType;
12878 bool CanOverflow = false;
12880 bool ConvertHalfVec = false;
12881 if (getLangOpts().OpenCL) {
12882 QualType Ty = InputExpr->getType();
12883 // The only legal unary operation for atomics is '&'.
12884 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12885 // OpenCL special types - image, sampler, pipe, and blocks are to be used
12886 // only with a builtin functions and therefore should be disallowed here.
12887 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12888 || Ty->isBlockPointerType())) {
12889 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12890 << InputExpr->getType()
12891 << Input.get()->getSourceRange());
12899 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12901 Opc == UO_PreInc ||
12903 Opc == UO_PreInc ||
12905 CanOverflow = isOverflowingIntegerType(Context, resultType);
12908 resultType = CheckAddressOfOperand(Input, OpLoc);
12909 CheckAddressOfNoDeref(InputExpr);
12910 RecordModifiableNonNullParam(*this, InputExpr);
12913 Input = DefaultFunctionArrayLvalueConversion(Input.get());
12914 if (Input.isInvalid()) return ExprError();
12915 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12920 CanOverflow = Opc == UO_Minus &&
12921 isOverflowingIntegerType(Context, Input.get()->getType());
12922 Input = UsualUnaryConversions(Input.get());
12923 if (Input.isInvalid()) return ExprError();
12924 // Unary plus and minus require promoting an operand of half vector to a
12925 // float vector and truncating the result back to a half vector. For now, we
12926 // do this only when HalfArgsAndReturns is set (that is, when the target is
12929 needsConversionOfHalfVec(true, Context, Input.get()->getType());
12931 // If the operand is a half vector, promote it to a float vector.
12932 if (ConvertHalfVec)
12933 Input = convertVector(Input.get(), Context.FloatTy, *this);
12934 resultType = Input.get()->getType();
12935 if (resultType->isDependentType())
12937 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12939 else if (resultType->isVectorType() &&
12940 // The z vector extensions don't allow + or - with bool vectors.
12941 (!Context.getLangOpts().ZVector ||
12942 resultType->getAs<VectorType>()->getVectorKind() !=
12943 VectorType::AltiVecBool))
12945 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12947 resultType->isPointerType())
12950 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12951 << resultType << Input.get()->getSourceRange());
12953 case UO_Not: // bitwise complement
12954 Input = UsualUnaryConversions(Input.get());
12955 if (Input.isInvalid())
12956 return ExprError();
12957 resultType = Input.get()->getType();
12959 if (resultType->isDependentType())
12961 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12962 if (resultType->isComplexType() || resultType->isComplexIntegerType())
12963 // C99 does not support '~' for complex conjugation.
12964 Diag(OpLoc, diag::ext_integer_complement_complex)
12965 << resultType << Input.get()->getSourceRange();
12966 else if (resultType->hasIntegerRepresentation())
12968 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12969 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12970 // on vector float types.
12971 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12972 if (!T->isIntegerType())
12973 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12974 << resultType << Input.get()->getSourceRange());
12976 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12977 << resultType << Input.get()->getSourceRange());
12981 case UO_LNot: // logical negation
12982 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12983 Input = DefaultFunctionArrayLvalueConversion(Input.get());
12984 if (Input.isInvalid()) return ExprError();
12985 resultType = Input.get()->getType();
12987 // Though we still have to promote half FP to float...
12988 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12989 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12990 resultType = Context.FloatTy;
12993 if (resultType->isDependentType())
12995 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12996 // C99 6.5.3.3p1: ok, fallthrough;
12997 if (Context.getLangOpts().CPlusPlus) {
12998 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12999 // operand contextually converted to bool.
13000 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13001 ScalarTypeToBooleanCastKind(resultType));
13002 } else if (Context.getLangOpts().OpenCL &&
13003 Context.getLangOpts().OpenCLVersion < 120) {
13004 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13005 // operate on scalar float types.
13006 if (!resultType->isIntegerType() && !resultType->isPointerType())
13007 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13008 << resultType << Input.get()->getSourceRange());
13010 } else if (resultType->isExtVectorType()) {
13011 if (Context.getLangOpts().OpenCL &&
13012 Context.getLangOpts().OpenCLVersion < 120) {
13013 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13014 // operate on vector float types.
13015 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13016 if (!T->isIntegerType())
13017 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13018 << resultType << Input.get()->getSourceRange());
13020 // Vector logical not returns the signed variant of the operand type.
13021 resultType = GetSignedVectorType(resultType);
13024 // FIXME: GCC's vector extension permits the usage of '!' with a vector
13025 // type in C++. We should allow that here too.
13026 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13027 << resultType << Input.get()->getSourceRange());
13030 // LNot always has type int. C99 6.5.3.3p5.
13031 // In C++, it's bool. C++ 5.3.1p8
13032 resultType = Context.getLogicalOperationType();
13036 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13037 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13038 // complex l-values to ordinary l-values and all other values to r-values.
13039 if (Input.isInvalid()) return ExprError();
13040 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13041 if (Input.get()->getValueKind() != VK_RValue &&
13042 Input.get()->getObjectKind() == OK_Ordinary)
13043 VK = Input.get()->getValueKind();
13044 } else if (!getLangOpts().CPlusPlus) {
13045 // In C, a volatile scalar is read by __imag. In C++, it is not.
13046 Input = DefaultLvalueConversion(Input.get());
13050 resultType = Input.get()->getType();
13051 VK = Input.get()->getValueKind();
13052 OK = Input.get()->getObjectKind();
13055 // It's unnecessary to represent the pass-through operator co_await in the
13056 // AST; just return the input expression instead.
13057 assert(!Input.get()->getType()->isDependentType() &&
13058 "the co_await expression must be non-dependant before "
13059 "building operator co_await");
13062 if (resultType.isNull() || Input.isInvalid())
13063 return ExprError();
13065 // Check for array bounds violations in the operand of the UnaryOperator,
13066 // except for the '*' and '&' operators that have to be handled specially
13067 // by CheckArrayAccess (as there are special cases like &array[arraysize]
13068 // that are explicitly defined as valid by the standard).
13069 if (Opc != UO_AddrOf && Opc != UO_Deref)
13070 CheckArrayAccess(Input.get());
13072 auto *UO = new (Context)
13073 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13075 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13076 !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13077 ExprEvalContexts.back().PossibleDerefs.insert(UO);
13079 // Convert the result back to a half vector.
13080 if (ConvertHalfVec)
13081 return convertVector(UO, Context.HalfTy, *this);
13085 /// Determine whether the given expression is a qualified member
13086 /// access expression, of a form that could be turned into a pointer to member
13087 /// with the address-of operator.
13088 bool Sema::isQualifiedMemberAccess(Expr *E) {
13089 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13090 if (!DRE->getQualifier())
13093 ValueDecl *VD = DRE->getDecl();
13094 if (!VD->isCXXClassMember())
13097 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13099 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13100 return Method->isInstance();
13105 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13106 if (!ULE->getQualifier())
13109 for (NamedDecl *D : ULE->decls()) {
13110 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13111 if (Method->isInstance())
13114 // Overload set does not contain methods.
13125 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13126 UnaryOperatorKind Opc, Expr *Input) {
13127 // First things first: handle placeholders so that the
13128 // overloaded-operator check considers the right type.
13129 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13130 // Increment and decrement of pseudo-object references.
13131 if (pty->getKind() == BuiltinType::PseudoObject &&
13132 UnaryOperator::isIncrementDecrementOp(Opc))
13133 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13135 // extension is always a builtin operator.
13136 if (Opc == UO_Extension)
13137 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13139 // & gets special logic for several kinds of placeholder.
13140 // The builtin code knows what to do.
13141 if (Opc == UO_AddrOf &&
13142 (pty->getKind() == BuiltinType::Overload ||
13143 pty->getKind() == BuiltinType::UnknownAny ||
13144 pty->getKind() == BuiltinType::BoundMember))
13145 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13147 // Anything else needs to be handled now.
13148 ExprResult Result = CheckPlaceholderExpr(Input);
13149 if (Result.isInvalid()) return ExprError();
13150 Input = Result.get();
13153 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13154 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13155 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13156 // Find all of the overloaded operators visible from this
13157 // point. We perform both an operator-name lookup from the local
13158 // scope and an argument-dependent lookup based on the types of
13160 UnresolvedSet<16> Functions;
13161 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13162 if (S && OverOp != OO_None)
13163 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13166 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13169 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13172 // Unary Operators. 'Tok' is the token for the operator.
13173 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13174 tok::TokenKind Op, Expr *Input) {
13175 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13178 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13179 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13180 LabelDecl *TheDecl) {
13181 TheDecl->markUsed(Context);
13182 // Create the AST node. The address of a label always has type 'void*'.
13183 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13184 Context.getPointerType(Context.VoidTy));
13187 /// Given the last statement in a statement-expression, check whether
13188 /// the result is a producing expression (like a call to an
13189 /// ns_returns_retained function) and, if so, rebuild it to hoist the
13190 /// release out of the full-expression. Otherwise, return null.
13192 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
13193 // Should always be wrapped with one of these.
13194 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
13195 if (!cleanups) return nullptr;
13197 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
13198 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
13201 // Splice out the cast. This shouldn't modify any interesting
13202 // features of the statement.
13203 Expr *producer = cast->getSubExpr();
13204 assert(producer->getType() == cast->getType());
13205 assert(producer->getValueKind() == cast->getValueKind());
13206 cleanups->setSubExpr(producer);
13210 void Sema::ActOnStartStmtExpr() {
13211 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13214 void Sema::ActOnStmtExprError() {
13215 // Note that function is also called by TreeTransform when leaving a
13216 // StmtExpr scope without rebuilding anything.
13218 DiscardCleanupsInEvaluationContext();
13219 PopExpressionEvaluationContext();
13223 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13224 SourceLocation RPLoc) { // "({..})"
13225 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13226 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13228 if (hasAnyUnrecoverableErrorsInThisFunction())
13229 DiscardCleanupsInEvaluationContext();
13230 assert(!Cleanup.exprNeedsCleanups() &&
13231 "cleanups within StmtExpr not correctly bound!");
13232 PopExpressionEvaluationContext();
13234 // FIXME: there are a variety of strange constraints to enforce here, for
13235 // example, it is not possible to goto into a stmt expression apparently.
13236 // More semantic analysis is needed.
13238 // If there are sub-stmts in the compound stmt, take the type of the last one
13239 // as the type of the stmtexpr.
13240 QualType Ty = Context.VoidTy;
13241 bool StmtExprMayBindToTemp = false;
13242 if (!Compound->body_empty()) {
13243 Stmt *LastStmt = Compound->body_back();
13244 LabelStmt *LastLabelStmt = nullptr;
13245 // If LastStmt is a label, skip down through into the body.
13246 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
13247 LastLabelStmt = Label;
13248 LastStmt = Label->getSubStmt();
13251 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
13252 // Do function/array conversion on the last expression, but not
13253 // lvalue-to-rvalue. However, initialize an unqualified type.
13254 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
13255 if (LastExpr.isInvalid())
13256 return ExprError();
13257 Ty = LastExpr.get()->getType().getUnqualifiedType();
13259 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
13260 // In ARC, if the final expression ends in a consume, splice
13261 // the consume out and bind it later. In the alternate case
13262 // (when dealing with a retainable type), the result
13263 // initialization will create a produce. In both cases the
13264 // result will be +1, and we'll need to balance that out with
13266 if (Expr *rebuiltLastStmt
13267 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
13268 LastExpr = rebuiltLastStmt;
13270 LastExpr = PerformCopyInitialization(
13271 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
13272 SourceLocation(), LastExpr);
13275 if (LastExpr.isInvalid())
13276 return ExprError();
13277 if (LastExpr.get() != nullptr) {
13278 if (!LastLabelStmt)
13279 Compound->setLastStmt(LastExpr.get());
13281 LastLabelStmt->setSubStmt(LastExpr.get());
13282 StmtExprMayBindToTemp = true;
13288 // FIXME: Check that expression type is complete/non-abstract; statement
13289 // expressions are not lvalues.
13290 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13291 if (StmtExprMayBindToTemp)
13292 return MaybeBindToTemporary(ResStmtExpr);
13293 return ResStmtExpr;
13296 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13297 TypeSourceInfo *TInfo,
13298 ArrayRef<OffsetOfComponent> Components,
13299 SourceLocation RParenLoc) {
13300 QualType ArgTy = TInfo->getType();
13301 bool Dependent = ArgTy->isDependentType();
13302 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13304 // We must have at least one component that refers to the type, and the first
13305 // one is known to be a field designator. Verify that the ArgTy represents
13306 // a struct/union/class.
13307 if (!Dependent && !ArgTy->isRecordType())
13308 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13309 << ArgTy << TypeRange);
13311 // Type must be complete per C99 7.17p3 because a declaring a variable
13312 // with an incomplete type would be ill-formed.
13314 && RequireCompleteType(BuiltinLoc, ArgTy,
13315 diag::err_offsetof_incomplete_type, TypeRange))
13316 return ExprError();
13318 bool DidWarnAboutNonPOD = false;
13319 QualType CurrentType = ArgTy;
13320 SmallVector<OffsetOfNode, 4> Comps;
13321 SmallVector<Expr*, 4> Exprs;
13322 for (const OffsetOfComponent &OC : Components) {
13323 if (OC.isBrackets) {
13324 // Offset of an array sub-field. TODO: Should we allow vector elements?
13325 if (!CurrentType->isDependentType()) {
13326 const ArrayType *AT = Context.getAsArrayType(CurrentType);
13328 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13330 CurrentType = AT->getElementType();
13332 CurrentType = Context.DependentTy;
13334 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13335 if (IdxRval.isInvalid())
13336 return ExprError();
13337 Expr *Idx = IdxRval.get();
13339 // The expression must be an integral expression.
13340 // FIXME: An integral constant expression?
13341 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13342 !Idx->getType()->isIntegerType())
13344 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13345 << Idx->getSourceRange());
13347 // Record this array index.
13348 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13349 Exprs.push_back(Idx);
13353 // Offset of a field.
13354 if (CurrentType->isDependentType()) {
13355 // We have the offset of a field, but we can't look into the dependent
13356 // type. Just record the identifier of the field.
13357 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13358 CurrentType = Context.DependentTy;
13362 // We need to have a complete type to look into.
13363 if (RequireCompleteType(OC.LocStart, CurrentType,
13364 diag::err_offsetof_incomplete_type))
13365 return ExprError();
13367 // Look for the designated field.
13368 const RecordType *RC = CurrentType->getAs<RecordType>();
13370 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13372 RecordDecl *RD = RC->getDecl();
13374 // C++ [lib.support.types]p5:
13375 // The macro offsetof accepts a restricted set of type arguments in this
13376 // International Standard. type shall be a POD structure or a POD union
13378 // C++11 [support.types]p4:
13379 // If type is not a standard-layout class (Clause 9), the results are
13381 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13382 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13384 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13385 : diag::ext_offsetof_non_pod_type;
13387 if (!IsSafe && !DidWarnAboutNonPOD &&
13388 DiagRuntimeBehavior(BuiltinLoc, nullptr,
13390 << SourceRange(Components[0].LocStart, OC.LocEnd)
13392 DidWarnAboutNonPOD = true;
13395 // Look for the field.
13396 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13397 LookupQualifiedName(R, RD);
13398 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13399 IndirectFieldDecl *IndirectMemberDecl = nullptr;
13401 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13402 MemberDecl = IndirectMemberDecl->getAnonField();
13406 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13407 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13411 // (If the specified member is a bit-field, the behavior is undefined.)
13413 // We diagnose this as an error.
13414 if (MemberDecl->isBitField()) {
13415 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13416 << MemberDecl->getDeclName()
13417 << SourceRange(BuiltinLoc, RParenLoc);
13418 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13419 return ExprError();
13422 RecordDecl *Parent = MemberDecl->getParent();
13423 if (IndirectMemberDecl)
13424 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13426 // If the member was found in a base class, introduce OffsetOfNodes for
13427 // the base class indirections.
13428 CXXBasePaths Paths;
13429 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13431 if (Paths.getDetectedVirtual()) {
13432 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13433 << MemberDecl->getDeclName()
13434 << SourceRange(BuiltinLoc, RParenLoc);
13435 return ExprError();
13438 CXXBasePath &Path = Paths.front();
13439 for (const CXXBasePathElement &B : Path)
13440 Comps.push_back(OffsetOfNode(B.Base));
13443 if (IndirectMemberDecl) {
13444 for (auto *FI : IndirectMemberDecl->chain()) {
13445 assert(isa<FieldDecl>(FI));
13446 Comps.push_back(OffsetOfNode(OC.LocStart,
13447 cast<FieldDecl>(FI), OC.LocEnd));
13450 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13452 CurrentType = MemberDecl->getType().getNonReferenceType();
13455 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13456 Comps, Exprs, RParenLoc);
13459 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13460 SourceLocation BuiltinLoc,
13461 SourceLocation TypeLoc,
13462 ParsedType ParsedArgTy,
13463 ArrayRef<OffsetOfComponent> Components,
13464 SourceLocation RParenLoc) {
13466 TypeSourceInfo *ArgTInfo;
13467 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13468 if (ArgTy.isNull())
13469 return ExprError();
13472 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13474 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13478 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13480 Expr *LHSExpr, Expr *RHSExpr,
13481 SourceLocation RPLoc) {
13482 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13484 ExprValueKind VK = VK_RValue;
13485 ExprObjectKind OK = OK_Ordinary;
13487 bool ValueDependent = false;
13488 bool CondIsTrue = false;
13489 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13490 resType = Context.DependentTy;
13491 ValueDependent = true;
13493 // The conditional expression is required to be a constant expression.
13494 llvm::APSInt condEval(32);
13496 = VerifyIntegerConstantExpression(CondExpr, &condEval,
13497 diag::err_typecheck_choose_expr_requires_constant, false);
13498 if (CondICE.isInvalid())
13499 return ExprError();
13500 CondExpr = CondICE.get();
13501 CondIsTrue = condEval.getZExtValue();
13503 // If the condition is > zero, then the AST type is the same as the LHSExpr.
13504 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13506 resType = ActiveExpr->getType();
13507 ValueDependent = ActiveExpr->isValueDependent();
13508 VK = ActiveExpr->getValueKind();
13509 OK = ActiveExpr->getObjectKind();
13512 return new (Context)
13513 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13514 CondIsTrue, resType->isDependentType(), ValueDependent);
13517 //===----------------------------------------------------------------------===//
13518 // Clang Extensions.
13519 //===----------------------------------------------------------------------===//
13521 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13522 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13523 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13525 if (LangOpts.CPlusPlus) {
13526 Decl *ManglingContextDecl;
13527 if (MangleNumberingContext *MCtx =
13528 getCurrentMangleNumberContext(Block->getDeclContext(),
13529 ManglingContextDecl)) {
13530 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13531 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13535 PushBlockScope(CurScope, Block);
13536 CurContext->addDecl(Block);
13538 PushDeclContext(CurScope, Block);
13540 CurContext = Block;
13542 getCurBlock()->HasImplicitReturnType = true;
13544 // Enter a new evaluation context to insulate the block from any
13545 // cleanups from the enclosing full-expression.
13546 PushExpressionEvaluationContext(
13547 ExpressionEvaluationContext::PotentiallyEvaluated);
13550 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13552 assert(ParamInfo.getIdentifier() == nullptr &&
13553 "block-id should have no identifier!");
13554 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13555 BlockScopeInfo *CurBlock = getCurBlock();
13557 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13558 QualType T = Sig->getType();
13560 // FIXME: We should allow unexpanded parameter packs here, but that would,
13561 // in turn, make the block expression contain unexpanded parameter packs.
13562 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13563 // Drop the parameters.
13564 FunctionProtoType::ExtProtoInfo EPI;
13565 EPI.HasTrailingReturn = false;
13566 EPI.TypeQuals.addConst();
13567 T = Context.getFunctionType(Context.DependentTy, None, EPI);
13568 Sig = Context.getTrivialTypeSourceInfo(T);
13571 // GetTypeForDeclarator always produces a function type for a block
13572 // literal signature. Furthermore, it is always a FunctionProtoType
13573 // unless the function was written with a typedef.
13574 assert(T->isFunctionType() &&
13575 "GetTypeForDeclarator made a non-function block signature");
13577 // Look for an explicit signature in that function type.
13578 FunctionProtoTypeLoc ExplicitSignature;
13580 if ((ExplicitSignature =
13581 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13583 // Check whether that explicit signature was synthesized by
13584 // GetTypeForDeclarator. If so, don't save that as part of the
13585 // written signature.
13586 if (ExplicitSignature.getLocalRangeBegin() ==
13587 ExplicitSignature.getLocalRangeEnd()) {
13588 // This would be much cheaper if we stored TypeLocs instead of
13589 // TypeSourceInfos.
13590 TypeLoc Result = ExplicitSignature.getReturnLoc();
13591 unsigned Size = Result.getFullDataSize();
13592 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13593 Sig->getTypeLoc().initializeFullCopy(Result, Size);
13595 ExplicitSignature = FunctionProtoTypeLoc();
13599 CurBlock->TheDecl->setSignatureAsWritten(Sig);
13600 CurBlock->FunctionType = T;
13602 const FunctionType *Fn = T->getAs<FunctionType>();
13603 QualType RetTy = Fn->getReturnType();
13605 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13607 CurBlock->TheDecl->setIsVariadic(isVariadic);
13609 // Context.DependentTy is used as a placeholder for a missing block
13610 // return type. TODO: what should we do with declarators like:
13612 // If the answer is "apply template argument deduction"....
13613 if (RetTy != Context.DependentTy) {
13614 CurBlock->ReturnType = RetTy;
13615 CurBlock->TheDecl->setBlockMissingReturnType(false);
13616 CurBlock->HasImplicitReturnType = false;
13619 // Push block parameters from the declarator if we had them.
13620 SmallVector<ParmVarDecl*, 8> Params;
13621 if (ExplicitSignature) {
13622 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13623 ParmVarDecl *Param = ExplicitSignature.getParam(I);
13624 if (Param->getIdentifier() == nullptr &&
13625 !Param->isImplicit() &&
13626 !Param->isInvalidDecl() &&
13627 !getLangOpts().CPlusPlus)
13628 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13629 Params.push_back(Param);
13632 // Fake up parameter variables if we have a typedef, like
13633 // ^ fntype { ... }
13634 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13635 for (const auto &I : Fn->param_types()) {
13636 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13637 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13638 Params.push_back(Param);
13642 // Set the parameters on the block decl.
13643 if (!Params.empty()) {
13644 CurBlock->TheDecl->setParams(Params);
13645 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13646 /*CheckParameterNames=*/false);
13649 // Finally we can process decl attributes.
13650 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13652 // Put the parameter variables in scope.
13653 for (auto AI : CurBlock->TheDecl->parameters()) {
13654 AI->setOwningFunction(CurBlock->TheDecl);
13656 // If this has an identifier, add it to the scope stack.
13657 if (AI->getIdentifier()) {
13658 CheckShadow(CurBlock->TheScope, AI);
13660 PushOnScopeChains(AI, CurBlock->TheScope);
13665 /// ActOnBlockError - If there is an error parsing a block, this callback
13666 /// is invoked to pop the information about the block from the action impl.
13667 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13668 // Leave the expression-evaluation context.
13669 DiscardCleanupsInEvaluationContext();
13670 PopExpressionEvaluationContext();
13672 // Pop off CurBlock, handle nested blocks.
13674 PopFunctionScopeInfo();
13677 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13678 /// literal was successfully completed. ^(int x){...}
13679 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13680 Stmt *Body, Scope *CurScope) {
13681 // If blocks are disabled, emit an error.
13682 if (!LangOpts.Blocks)
13683 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13685 // Leave the expression-evaluation context.
13686 if (hasAnyUnrecoverableErrorsInThisFunction())
13687 DiscardCleanupsInEvaluationContext();
13688 assert(!Cleanup.exprNeedsCleanups() &&
13689 "cleanups within block not correctly bound!");
13690 PopExpressionEvaluationContext();
13692 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13693 BlockDecl *BD = BSI->TheDecl;
13695 if (BSI->HasImplicitReturnType)
13696 deduceClosureReturnType(*BSI);
13700 QualType RetTy = Context.VoidTy;
13701 if (!BSI->ReturnType.isNull())
13702 RetTy = BSI->ReturnType;
13704 bool NoReturn = BD->hasAttr<NoReturnAttr>();
13707 // Set the captured variables on the block.
13708 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13709 SmallVector<BlockDecl::Capture, 4> Captures;
13710 for (Capture &Cap : BSI->Captures) {
13711 if (Cap.isThisCapture())
13713 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13714 Cap.isNested(), Cap.getInitExpr());
13715 Captures.push_back(NewCap);
13717 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13719 // If the user wrote a function type in some form, try to use that.
13720 if (!BSI->FunctionType.isNull()) {
13721 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13723 FunctionType::ExtInfo Ext = FTy->getExtInfo();
13724 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13726 // Turn protoless block types into nullary block types.
13727 if (isa<FunctionNoProtoType>(FTy)) {
13728 FunctionProtoType::ExtProtoInfo EPI;
13730 BlockTy = Context.getFunctionType(RetTy, None, EPI);
13732 // Otherwise, if we don't need to change anything about the function type,
13733 // preserve its sugar structure.
13734 } else if (FTy->getReturnType() == RetTy &&
13735 (!NoReturn || FTy->getNoReturnAttr())) {
13736 BlockTy = BSI->FunctionType;
13738 // Otherwise, make the minimal modifications to the function type.
13740 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13741 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13742 EPI.TypeQuals = Qualifiers();
13744 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13747 // If we don't have a function type, just build one from nothing.
13749 FunctionProtoType::ExtProtoInfo EPI;
13750 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13751 BlockTy = Context.getFunctionType(RetTy, None, EPI);
13754 DiagnoseUnusedParameters(BD->parameters());
13755 BlockTy = Context.getBlockPointerType(BlockTy);
13757 // If needed, diagnose invalid gotos and switches in the block.
13758 if (getCurFunction()->NeedsScopeChecking() &&
13759 !PP.isCodeCompletionEnabled())
13760 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13762 BD->setBody(cast<CompoundStmt>(Body));
13764 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13765 DiagnoseUnguardedAvailabilityViolations(BD);
13767 // Try to apply the named return value optimization. We have to check again
13768 // if we can do this, though, because blocks keep return statements around
13769 // to deduce an implicit return type.
13770 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13771 !BD->isDependentContext())
13772 computeNRVO(Body, BSI);
13774 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13775 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13776 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13778 // If the block isn't obviously global, i.e. it captures anything at
13779 // all, then we need to do a few things in the surrounding context:
13780 if (Result->getBlockDecl()->hasCaptures()) {
13781 // First, this expression has a new cleanup object.
13782 ExprCleanupObjects.push_back(Result->getBlockDecl());
13783 Cleanup.setExprNeedsCleanups(true);
13785 // It also gets a branch-protected scope if any of the captured
13786 // variables needs destruction.
13787 for (const auto &CI : Result->getBlockDecl()->captures()) {
13788 const VarDecl *var = CI.getVariable();
13789 if (var->getType().isDestructedType() != QualType::DK_none) {
13790 setFunctionHasBranchProtectedScope();
13796 if (getCurFunction())
13797 getCurFunction()->addBlock(BD);
13802 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13803 SourceLocation RPLoc) {
13804 TypeSourceInfo *TInfo;
13805 GetTypeFromParser(Ty, &TInfo);
13806 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13809 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13810 Expr *E, TypeSourceInfo *TInfo,
13811 SourceLocation RPLoc) {
13812 Expr *OrigExpr = E;
13815 // CUDA device code does not support varargs.
13816 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13817 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13818 CUDAFunctionTarget T = IdentifyCUDATarget(F);
13819 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13820 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13824 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13825 // as Microsoft ABI on an actual Microsoft platform, where
13826 // __builtin_ms_va_list and __builtin_va_list are the same.)
13827 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13828 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13829 QualType MSVaListType = Context.getBuiltinMSVaListType();
13830 if (Context.hasSameType(MSVaListType, E->getType())) {
13831 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13832 return ExprError();
13837 // Get the va_list type
13838 QualType VaListType = Context.getBuiltinVaListType();
13840 if (VaListType->isArrayType()) {
13841 // Deal with implicit array decay; for example, on x86-64,
13842 // va_list is an array, but it's supposed to decay to
13843 // a pointer for va_arg.
13844 VaListType = Context.getArrayDecayedType(VaListType);
13845 // Make sure the input expression also decays appropriately.
13846 ExprResult Result = UsualUnaryConversions(E);
13847 if (Result.isInvalid())
13848 return ExprError();
13850 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13851 // If va_list is a record type and we are compiling in C++ mode,
13852 // check the argument using reference binding.
13853 InitializedEntity Entity = InitializedEntity::InitializeParameter(
13854 Context, Context.getLValueReferenceType(VaListType), false);
13855 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13856 if (Init.isInvalid())
13857 return ExprError();
13858 E = Init.getAs<Expr>();
13860 // Otherwise, the va_list argument must be an l-value because
13861 // it is modified by va_arg.
13862 if (!E->isTypeDependent() &&
13863 CheckForModifiableLvalue(E, BuiltinLoc, *this))
13864 return ExprError();
13868 if (!IsMS && !E->isTypeDependent() &&
13869 !Context.hasSameType(VaListType, E->getType()))
13871 Diag(E->getBeginLoc(),
13872 diag::err_first_argument_to_va_arg_not_of_type_va_list)
13873 << OrigExpr->getType() << E->getSourceRange());
13875 if (!TInfo->getType()->isDependentType()) {
13876 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13877 diag::err_second_parameter_to_va_arg_incomplete,
13878 TInfo->getTypeLoc()))
13879 return ExprError();
13881 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13883 diag::err_second_parameter_to_va_arg_abstract,
13884 TInfo->getTypeLoc()))
13885 return ExprError();
13887 if (!TInfo->getType().isPODType(Context)) {
13888 Diag(TInfo->getTypeLoc().getBeginLoc(),
13889 TInfo->getType()->isObjCLifetimeType()
13890 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13891 : diag::warn_second_parameter_to_va_arg_not_pod)
13892 << TInfo->getType()
13893 << TInfo->getTypeLoc().getSourceRange();
13896 // Check for va_arg where arguments of the given type will be promoted
13897 // (i.e. this va_arg is guaranteed to have undefined behavior).
13898 QualType PromoteType;
13899 if (TInfo->getType()->isPromotableIntegerType()) {
13900 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13901 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13902 PromoteType = QualType();
13904 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13905 PromoteType = Context.DoubleTy;
13906 if (!PromoteType.isNull())
13907 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13908 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13909 << TInfo->getType()
13911 << TInfo->getTypeLoc().getSourceRange());
13914 QualType T = TInfo->getType().getNonLValueExprType(Context);
13915 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13918 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13919 // The type of __null will be int or long, depending on the size of
13920 // pointers on the target.
13922 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13923 if (pw == Context.getTargetInfo().getIntWidth())
13924 Ty = Context.IntTy;
13925 else if (pw == Context.getTargetInfo().getLongWidth())
13926 Ty = Context.LongTy;
13927 else if (pw == Context.getTargetInfo().getLongLongWidth())
13928 Ty = Context.LongLongTy;
13930 llvm_unreachable("I don't know size of pointer!");
13933 return new (Context) GNUNullExpr(Ty, TokenLoc);
13936 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13938 if (!getLangOpts().ObjC)
13941 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13945 if (!PT->isObjCIdType()) {
13946 // Check if the destination is the 'NSString' interface.
13947 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13948 if (!ID || !ID->getIdentifier()->isStr("NSString"))
13952 // Ignore any parens, implicit casts (should only be
13953 // array-to-pointer decays), and not-so-opaque values. The last is
13954 // important for making this trigger for property assignments.
13955 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13956 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13957 if (OV->getSourceExpr())
13958 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13960 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13961 if (!SL || !SL->isAscii())
13964 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
13965 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
13966 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
13971 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13972 const Expr *SrcExpr) {
13973 if (!DstType->isFunctionPointerType() ||
13974 !SrcExpr->getType()->isFunctionType())
13977 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13981 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13985 return !S.checkAddressOfFunctionIsAvailable(FD,
13987 SrcExpr->getBeginLoc());
13990 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13991 SourceLocation Loc,
13992 QualType DstType, QualType SrcType,
13993 Expr *SrcExpr, AssignmentAction Action,
13994 bool *Complained) {
13996 *Complained = false;
13998 // Decode the result (notice that AST's are still created for extensions).
13999 bool CheckInferredResultType = false;
14000 bool isInvalid = false;
14001 unsigned DiagKind = 0;
14003 ConversionFixItGenerator ConvHints;
14004 bool MayHaveConvFixit = false;
14005 bool MayHaveFunctionDiff = false;
14006 const ObjCInterfaceDecl *IFace = nullptr;
14007 const ObjCProtocolDecl *PDecl = nullptr;
14011 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14015 DiagKind = diag::ext_typecheck_convert_pointer_int;
14016 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14017 MayHaveConvFixit = true;
14020 DiagKind = diag::ext_typecheck_convert_int_pointer;
14021 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14022 MayHaveConvFixit = true;
14024 case IncompatiblePointer:
14025 if (Action == AA_Passing_CFAudited)
14026 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14027 else if (SrcType->isFunctionPointerType() &&
14028 DstType->isFunctionPointerType())
14029 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14031 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14033 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14034 SrcType->isObjCObjectPointerType();
14035 if (Hint.isNull() && !CheckInferredResultType) {
14036 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14038 else if (CheckInferredResultType) {
14039 SrcType = SrcType.getUnqualifiedType();
14040 DstType = DstType.getUnqualifiedType();
14042 MayHaveConvFixit = true;
14044 case IncompatiblePointerSign:
14045 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14047 case FunctionVoidPointer:
14048 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14050 case IncompatiblePointerDiscardsQualifiers: {
14051 // Perform array-to-pointer decay if necessary.
14052 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14054 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14055 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14056 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14057 DiagKind = diag::err_typecheck_incompatible_address_space;
14060 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14061 DiagKind = diag::err_typecheck_incompatible_ownership;
14065 llvm_unreachable("unknown error case for discarding qualifiers!");
14068 case CompatiblePointerDiscardsQualifiers:
14069 // If the qualifiers lost were because we were applying the
14070 // (deprecated) C++ conversion from a string literal to a char*
14071 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
14072 // Ideally, this check would be performed in
14073 // checkPointerTypesForAssignment. However, that would require a
14074 // bit of refactoring (so that the second argument is an
14075 // expression, rather than a type), which should be done as part
14076 // of a larger effort to fix checkPointerTypesForAssignment for
14078 if (getLangOpts().CPlusPlus &&
14079 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14081 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14083 case IncompatibleNestedPointerQualifiers:
14084 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14086 case IntToBlockPointer:
14087 DiagKind = diag::err_int_to_block_pointer;
14089 case IncompatibleBlockPointer:
14090 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14092 case IncompatibleObjCQualifiedId: {
14093 if (SrcType->isObjCQualifiedIdType()) {
14094 const ObjCObjectPointerType *srcOPT =
14095 SrcType->getAs<ObjCObjectPointerType>();
14096 for (auto *srcProto : srcOPT->quals()) {
14100 if (const ObjCInterfaceType *IFaceT =
14101 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14102 IFace = IFaceT->getDecl();
14104 else if (DstType->isObjCQualifiedIdType()) {
14105 const ObjCObjectPointerType *dstOPT =
14106 DstType->getAs<ObjCObjectPointerType>();
14107 for (auto *dstProto : dstOPT->quals()) {
14111 if (const ObjCInterfaceType *IFaceT =
14112 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14113 IFace = IFaceT->getDecl();
14115 DiagKind = diag::warn_incompatible_qualified_id;
14118 case IncompatibleVectors:
14119 DiagKind = diag::warn_incompatible_vectors;
14121 case IncompatibleObjCWeakRef:
14122 DiagKind = diag::err_arc_weak_unavailable_assign;
14125 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14127 *Complained = true;
14131 DiagKind = diag::err_typecheck_convert_incompatible;
14132 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14133 MayHaveConvFixit = true;
14135 MayHaveFunctionDiff = true;
14139 QualType FirstType, SecondType;
14142 case AA_Initializing:
14143 // The destination type comes first.
14144 FirstType = DstType;
14145 SecondType = SrcType;
14150 case AA_Passing_CFAudited:
14151 case AA_Converting:
14154 // The source type comes first.
14155 FirstType = SrcType;
14156 SecondType = DstType;
14160 PartialDiagnostic FDiag = PDiag(DiagKind);
14161 if (Action == AA_Passing_CFAudited)
14162 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14164 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14166 // If we can fix the conversion, suggest the FixIts.
14167 assert(ConvHints.isNull() || Hint.isNull());
14168 if (!ConvHints.isNull()) {
14169 for (FixItHint &H : ConvHints.Hints)
14174 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14176 if (MayHaveFunctionDiff)
14177 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14180 if (DiagKind == diag::warn_incompatible_qualified_id &&
14181 PDecl && IFace && !IFace->hasDefinition())
14182 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14185 if (SecondType == Context.OverloadTy)
14186 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14187 FirstType, /*TakingAddress=*/true);
14189 if (CheckInferredResultType)
14190 EmitRelatedResultTypeNote(SrcExpr);
14192 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14193 EmitRelatedResultTypeNoteForReturn(DstType);
14196 *Complained = true;
14200 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14201 llvm::APSInt *Result) {
14202 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14204 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14205 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14209 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14212 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14213 llvm::APSInt *Result,
14216 class IDDiagnoser : public VerifyICEDiagnoser {
14220 IDDiagnoser(unsigned DiagID)
14221 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14223 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14224 S.Diag(Loc, DiagID) << SR;
14226 } Diagnoser(DiagID);
14228 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14231 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14233 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14237 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14238 VerifyICEDiagnoser &Diagnoser,
14240 SourceLocation DiagLoc = E->getBeginLoc();
14242 if (getLangOpts().CPlusPlus11) {
14243 // C++11 [expr.const]p5:
14244 // If an expression of literal class type is used in a context where an
14245 // integral constant expression is required, then that class type shall
14246 // have a single non-explicit conversion function to an integral or
14247 // unscoped enumeration type
14248 ExprResult Converted;
14249 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14251 CXX11ConvertDiagnoser(bool Silent)
14252 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14255 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14256 QualType T) override {
14257 return S.Diag(Loc, diag::err_ice_not_integral) << T;
14260 SemaDiagnosticBuilder diagnoseIncomplete(
14261 Sema &S, SourceLocation Loc, QualType T) override {
14262 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14265 SemaDiagnosticBuilder diagnoseExplicitConv(
14266 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14267 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14270 SemaDiagnosticBuilder noteExplicitConv(
14271 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14272 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14273 << ConvTy->isEnumeralType() << ConvTy;
14276 SemaDiagnosticBuilder diagnoseAmbiguous(
14277 Sema &S, SourceLocation Loc, QualType T) override {
14278 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14281 SemaDiagnosticBuilder noteAmbiguous(
14282 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14283 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14284 << ConvTy->isEnumeralType() << ConvTy;
14287 SemaDiagnosticBuilder diagnoseConversion(
14288 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14289 llvm_unreachable("conversion functions are permitted");
14291 } ConvertDiagnoser(Diagnoser.Suppress);
14293 Converted = PerformContextualImplicitConversion(DiagLoc, E,
14295 if (Converted.isInvalid())
14297 E = Converted.get();
14298 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14299 return ExprError();
14300 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14301 // An ICE must be of integral or unscoped enumeration type.
14302 if (!Diagnoser.Suppress)
14303 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14304 return ExprError();
14307 if (!isa<ConstantExpr>(E))
14308 E = ConstantExpr::Create(Context, E);
14310 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14311 // in the non-ICE case.
14312 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14314 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14318 Expr::EvalResult EvalResult;
14319 SmallVector<PartialDiagnosticAt, 8> Notes;
14320 EvalResult.Diag = &Notes;
14322 // Try to evaluate the expression, and produce diagnostics explaining why it's
14323 // not a constant expression as a side-effect.
14324 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14325 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14327 // In C++11, we can rely on diagnostics being produced for any expression
14328 // which is not a constant expression. If no diagnostics were produced, then
14329 // this is a constant expression.
14330 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14332 *Result = EvalResult.Val.getInt();
14336 // If our only note is the usual "invalid subexpression" note, just point
14337 // the caret at its location rather than producing an essentially
14339 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14340 diag::note_invalid_subexpr_in_const_expr) {
14341 DiagLoc = Notes[0].first;
14345 if (!Folded || !AllowFold) {
14346 if (!Diagnoser.Suppress) {
14347 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14348 for (const PartialDiagnosticAt &Note : Notes)
14349 Diag(Note.first, Note.second);
14352 return ExprError();
14355 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14356 for (const PartialDiagnosticAt &Note : Notes)
14357 Diag(Note.first, Note.second);
14360 *Result = EvalResult.Val.getInt();
14365 // Handle the case where we conclude a expression which we speculatively
14366 // considered to be unevaluated is actually evaluated.
14367 class TransformToPE : public TreeTransform<TransformToPE> {
14368 typedef TreeTransform<TransformToPE> BaseTransform;
14371 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14373 // Make sure we redo semantic analysis
14374 bool AlwaysRebuild() { return true; }
14376 // Make sure we handle LabelStmts correctly.
14377 // FIXME: This does the right thing, but maybe we need a more general
14378 // fix to TreeTransform?
14379 StmtResult TransformLabelStmt(LabelStmt *S) {
14380 S->getDecl()->setStmt(nullptr);
14381 return BaseTransform::TransformLabelStmt(S);
14384 // We need to special-case DeclRefExprs referring to FieldDecls which
14385 // are not part of a member pointer formation; normal TreeTransforming
14386 // doesn't catch this case because of the way we represent them in the AST.
14387 // FIXME: This is a bit ugly; is it really the best way to handle this
14390 // Error on DeclRefExprs referring to FieldDecls.
14391 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14392 if (isa<FieldDecl>(E->getDecl()) &&
14393 !SemaRef.isUnevaluatedContext())
14394 return SemaRef.Diag(E->getLocation(),
14395 diag::err_invalid_non_static_member_use)
14396 << E->getDecl() << E->getSourceRange();
14398 return BaseTransform::TransformDeclRefExpr(E);
14401 // Exception: filter out member pointer formation
14402 ExprResult TransformUnaryOperator(UnaryOperator *E) {
14403 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14406 return BaseTransform::TransformUnaryOperator(E);
14409 ExprResult TransformLambdaExpr(LambdaExpr *E) {
14410 // Lambdas never need to be transformed.
14416 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14417 assert(isUnevaluatedContext() &&
14418 "Should only transform unevaluated expressions");
14419 ExprEvalContexts.back().Context =
14420 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14421 if (isUnevaluatedContext())
14423 return TransformToPE(*this).TransformExpr(E);
14427 Sema::PushExpressionEvaluationContext(
14428 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14429 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14430 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14431 LambdaContextDecl, ExprContext);
14433 if (!MaybeODRUseExprs.empty())
14434 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14438 Sema::PushExpressionEvaluationContext(
14439 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14440 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14441 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14442 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14447 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14448 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14449 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14450 if (E->getOpcode() == UO_Deref)
14451 return CheckPossibleDeref(S, E->getSubExpr());
14452 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14453 return CheckPossibleDeref(S, E->getBase());
14454 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14455 return CheckPossibleDeref(S, E->getBase());
14456 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14458 QualType Ty = E->getType();
14459 if (const auto *Ptr = Ty->getAs<PointerType>())
14460 Inner = Ptr->getPointeeType();
14461 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14462 Inner = Arr->getElementType();
14466 if (Inner->hasAttr(attr::NoDeref))
14474 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14475 for (const Expr *E : Rec.PossibleDerefs) {
14476 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14478 const ValueDecl *Decl = DeclRef->getDecl();
14479 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14480 << Decl->getName() << E->getSourceRange();
14481 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14483 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14484 << E->getSourceRange();
14487 Rec.PossibleDerefs.clear();
14490 void Sema::PopExpressionEvaluationContext() {
14491 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14492 unsigned NumTypos = Rec.NumTypos;
14494 if (!Rec.Lambdas.empty()) {
14495 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14496 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14497 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14499 if (Rec.isUnevaluated()) {
14500 // C++11 [expr.prim.lambda]p2:
14501 // A lambda-expression shall not appear in an unevaluated operand
14503 D = diag::err_lambda_unevaluated_operand;
14504 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14505 // C++1y [expr.const]p2:
14506 // A conditional-expression e is a core constant expression unless the
14507 // evaluation of e, following the rules of the abstract machine, would
14508 // evaluate [...] a lambda-expression.
14509 D = diag::err_lambda_in_constant_expression;
14510 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14511 // C++17 [expr.prim.lamda]p2:
14512 // A lambda-expression shall not appear [...] in a template-argument.
14513 D = diag::err_lambda_in_invalid_context;
14515 llvm_unreachable("Couldn't infer lambda error message.");
14517 for (const auto *L : Rec.Lambdas)
14518 Diag(L->getBeginLoc(), D);
14520 // Mark the capture expressions odr-used. This was deferred
14521 // during lambda expression creation.
14522 for (auto *Lambda : Rec.Lambdas) {
14523 for (auto *C : Lambda->capture_inits())
14524 MarkDeclarationsReferencedInExpr(C);
14529 WarnOnPendingNoDerefs(Rec);
14531 // When are coming out of an unevaluated context, clear out any
14532 // temporaries that we may have created as part of the evaluation of
14533 // the expression in that context: they aren't relevant because they
14534 // will never be constructed.
14535 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14536 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14537 ExprCleanupObjects.end());
14538 Cleanup = Rec.ParentCleanup;
14539 CleanupVarDeclMarking();
14540 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14541 // Otherwise, merge the contexts together.
14543 Cleanup.mergeFrom(Rec.ParentCleanup);
14544 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14545 Rec.SavedMaybeODRUseExprs.end());
14548 // Pop the current expression evaluation context off the stack.
14549 ExprEvalContexts.pop_back();
14551 // The global expression evaluation context record is never popped.
14552 ExprEvalContexts.back().NumTypos += NumTypos;
14555 void Sema::DiscardCleanupsInEvaluationContext() {
14556 ExprCleanupObjects.erase(
14557 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14558 ExprCleanupObjects.end());
14560 MaybeODRUseExprs.clear();
14563 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14564 ExprResult Result = CheckPlaceholderExpr(E);
14565 if (Result.isInvalid())
14566 return ExprError();
14568 if (!E->getType()->isVariablyModifiedType())
14570 return TransformToPotentiallyEvaluated(E);
14573 /// Are we within a context in which some evaluation could be performed (be it
14574 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14575 /// captured by C++'s idea of an "unevaluated context".
14576 static bool isEvaluatableContext(Sema &SemaRef) {
14577 switch (SemaRef.ExprEvalContexts.back().Context) {
14578 case Sema::ExpressionEvaluationContext::Unevaluated:
14579 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14580 // Expressions in this context are never evaluated.
14583 case Sema::ExpressionEvaluationContext::UnevaluatedList:
14584 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14585 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14586 case Sema::ExpressionEvaluationContext::DiscardedStatement:
14587 // Expressions in this context could be evaluated.
14590 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14591 // Referenced declarations will only be used if the construct in the
14592 // containing expression is used, at which point we'll be given another
14593 // turn to mark them.
14596 llvm_unreachable("Invalid context");
14599 /// Are we within a context in which references to resolved functions or to
14600 /// variables result in odr-use?
14601 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14602 // An expression in a template is not really an expression until it's been
14603 // instantiated, so it doesn't trigger odr-use.
14604 if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14607 switch (SemaRef.ExprEvalContexts.back().Context) {
14608 case Sema::ExpressionEvaluationContext::Unevaluated:
14609 case Sema::ExpressionEvaluationContext::UnevaluatedList:
14610 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14611 case Sema::ExpressionEvaluationContext::DiscardedStatement:
14614 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14615 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14618 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14621 llvm_unreachable("Invalid context");
14624 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14625 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14626 return Func->isConstexpr() &&
14627 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14630 /// Mark a function referenced, and check whether it is odr-used
14631 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14632 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14633 bool MightBeOdrUse) {
14634 assert(Func && "No function?");
14636 Func->setReferenced();
14638 // C++11 [basic.def.odr]p3:
14639 // A function whose name appears as a potentially-evaluated expression is
14640 // odr-used if it is the unique lookup result or the selected member of a
14641 // set of overloaded functions [...].
14643 // We (incorrectly) mark overload resolution as an unevaluated context, so we
14644 // can just check that here.
14645 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14647 // Determine whether we require a function definition to exist, per
14648 // C++11 [temp.inst]p3:
14649 // Unless a function template specialization has been explicitly
14650 // instantiated or explicitly specialized, the function template
14651 // specialization is implicitly instantiated when the specialization is
14652 // referenced in a context that requires a function definition to exist.
14654 // That is either when this is an odr-use, or when a usage of a constexpr
14655 // function occurs within an evaluatable context.
14656 bool NeedDefinition =
14657 OdrUse || (isEvaluatableContext(*this) &&
14658 isImplicitlyDefinableConstexprFunction(Func));
14660 // C++14 [temp.expl.spec]p6:
14661 // If a template [...] is explicitly specialized then that specialization
14662 // shall be declared before the first use of that specialization that would
14663 // cause an implicit instantiation to take place, in every translation unit
14664 // in which such a use occurs
14665 if (NeedDefinition &&
14666 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14667 Func->getMemberSpecializationInfo()))
14668 checkSpecializationVisibility(Loc, Func);
14670 // C++14 [except.spec]p17:
14671 // An exception-specification is considered to be needed when:
14672 // - the function is odr-used or, if it appears in an unevaluated operand,
14673 // would be odr-used if the expression were potentially-evaluated;
14675 // Note, we do this even if MightBeOdrUse is false. That indicates that the
14676 // function is a pure virtual function we're calling, and in that case the
14677 // function was selected by overload resolution and we need to resolve its
14678 // exception specification for a different reason.
14679 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14680 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14681 ResolveExceptionSpec(Loc, FPT);
14683 // If we don't need to mark the function as used, and we don't need to
14684 // try to provide a definition, there's nothing more to do.
14685 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14686 (!NeedDefinition || Func->getBody()))
14689 // Note that this declaration has been used.
14690 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14691 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14692 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14693 if (Constructor->isDefaultConstructor()) {
14694 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14696 DefineImplicitDefaultConstructor(Loc, Constructor);
14697 } else if (Constructor->isCopyConstructor()) {
14698 DefineImplicitCopyConstructor(Loc, Constructor);
14699 } else if (Constructor->isMoveConstructor()) {
14700 DefineImplicitMoveConstructor(Loc, Constructor);
14702 } else if (Constructor->getInheritedConstructor()) {
14703 DefineInheritingConstructor(Loc, Constructor);
14705 } else if (CXXDestructorDecl *Destructor =
14706 dyn_cast<CXXDestructorDecl>(Func)) {
14707 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14708 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14709 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14711 DefineImplicitDestructor(Loc, Destructor);
14713 if (Destructor->isVirtual() && getLangOpts().AppleKext)
14714 MarkVTableUsed(Loc, Destructor->getParent());
14715 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14716 if (MethodDecl->isOverloadedOperator() &&
14717 MethodDecl->getOverloadedOperator() == OO_Equal) {
14718 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14719 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14720 if (MethodDecl->isCopyAssignmentOperator())
14721 DefineImplicitCopyAssignment(Loc, MethodDecl);
14722 else if (MethodDecl->isMoveAssignmentOperator())
14723 DefineImplicitMoveAssignment(Loc, MethodDecl);
14725 } else if (isa<CXXConversionDecl>(MethodDecl) &&
14726 MethodDecl->getParent()->isLambda()) {
14727 CXXConversionDecl *Conversion =
14728 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14729 if (Conversion->isLambdaToBlockPointerConversion())
14730 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14732 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14733 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14734 MarkVTableUsed(Loc, MethodDecl->getParent());
14737 // Recursive functions should be marked when used from another function.
14738 // FIXME: Is this really right?
14739 if (CurContext == Func) return;
14741 // Implicit instantiation of function templates and member functions of
14742 // class templates.
14743 if (Func->isImplicitlyInstantiable()) {
14744 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14745 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14746 bool FirstInstantiation = PointOfInstantiation.isInvalid();
14747 if (FirstInstantiation) {
14748 PointOfInstantiation = Loc;
14749 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14750 } else if (TSK != TSK_ImplicitInstantiation) {
14751 // Use the point of use as the point of instantiation, instead of the
14752 // point of explicit instantiation (which we track as the actual point of
14753 // instantiation). This gives better backtraces in diagnostics.
14754 PointOfInstantiation = Loc;
14757 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14758 Func->isConstexpr()) {
14759 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14760 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14761 CodeSynthesisContexts.size())
14762 PendingLocalImplicitInstantiations.push_back(
14763 std::make_pair(Func, PointOfInstantiation));
14764 else if (Func->isConstexpr())
14765 // Do not defer instantiations of constexpr functions, to avoid the
14766 // expression evaluator needing to call back into Sema if it sees a
14767 // call to such a function.
14768 InstantiateFunctionDefinition(PointOfInstantiation, Func);
14770 Func->setInstantiationIsPending(true);
14771 PendingInstantiations.push_back(std::make_pair(Func,
14772 PointOfInstantiation));
14773 // Notify the consumer that a function was implicitly instantiated.
14774 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14778 // Walk redefinitions, as some of them may be instantiable.
14779 for (auto i : Func->redecls()) {
14780 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14781 MarkFunctionReferenced(Loc, i, OdrUse);
14785 if (!OdrUse) return;
14787 // Keep track of used but undefined functions.
14788 if (!Func->isDefined()) {
14789 if (mightHaveNonExternalLinkage(Func))
14790 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14791 else if (Func->getMostRecentDecl()->isInlined() &&
14792 !LangOpts.GNUInline &&
14793 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14794 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14795 else if (isExternalWithNoLinkageType(Func))
14796 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14799 Func->markUsed(Context);
14803 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14804 ValueDecl *var, DeclContext *DC) {
14805 DeclContext *VarDC = var->getDeclContext();
14807 // If the parameter still belongs to the translation unit, then
14808 // we're actually just using one parameter in the declaration of
14810 if (isa<ParmVarDecl>(var) &&
14811 isa<TranslationUnitDecl>(VarDC))
14814 // For C code, don't diagnose about capture if we're not actually in code
14815 // right now; it's impossible to write a non-constant expression outside of
14816 // function context, so we'll get other (more useful) diagnostics later.
14818 // For C++, things get a bit more nasty... it would be nice to suppress this
14819 // diagnostic for certain cases like using a local variable in an array bound
14820 // for a member of a local class, but the correct predicate is not obvious.
14821 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14824 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14825 unsigned ContextKind = 3; // unknown
14826 if (isa<CXXMethodDecl>(VarDC) &&
14827 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14829 } else if (isa<FunctionDecl>(VarDC)) {
14831 } else if (isa<BlockDecl>(VarDC)) {
14835 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14836 << var << ValueKind << ContextKind << VarDC;
14837 S.Diag(var->getLocation(), diag::note_entity_declared_at)
14840 // FIXME: Add additional diagnostic info about class etc. which prevents
14845 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14846 bool &SubCapturesAreNested,
14847 QualType &CaptureType,
14848 QualType &DeclRefType) {
14849 // Check whether we've already captured it.
14850 if (CSI->CaptureMap.count(Var)) {
14851 // If we found a capture, any subcaptures are nested.
14852 SubCapturesAreNested = true;
14854 // Retrieve the capture type for this variable.
14855 CaptureType = CSI->getCapture(Var).getCaptureType();
14857 // Compute the type of an expression that refers to this variable.
14858 DeclRefType = CaptureType.getNonReferenceType();
14860 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14861 // are mutable in the sense that user can change their value - they are
14862 // private instances of the captured declarations.
14863 const Capture &Cap = CSI->getCapture(Var);
14864 if (Cap.isCopyCapture() &&
14865 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14866 !(isa<CapturedRegionScopeInfo>(CSI) &&
14867 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14868 DeclRefType.addConst();
14874 // Only block literals, captured statements, and lambda expressions can
14875 // capture; other scopes don't work.
14876 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14877 SourceLocation Loc,
14878 const bool Diagnose, Sema &S) {
14879 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14880 return getLambdaAwareParentOfDeclContext(DC);
14881 else if (Var->hasLocalStorage()) {
14883 diagnoseUncapturableValueReference(S, Loc, Var, DC);
14888 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14889 // certain types of variables (unnamed, variably modified types etc.)
14890 // so check for eligibility.
14891 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14892 SourceLocation Loc,
14893 const bool Diagnose, Sema &S) {
14895 bool IsBlock = isa<BlockScopeInfo>(CSI);
14896 bool IsLambda = isa<LambdaScopeInfo>(CSI);
14898 // Lambdas are not allowed to capture unnamed variables
14899 // (e.g. anonymous unions).
14900 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14901 // assuming that's the intent.
14902 if (IsLambda && !Var->getDeclName()) {
14904 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14905 S.Diag(Var->getLocation(), diag::note_declared_at);
14910 // Prohibit variably-modified types in blocks; they're difficult to deal with.
14911 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14913 S.Diag(Loc, diag::err_ref_vm_type);
14914 S.Diag(Var->getLocation(), diag::note_previous_decl)
14915 << Var->getDeclName();
14919 // Prohibit structs with flexible array members too.
14920 // We cannot capture what is in the tail end of the struct.
14921 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14922 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14925 S.Diag(Loc, diag::err_ref_flexarray_type);
14927 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14928 << Var->getDeclName();
14929 S.Diag(Var->getLocation(), diag::note_previous_decl)
14930 << Var->getDeclName();
14935 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14936 // Lambdas and captured statements are not allowed to capture __block
14937 // variables; they don't support the expected semantics.
14938 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14940 S.Diag(Loc, diag::err_capture_block_variable)
14941 << Var->getDeclName() << !IsLambda;
14942 S.Diag(Var->getLocation(), diag::note_previous_decl)
14943 << Var->getDeclName();
14947 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14948 if (S.getLangOpts().OpenCL && IsBlock &&
14949 Var->getType()->isBlockPointerType()) {
14951 S.Diag(Loc, diag::err_opencl_block_ref_block);
14958 // Returns true if the capture by block was successful.
14959 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14960 SourceLocation Loc,
14961 const bool BuildAndDiagnose,
14962 QualType &CaptureType,
14963 QualType &DeclRefType,
14966 Expr *CopyExpr = nullptr;
14967 bool ByRef = false;
14969 // Blocks are not allowed to capture arrays, excepting OpenCL.
14970 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
14971 // (decayed to pointers).
14972 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
14973 if (BuildAndDiagnose) {
14974 S.Diag(Loc, diag::err_ref_array_type);
14975 S.Diag(Var->getLocation(), diag::note_previous_decl)
14976 << Var->getDeclName();
14981 // Forbid the block-capture of autoreleasing variables.
14982 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14983 if (BuildAndDiagnose) {
14984 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14986 S.Diag(Var->getLocation(), diag::note_previous_decl)
14987 << Var->getDeclName();
14992 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14993 if (const auto *PT = CaptureType->getAs<PointerType>()) {
14994 // This function finds out whether there is an AttributedType of kind
14995 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
14996 // attr::ObjCOwnership implies __autoreleasing was explicitly specified
14997 // rather than being added implicitly by the compiler.
14998 auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14999 while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15000 if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15003 // Peel off AttributedTypes that are not of kind ObjCOwnership.
15004 Ty = AttrTy->getModifiedType();
15010 QualType PointeeTy = PT->getPointeeType();
15012 if (PointeeTy->getAs<ObjCObjectPointerType>() &&
15013 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15014 !IsObjCOwnershipAttributedType(PointeeTy)) {
15015 if (BuildAndDiagnose) {
15016 SourceLocation VarLoc = Var->getLocation();
15017 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15018 S.Diag(VarLoc, diag::note_declare_parameter_strong);
15023 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15024 if (HasBlocksAttr || CaptureType->isReferenceType() ||
15025 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15026 // Block capture by reference does not change the capture or
15027 // declaration reference types.
15030 // Block capture by copy introduces 'const'.
15031 CaptureType = CaptureType.getNonReferenceType().withConst();
15032 DeclRefType = CaptureType;
15034 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
15035 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
15036 // The capture logic needs the destructor, so make sure we mark it.
15037 // Usually this is unnecessary because most local variables have
15038 // their destructors marked at declaration time, but parameters are
15039 // an exception because it's technically only the call site that
15040 // actually requires the destructor.
15041 if (isa<ParmVarDecl>(Var))
15042 S.FinalizeVarWithDestructor(Var, Record);
15044 // Enter a new evaluation context to insulate the copy
15045 // full-expression.
15046 EnterExpressionEvaluationContext scope(
15047 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
15049 // According to the blocks spec, the capture of a variable from
15050 // the stack requires a const copy constructor. This is not true
15051 // of the copy/move done to move a __block variable to the heap.
15052 Expr *DeclRef = new (S.Context) DeclRefExpr(
15053 S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc);
15056 = S.PerformCopyInitialization(
15057 InitializedEntity::InitializeBlock(Var->getLocation(),
15058 CaptureType, false),
15061 // Build a full-expression copy expression if initialization
15062 // succeeded and used a non-trivial constructor. Recover from
15063 // errors by pretending that the copy isn't necessary.
15064 if (!Result.isInvalid() &&
15065 !cast<CXXConstructExpr>(Result.get())->getConstructor()
15067 Result = S.MaybeCreateExprWithCleanups(Result);
15068 CopyExpr = Result.get();
15074 // Actually capture the variable.
15075 if (BuildAndDiagnose)
15076 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
15077 SourceLocation(), CaptureType, CopyExpr);
15084 /// Capture the given variable in the captured region.
15085 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15087 SourceLocation Loc,
15088 const bool BuildAndDiagnose,
15089 QualType &CaptureType,
15090 QualType &DeclRefType,
15091 const bool RefersToCapturedVariable,
15093 // By default, capture variables by reference.
15095 // Using an LValue reference type is consistent with Lambdas (see below).
15096 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15097 if (S.isOpenMPCapturedDecl(Var)) {
15098 bool HasConst = DeclRefType.isConstQualified();
15099 DeclRefType = DeclRefType.getUnqualifiedType();
15100 // Don't lose diagnostics about assignments to const.
15102 DeclRefType.addConst();
15104 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15108 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15110 CaptureType = DeclRefType;
15112 Expr *CopyExpr = nullptr;
15113 if (BuildAndDiagnose) {
15114 // The current implementation assumes that all variables are captured
15115 // by references. Since there is no capture by copy, no expression
15116 // evaluation will be needed.
15117 RecordDecl *RD = RSI->TheRecordDecl;
15120 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
15121 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
15122 nullptr, false, ICIS_NoInit);
15123 Field->setImplicit(true);
15124 Field->setAccess(AS_private);
15125 RD->addDecl(Field);
15126 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
15127 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
15129 CopyExpr = new (S.Context) DeclRefExpr(
15130 S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc);
15131 Var->setReferenced(true);
15132 Var->markUsed(S.Context);
15135 // Actually capture the variable.
15136 if (BuildAndDiagnose)
15137 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
15138 SourceLocation(), CaptureType, CopyExpr);
15144 /// Create a field within the lambda class for the variable
15145 /// being captured.
15146 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
15147 QualType FieldType, QualType DeclRefType,
15148 SourceLocation Loc,
15149 bool RefersToCapturedVariable) {
15150 CXXRecordDecl *Lambda = LSI->Lambda;
15152 // Build the non-static data member.
15154 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
15155 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
15156 nullptr, false, ICIS_NoInit);
15157 // If the variable being captured has an invalid type, mark the lambda class
15158 // as invalid as well.
15159 if (!FieldType->isDependentType()) {
15160 if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
15161 Lambda->setInvalidDecl();
15162 Field->setInvalidDecl();
15165 FieldType->isIncompleteType(&Def);
15166 if (Def && Def->isInvalidDecl()) {
15167 Lambda->setInvalidDecl();
15168 Field->setInvalidDecl();
15172 Field->setImplicit(true);
15173 Field->setAccess(AS_private);
15174 Lambda->addDecl(Field);
15177 /// Capture the given variable in the lambda.
15178 static bool captureInLambda(LambdaScopeInfo *LSI,
15180 SourceLocation Loc,
15181 const bool BuildAndDiagnose,
15182 QualType &CaptureType,
15183 QualType &DeclRefType,
15184 const bool RefersToCapturedVariable,
15185 const Sema::TryCaptureKind Kind,
15186 SourceLocation EllipsisLoc,
15187 const bool IsTopScope,
15190 // Determine whether we are capturing by reference or by value.
15191 bool ByRef = false;
15192 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15193 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15195 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15198 // Compute the type of the field that will capture this variable.
15200 // C++11 [expr.prim.lambda]p15:
15201 // An entity is captured by reference if it is implicitly or
15202 // explicitly captured but not captured by copy. It is
15203 // unspecified whether additional unnamed non-static data
15204 // members are declared in the closure type for entities
15205 // captured by reference.
15207 // FIXME: It is not clear whether we want to build an lvalue reference
15208 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15209 // to do the former, while EDG does the latter. Core issue 1249 will
15210 // clarify, but for now we follow GCC because it's a more permissive and
15211 // easily defensible position.
15212 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15214 // C++11 [expr.prim.lambda]p14:
15215 // For each entity captured by copy, an unnamed non-static
15216 // data member is declared in the closure type. The
15217 // declaration order of these members is unspecified. The type
15218 // of such a data member is the type of the corresponding
15219 // captured entity if the entity is not a reference to an
15220 // object, or the referenced type otherwise. [Note: If the
15221 // captured entity is a reference to a function, the
15222 // corresponding data member is also a reference to a
15223 // function. - end note ]
15224 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15225 if (!RefType->getPointeeType()->isFunctionType())
15226 CaptureType = RefType->getPointeeType();
15229 // Forbid the lambda copy-capture of autoreleasing variables.
15230 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15231 if (BuildAndDiagnose) {
15232 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15233 S.Diag(Var->getLocation(), diag::note_previous_decl)
15234 << Var->getDeclName();
15239 // Make sure that by-copy captures are of a complete and non-abstract type.
15240 if (BuildAndDiagnose) {
15241 if (!CaptureType->isDependentType() &&
15242 S.RequireCompleteType(Loc, CaptureType,
15243 diag::err_capture_of_incomplete_type,
15244 Var->getDeclName()))
15247 if (S.RequireNonAbstractType(Loc, CaptureType,
15248 diag::err_capture_of_abstract_type))
15253 // Capture this variable in the lambda.
15254 if (BuildAndDiagnose)
15255 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15256 RefersToCapturedVariable);
15258 // Compute the type of a reference to this captured variable.
15260 DeclRefType = CaptureType.getNonReferenceType();
15262 // C++ [expr.prim.lambda]p5:
15263 // The closure type for a lambda-expression has a public inline
15264 // function call operator [...]. This function call operator is
15265 // declared const (9.3.1) if and only if the lambda-expression's
15266 // parameter-declaration-clause is not followed by mutable.
15267 DeclRefType = CaptureType.getNonReferenceType();
15268 if (!LSI->Mutable && !CaptureType->isReferenceType())
15269 DeclRefType.addConst();
15272 // Add the capture.
15273 if (BuildAndDiagnose)
15274 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15275 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15280 bool Sema::tryCaptureVariable(
15281 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15282 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15283 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15284 // An init-capture is notionally from the context surrounding its
15285 // declaration, but its parent DC is the lambda class.
15286 DeclContext *VarDC = Var->getDeclContext();
15287 if (Var->isInitCapture())
15288 VarDC = VarDC->getParent();
15290 DeclContext *DC = CurContext;
15291 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15292 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15293 // We need to sync up the Declaration Context with the
15294 // FunctionScopeIndexToStopAt
15295 if (FunctionScopeIndexToStopAt) {
15296 unsigned FSIndex = FunctionScopes.size() - 1;
15297 while (FSIndex != MaxFunctionScopesIndex) {
15298 DC = getLambdaAwareParentOfDeclContext(DC);
15304 // If the variable is declared in the current context, there is no need to
15306 if (VarDC == DC) return true;
15308 // Capture global variables if it is required to use private copy of this
15310 bool IsGlobal = !Var->hasLocalStorage();
15311 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15313 Var = Var->getCanonicalDecl();
15315 // Walk up the stack to determine whether we can capture the variable,
15316 // performing the "simple" checks that don't depend on type. We stop when
15317 // we've either hit the declared scope of the variable or find an existing
15318 // capture of that variable. We start from the innermost capturing-entity
15319 // (the DC) and ensure that all intervening capturing-entities
15320 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15321 // declcontext can either capture the variable or have already captured
15323 CaptureType = Var->getType();
15324 DeclRefType = CaptureType.getNonReferenceType();
15325 bool Nested = false;
15326 bool Explicit = (Kind != TryCapture_Implicit);
15327 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15329 // Only block literals, captured statements, and lambda expressions can
15330 // capture; other scopes don't work.
15331 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15335 // We need to check for the parent *first* because, if we *have*
15336 // private-captured a global variable, we need to recursively capture it in
15337 // intermediate blocks, lambdas, etc.
15340 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15346 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
15347 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15350 // Check whether we've already captured it.
15351 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15353 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15356 // If we are instantiating a generic lambda call operator body,
15357 // we do not want to capture new variables. What was captured
15358 // during either a lambdas transformation or initial parsing
15360 if (isGenericLambdaCallOperatorSpecialization(DC)) {
15361 if (BuildAndDiagnose) {
15362 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15363 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15364 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15365 Diag(Var->getLocation(), diag::note_previous_decl)
15366 << Var->getDeclName();
15367 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15369 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15373 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15374 // certain types of variables (unnamed, variably modified types etc.)
15375 // so check for eligibility.
15376 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15379 // Try to capture variable-length arrays types.
15380 if (Var->getType()->isVariablyModifiedType()) {
15381 // We're going to walk down into the type and look for VLA
15383 QualType QTy = Var->getType();
15384 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15385 QTy = PVD->getOriginalType();
15386 captureVariablyModifiedType(Context, QTy, CSI);
15389 if (getLangOpts().OpenMP) {
15390 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15391 // OpenMP private variables should not be captured in outer scope, so
15392 // just break here. Similarly, global variables that are captured in a
15393 // target region should not be captured outside the scope of the region.
15394 if (RSI->CapRegionKind == CR_OpenMP) {
15395 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15396 auto IsTargetCap = !IsOpenMPPrivateDecl &&
15397 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15398 // When we detect target captures we are looking from inside the
15399 // target region, therefore we need to propagate the capture from the
15400 // enclosing region. Therefore, the capture is not initially nested.
15402 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15404 if (IsTargetCap || IsOpenMPPrivateDecl) {
15405 Nested = !IsTargetCap;
15406 DeclRefType = DeclRefType.getUnqualifiedType();
15407 CaptureType = Context.getLValueReferenceType(DeclRefType);
15413 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15414 // No capture-default, and this is not an explicit capture
15415 // so cannot capture this variable.
15416 if (BuildAndDiagnose) {
15417 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15418 Diag(Var->getLocation(), diag::note_previous_decl)
15419 << Var->getDeclName();
15420 if (cast<LambdaScopeInfo>(CSI)->Lambda)
15421 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15422 diag::note_lambda_decl);
15423 // FIXME: If we error out because an outer lambda can not implicitly
15424 // capture a variable that an inner lambda explicitly captures, we
15425 // should have the inner lambda do the explicit capture - because
15426 // it makes for cleaner diagnostics later. This would purely be done
15427 // so that the diagnostic does not misleadingly claim that a variable
15428 // can not be captured by a lambda implicitly even though it is captured
15429 // explicitly. Suggestion:
15430 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15431 // at the function head
15432 // - cache the StartingDeclContext - this must be a lambda
15433 // - captureInLambda in the innermost lambda the variable.
15438 FunctionScopesIndex--;
15441 } while (!VarDC->Equals(DC));
15443 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15444 // computing the type of the capture at each step, checking type-specific
15445 // requirements, and adding captures if requested.
15446 // If the variable had already been captured previously, we start capturing
15447 // at the lambda nested within that one.
15448 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15450 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15452 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15453 if (!captureInBlock(BSI, Var, ExprLoc,
15454 BuildAndDiagnose, CaptureType,
15455 DeclRefType, Nested, *this))
15458 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15459 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15460 BuildAndDiagnose, CaptureType,
15461 DeclRefType, Nested, *this))
15465 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15466 if (!captureInLambda(LSI, Var, ExprLoc,
15467 BuildAndDiagnose, CaptureType,
15468 DeclRefType, Nested, Kind, EllipsisLoc,
15469 /*IsTopScope*/I == N - 1, *this))
15477 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15478 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15479 QualType CaptureType;
15480 QualType DeclRefType;
15481 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15482 /*BuildAndDiagnose=*/true, CaptureType,
15483 DeclRefType, nullptr);
15486 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15487 QualType CaptureType;
15488 QualType DeclRefType;
15489 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15490 /*BuildAndDiagnose=*/false, CaptureType,
15491 DeclRefType, nullptr);
15494 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15495 QualType CaptureType;
15496 QualType DeclRefType;
15498 // Determine whether we can capture this variable.
15499 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15500 /*BuildAndDiagnose=*/false, CaptureType,
15501 DeclRefType, nullptr))
15504 return DeclRefType;
15509 // If either the type of the variable or the initializer is dependent,
15510 // return false. Otherwise, determine whether the variable is a constant
15511 // expression. Use this if you need to know if a variable that might or
15512 // might not be dependent is truly a constant expression.
15513 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15514 ASTContext &Context) {
15516 if (Var->getType()->isDependentType())
15518 const VarDecl *DefVD = nullptr;
15519 Var->getAnyInitializer(DefVD);
15522 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15523 Expr *Init = cast<Expr>(Eval->Value);
15524 if (Init->isValueDependent())
15526 return IsVariableAConstantExpression(Var, Context);
15530 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15531 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15532 // an object that satisfies the requirements for appearing in a
15533 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15534 // is immediately applied." This function handles the lvalue-to-rvalue
15535 // conversion part.
15536 MaybeODRUseExprs.erase(E->IgnoreParens());
15538 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15539 // to a variable that is a constant expression, and if so, identify it as
15540 // a reference to a variable that does not involve an odr-use of that
15542 if (LambdaScopeInfo *LSI = getCurLambda()) {
15543 Expr *SansParensExpr = E->IgnoreParens();
15544 VarDecl *Var = nullptr;
15545 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15546 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15547 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15548 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15550 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15551 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15555 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15556 Res = CorrectDelayedTyposInExpr(Res);
15558 if (!Res.isUsable())
15561 // If a constant-expression is a reference to a variable where we delay
15562 // deciding whether it is an odr-use, just assume we will apply the
15563 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
15564 // (a non-type template argument), we have special handling anyway.
15565 UpdateMarkingForLValueToRValue(Res.get());
15569 void Sema::CleanupVarDeclMarking() {
15570 for (Expr *E : MaybeODRUseExprs) {
15572 SourceLocation Loc;
15573 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15574 Var = cast<VarDecl>(DRE->getDecl());
15575 Loc = DRE->getLocation();
15576 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15577 Var = cast<VarDecl>(ME->getMemberDecl());
15578 Loc = ME->getMemberLoc();
15580 llvm_unreachable("Unexpected expression");
15583 MarkVarDeclODRUsed(Var, Loc, *this,
15584 /*MaxFunctionScopeIndex Pointer*/ nullptr);
15587 MaybeODRUseExprs.clear();
15591 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15592 VarDecl *Var, Expr *E) {
15593 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15594 "Invalid Expr argument to DoMarkVarDeclReferenced");
15595 Var->setReferenced();
15597 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15599 bool OdrUseContext = isOdrUseContext(SemaRef);
15600 bool UsableInConstantExpr =
15601 Var->isUsableInConstantExpressions(SemaRef.Context);
15602 bool NeedDefinition =
15603 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15605 VarTemplateSpecializationDecl *VarSpec =
15606 dyn_cast<VarTemplateSpecializationDecl>(Var);
15607 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15608 "Can't instantiate a partial template specialization.");
15610 // If this might be a member specialization of a static data member, check
15611 // the specialization is visible. We already did the checks for variable
15612 // template specializations when we created them.
15613 if (NeedDefinition && TSK != TSK_Undeclared &&
15614 !isa<VarTemplateSpecializationDecl>(Var))
15615 SemaRef.checkSpecializationVisibility(Loc, Var);
15617 // Perform implicit instantiation of static data members, static data member
15618 // templates of class templates, and variable template specializations. Delay
15619 // instantiations of variable templates, except for those that could be used
15620 // in a constant expression.
15621 if (NeedDefinition && isTemplateInstantiation(TSK)) {
15622 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15623 // instantiation declaration if a variable is usable in a constant
15624 // expression (among other cases).
15625 bool TryInstantiating =
15626 TSK == TSK_ImplicitInstantiation ||
15627 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15629 if (TryInstantiating) {
15630 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15631 bool FirstInstantiation = PointOfInstantiation.isInvalid();
15632 if (FirstInstantiation) {
15633 PointOfInstantiation = Loc;
15634 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15637 bool InstantiationDependent = false;
15638 bool IsNonDependent =
15639 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15640 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15643 // Do not instantiate specializations that are still type-dependent.
15644 if (IsNonDependent) {
15645 if (UsableInConstantExpr) {
15646 // Do not defer instantiations of variables that could be used in a
15647 // constant expression.
15648 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15649 } else if (FirstInstantiation ||
15650 isa<VarTemplateSpecializationDecl>(Var)) {
15651 // FIXME: For a specialization of a variable template, we don't
15652 // distinguish between "declaration and type implicitly instantiated"
15653 // and "implicit instantiation of definition requested", so we have
15654 // no direct way to avoid enqueueing the pending instantiation
15656 SemaRef.PendingInstantiations
15657 .push_back(std::make_pair(Var, PointOfInstantiation));
15663 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15664 // the requirements for appearing in a constant expression (5.19) and, if
15665 // it is an object, the lvalue-to-rvalue conversion (4.1)
15666 // is immediately applied." We check the first part here, and
15667 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15668 // Note that we use the C++11 definition everywhere because nothing in
15669 // C++03 depends on whether we get the C++03 version correct. The second
15670 // part does not apply to references, since they are not objects.
15671 if (OdrUseContext && E &&
15672 IsVariableAConstantExpression(Var, SemaRef.Context)) {
15673 // A reference initialized by a constant expression can never be
15674 // odr-used, so simply ignore it.
15675 if (!Var->getType()->isReferenceType() ||
15676 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15677 SemaRef.MaybeODRUseExprs.insert(E);
15678 } else if (OdrUseContext) {
15679 MarkVarDeclODRUsed(Var, Loc, SemaRef,
15680 /*MaxFunctionScopeIndex ptr*/ nullptr);
15681 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15682 // If this is a dependent context, we don't need to mark variables as
15683 // odr-used, but we may still need to track them for lambda capture.
15684 // FIXME: Do we also need to do this inside dependent typeid expressions
15685 // (which are modeled as unevaluated at this point)?
15686 const bool RefersToEnclosingScope =
15687 (SemaRef.CurContext != Var->getDeclContext() &&
15688 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15689 if (RefersToEnclosingScope) {
15690 LambdaScopeInfo *const LSI =
15691 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15692 if (LSI && (!LSI->CallOperator ||
15693 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15694 // If a variable could potentially be odr-used, defer marking it so
15695 // until we finish analyzing the full expression for any
15696 // lvalue-to-rvalue
15697 // or discarded value conversions that would obviate odr-use.
15698 // Add it to the list of potential captures that will be analyzed
15699 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15700 // unless the variable is a reference that was initialized by a constant
15701 // expression (this will never need to be captured or odr-used).
15702 assert(E && "Capture variable should be used in an expression.");
15703 if (!Var->getType()->isReferenceType() ||
15704 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15705 LSI->addPotentialCapture(E->IgnoreParens());
15711 /// Mark a variable referenced, and check whether it is odr-used
15712 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
15713 /// used directly for normal expressions referring to VarDecl.
15714 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15715 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15718 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15719 Decl *D, Expr *E, bool MightBeOdrUse) {
15720 if (SemaRef.isInOpenMPDeclareTargetContext())
15721 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15723 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15724 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15728 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15730 // If this is a call to a method via a cast, also mark the method in the
15731 // derived class used in case codegen can devirtualize the call.
15732 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15735 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15738 // Only attempt to devirtualize if this is truly a virtual call.
15739 bool IsVirtualCall = MD->isVirtual() &&
15740 ME->performsVirtualDispatch(SemaRef.getLangOpts());
15741 if (!IsVirtualCall)
15744 // If it's possible to devirtualize the call, mark the called function
15746 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15747 ME->getBase(), SemaRef.getLangOpts().AppleKext);
15749 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15752 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15753 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15754 // TODO: update this with DR# once a defect report is filed.
15755 // C++11 defect. The address of a pure member should not be an ODR use, even
15756 // if it's a qualified reference.
15757 bool OdrUse = true;
15758 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15759 if (Method->isVirtual() &&
15760 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15762 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15765 /// Perform reference-marking and odr-use handling for a MemberExpr.
15766 void Sema::MarkMemberReferenced(MemberExpr *E) {
15767 // C++11 [basic.def.odr]p2:
15768 // A non-overloaded function whose name appears as a potentially-evaluated
15769 // expression or a member of a set of candidate functions, if selected by
15770 // overload resolution when referred to from a potentially-evaluated
15771 // expression, is odr-used, unless it is a pure virtual function and its
15772 // name is not explicitly qualified.
15773 bool MightBeOdrUse = true;
15774 if (E->performsVirtualDispatch(getLangOpts())) {
15775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15776 if (Method->isPure())
15777 MightBeOdrUse = false;
15779 SourceLocation Loc =
15780 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15781 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15784 /// Perform marking for a reference to an arbitrary declaration. It
15785 /// marks the declaration referenced, and performs odr-use checking for
15786 /// functions and variables. This method should not be used when building a
15787 /// normal expression which refers to a variable.
15788 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15789 bool MightBeOdrUse) {
15790 if (MightBeOdrUse) {
15791 if (auto *VD = dyn_cast<VarDecl>(D)) {
15792 MarkVariableReferenced(Loc, VD);
15796 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15797 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15800 D->setReferenced();
15804 // Mark all of the declarations used by a type as referenced.
15805 // FIXME: Not fully implemented yet! We need to have a better understanding
15806 // of when we're entering a context we should not recurse into.
15807 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15808 // TreeTransforms rebuilding the type in a new context. Rather than
15809 // duplicating the TreeTransform logic, we should consider reusing it here.
15810 // Currently that causes problems when rebuilding LambdaExprs.
15811 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15813 SourceLocation Loc;
15816 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15818 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15820 bool TraverseTemplateArgument(const TemplateArgument &Arg);
15824 bool MarkReferencedDecls::TraverseTemplateArgument(
15825 const TemplateArgument &Arg) {
15827 // A non-type template argument is a constant-evaluated context.
15828 EnterExpressionEvaluationContext Evaluated(
15829 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15830 if (Arg.getKind() == TemplateArgument::Declaration) {
15831 if (Decl *D = Arg.getAsDecl())
15832 S.MarkAnyDeclReferenced(Loc, D, true);
15833 } else if (Arg.getKind() == TemplateArgument::Expression) {
15834 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15838 return Inherited::TraverseTemplateArgument(Arg);
15841 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15842 MarkReferencedDecls Marker(*this, Loc);
15843 Marker.TraverseType(T);
15847 /// Helper class that marks all of the declarations referenced by
15848 /// potentially-evaluated subexpressions as "referenced".
15849 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15851 bool SkipLocalVariables;
15854 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15856 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15857 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15859 void VisitDeclRefExpr(DeclRefExpr *E) {
15860 // If we were asked not to visit local variables, don't.
15861 if (SkipLocalVariables) {
15862 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15863 if (VD->hasLocalStorage())
15867 S.MarkDeclRefReferenced(E);
15870 void VisitMemberExpr(MemberExpr *E) {
15871 S.MarkMemberReferenced(E);
15872 Inherited::VisitMemberExpr(E);
15875 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15876 S.MarkFunctionReferenced(
15878 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
15879 Visit(E->getSubExpr());
15882 void VisitCXXNewExpr(CXXNewExpr *E) {
15883 if (E->getOperatorNew())
15884 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
15885 if (E->getOperatorDelete())
15886 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15887 Inherited::VisitCXXNewExpr(E);
15890 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15891 if (E->getOperatorDelete())
15892 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15893 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15894 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15895 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15896 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
15899 Inherited::VisitCXXDeleteExpr(E);
15902 void VisitCXXConstructExpr(CXXConstructExpr *E) {
15903 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
15904 Inherited::VisitCXXConstructExpr(E);
15907 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15908 Visit(E->getExpr());
15911 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15912 Inherited::VisitImplicitCastExpr(E);
15914 if (E->getCastKind() == CK_LValueToRValue)
15915 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15920 /// Mark any declarations that appear within this expression or any
15921 /// potentially-evaluated subexpressions as "referenced".
15923 /// \param SkipLocalVariables If true, don't mark local variables as
15925 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15926 bool SkipLocalVariables) {
15927 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15930 /// Emit a diagnostic that describes an effect on the run-time behavior
15931 /// of the program being compiled.
15933 /// This routine emits the given diagnostic when the code currently being
15934 /// type-checked is "potentially evaluated", meaning that there is a
15935 /// possibility that the code will actually be executable. Code in sizeof()
15936 /// expressions, code used only during overload resolution, etc., are not
15937 /// potentially evaluated. This routine will suppress such diagnostics or,
15938 /// in the absolutely nutty case of potentially potentially evaluated
15939 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15942 /// This routine should be used for all diagnostics that describe the run-time
15943 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15944 /// Failure to do so will likely result in spurious diagnostics or failures
15945 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15946 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15947 const PartialDiagnostic &PD) {
15948 switch (ExprEvalContexts.back().Context) {
15949 case ExpressionEvaluationContext::Unevaluated:
15950 case ExpressionEvaluationContext::UnevaluatedList:
15951 case ExpressionEvaluationContext::UnevaluatedAbstract:
15952 case ExpressionEvaluationContext::DiscardedStatement:
15953 // The argument will never be evaluated, so don't complain.
15956 case ExpressionEvaluationContext::ConstantEvaluated:
15957 // Relevant diagnostics should be produced by constant evaluation.
15960 case ExpressionEvaluationContext::PotentiallyEvaluated:
15961 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15962 if (Statement && getCurFunctionOrMethodDecl()) {
15963 FunctionScopes.back()->PossiblyUnreachableDiags.
15964 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15968 // The initializer of a constexpr variable or of the first declaration of a
15969 // static data member is not syntactically a constant evaluated constant,
15970 // but nonetheless is always required to be a constant expression, so we
15971 // can skip diagnosing.
15972 // FIXME: Using the mangling context here is a hack.
15973 if (auto *VD = dyn_cast_or_null<VarDecl>(
15974 ExprEvalContexts.back().ManglingContextDecl)) {
15975 if (VD->isConstexpr() ||
15976 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15978 // FIXME: For any other kind of variable, we should build a CFG for its
15979 // initializer and check whether the context in question is reachable.
15989 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15990 CallExpr *CE, FunctionDecl *FD) {
15991 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15994 // If we're inside a decltype's expression, don't check for a valid return
15995 // type or construct temporaries until we know whether this is the last call.
15996 if (ExprEvalContexts.back().ExprContext ==
15997 ExpressionEvaluationContextRecord::EK_Decltype) {
15998 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16002 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16007 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16008 : FD(FD), CE(CE) { }
16010 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16012 S.Diag(Loc, diag::err_call_incomplete_return)
16013 << T << CE->getSourceRange();
16017 S.Diag(Loc, diag::err_call_function_incomplete_return)
16018 << CE->getSourceRange() << FD->getDeclName() << T;
16019 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16020 << FD->getDeclName();
16022 } Diagnoser(FD, CE);
16024 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16030 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16031 // will prevent this condition from triggering, which is what we want.
16032 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16033 SourceLocation Loc;
16035 unsigned diagnostic = diag::warn_condition_is_assignment;
16036 bool IsOrAssign = false;
16038 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16039 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16042 IsOrAssign = Op->getOpcode() == BO_OrAssign;
16044 // Greylist some idioms by putting them into a warning subcategory.
16045 if (ObjCMessageExpr *ME
16046 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16047 Selector Sel = ME->getSelector();
16049 // self = [<foo> init...]
16050 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16051 diagnostic = diag::warn_condition_is_idiomatic_assignment;
16053 // <foo> = [<bar> nextObject]
16054 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16055 diagnostic = diag::warn_condition_is_idiomatic_assignment;
16058 Loc = Op->getOperatorLoc();
16059 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16060 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16063 IsOrAssign = Op->getOperator() == OO_PipeEqual;
16064 Loc = Op->getOperatorLoc();
16065 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16066 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16068 // Not an assignment.
16072 Diag(Loc, diagnostic) << E->getSourceRange();
16074 SourceLocation Open = E->getBeginLoc();
16075 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16076 Diag(Loc, diag::note_condition_assign_silence)
16077 << FixItHint::CreateInsertion(Open, "(")
16078 << FixItHint::CreateInsertion(Close, ")");
16081 Diag(Loc, diag::note_condition_or_assign_to_comparison)
16082 << FixItHint::CreateReplacement(Loc, "!=");
16084 Diag(Loc, diag::note_condition_assign_to_comparison)
16085 << FixItHint::CreateReplacement(Loc, "==");
16088 /// Redundant parentheses over an equality comparison can indicate
16089 /// that the user intended an assignment used as condition.
16090 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16091 // Don't warn if the parens came from a macro.
16092 SourceLocation parenLoc = ParenE->getBeginLoc();
16093 if (parenLoc.isInvalid() || parenLoc.isMacroID())
16095 // Don't warn for dependent expressions.
16096 if (ParenE->isTypeDependent())
16099 Expr *E = ParenE->IgnoreParens();
16101 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16102 if (opE->getOpcode() == BO_EQ &&
16103 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16104 == Expr::MLV_Valid) {
16105 SourceLocation Loc = opE->getOperatorLoc();
16107 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16108 SourceRange ParenERange = ParenE->getSourceRange();
16109 Diag(Loc, diag::note_equality_comparison_silence)
16110 << FixItHint::CreateRemoval(ParenERange.getBegin())
16111 << FixItHint::CreateRemoval(ParenERange.getEnd());
16112 Diag(Loc, diag::note_equality_comparison_to_assign)
16113 << FixItHint::CreateReplacement(Loc, "=");
16117 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16118 bool IsConstexpr) {
16119 DiagnoseAssignmentAsCondition(E);
16120 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16121 DiagnoseEqualityWithExtraParens(parenE);
16123 ExprResult result = CheckPlaceholderExpr(E);
16124 if (result.isInvalid()) return ExprError();
16127 if (!E->isTypeDependent()) {
16128 if (getLangOpts().CPlusPlus)
16129 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16131 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16132 if (ERes.isInvalid())
16133 return ExprError();
16136 QualType T = E->getType();
16137 if (!T->isScalarType()) { // C99 6.8.4.1p1
16138 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16139 << T << E->getSourceRange();
16140 return ExprError();
16142 CheckBoolLikeConversion(E, Loc);
16148 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
16149 Expr *SubExpr, ConditionKind CK) {
16150 // Empty conditions are valid in for-statements.
16152 return ConditionResult();
16156 case ConditionKind::Boolean:
16157 Cond = CheckBooleanCondition(Loc, SubExpr);
16160 case ConditionKind::ConstexprIf:
16161 Cond = CheckBooleanCondition(Loc, SubExpr, true);
16164 case ConditionKind::Switch:
16165 Cond = CheckSwitchCondition(Loc, SubExpr);
16168 if (Cond.isInvalid())
16169 return ConditionError();
16171 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16172 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16173 if (!FullExpr.get())
16174 return ConditionError();
16176 return ConditionResult(*this, nullptr, FullExpr,
16177 CK == ConditionKind::ConstexprIf);
16181 /// A visitor for rebuilding a call to an __unknown_any expression
16182 /// to have an appropriate type.
16183 struct RebuildUnknownAnyFunction
16184 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16188 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16190 ExprResult VisitStmt(Stmt *S) {
16191 llvm_unreachable("unexpected statement!");
16194 ExprResult VisitExpr(Expr *E) {
16195 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16196 << E->getSourceRange();
16197 return ExprError();
16200 /// Rebuild an expression which simply semantically wraps another
16201 /// expression which it shares the type and value kind of.
16202 template <class T> ExprResult rebuildSugarExpr(T *E) {
16203 ExprResult SubResult = Visit(E->getSubExpr());
16204 if (SubResult.isInvalid()) return ExprError();
16206 Expr *SubExpr = SubResult.get();
16207 E->setSubExpr(SubExpr);
16208 E->setType(SubExpr->getType());
16209 E->setValueKind(SubExpr->getValueKind());
16210 assert(E->getObjectKind() == OK_Ordinary);
16214 ExprResult VisitParenExpr(ParenExpr *E) {
16215 return rebuildSugarExpr(E);
16218 ExprResult VisitUnaryExtension(UnaryOperator *E) {
16219 return rebuildSugarExpr(E);
16222 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16223 ExprResult SubResult = Visit(E->getSubExpr());
16224 if (SubResult.isInvalid()) return ExprError();
16226 Expr *SubExpr = SubResult.get();
16227 E->setSubExpr(SubExpr);
16228 E->setType(S.Context.getPointerType(SubExpr->getType()));
16229 assert(E->getValueKind() == VK_RValue);
16230 assert(E->getObjectKind() == OK_Ordinary);
16234 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16235 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16237 E->setType(VD->getType());
16239 assert(E->getValueKind() == VK_RValue);
16240 if (S.getLangOpts().CPlusPlus &&
16241 !(isa<CXXMethodDecl>(VD) &&
16242 cast<CXXMethodDecl>(VD)->isInstance()))
16243 E->setValueKind(VK_LValue);
16248 ExprResult VisitMemberExpr(MemberExpr *E) {
16249 return resolveDecl(E, E->getMemberDecl());
16252 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16253 return resolveDecl(E, E->getDecl());
16258 /// Given a function expression of unknown-any type, try to rebuild it
16259 /// to have a function type.
16260 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16261 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16262 if (Result.isInvalid()) return ExprError();
16263 return S.DefaultFunctionArrayConversion(Result.get());
16267 /// A visitor for rebuilding an expression of type __unknown_anytype
16268 /// into one which resolves the type directly on the referring
16269 /// expression. Strict preservation of the original source
16270 /// structure is not a goal.
16271 struct RebuildUnknownAnyExpr
16272 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16276 /// The current destination type.
16279 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16280 : S(S), DestType(CastType) {}
16282 ExprResult VisitStmt(Stmt *S) {
16283 llvm_unreachable("unexpected statement!");
16286 ExprResult VisitExpr(Expr *E) {
16287 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16288 << E->getSourceRange();
16289 return ExprError();
16292 ExprResult VisitCallExpr(CallExpr *E);
16293 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16295 /// Rebuild an expression which simply semantically wraps another
16296 /// expression which it shares the type and value kind of.
16297 template <class T> ExprResult rebuildSugarExpr(T *E) {
16298 ExprResult SubResult = Visit(E->getSubExpr());
16299 if (SubResult.isInvalid()) return ExprError();
16300 Expr *SubExpr = SubResult.get();
16301 E->setSubExpr(SubExpr);
16302 E->setType(SubExpr->getType());
16303 E->setValueKind(SubExpr->getValueKind());
16304 assert(E->getObjectKind() == OK_Ordinary);
16308 ExprResult VisitParenExpr(ParenExpr *E) {
16309 return rebuildSugarExpr(E);
16312 ExprResult VisitUnaryExtension(UnaryOperator *E) {
16313 return rebuildSugarExpr(E);
16316 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16317 const PointerType *Ptr = DestType->getAs<PointerType>();
16319 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16320 << E->getSourceRange();
16321 return ExprError();
16324 if (isa<CallExpr>(E->getSubExpr())) {
16325 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16326 << E->getSourceRange();
16327 return ExprError();
16330 assert(E->getValueKind() == VK_RValue);
16331 assert(E->getObjectKind() == OK_Ordinary);
16332 E->setType(DestType);
16334 // Build the sub-expression as if it were an object of the pointee type.
16335 DestType = Ptr->getPointeeType();
16336 ExprResult SubResult = Visit(E->getSubExpr());
16337 if (SubResult.isInvalid()) return ExprError();
16338 E->setSubExpr(SubResult.get());
16342 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16344 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16346 ExprResult VisitMemberExpr(MemberExpr *E) {
16347 return resolveDecl(E, E->getMemberDecl());
16350 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16351 return resolveDecl(E, E->getDecl());
16356 /// Rebuilds a call expression which yielded __unknown_anytype.
16357 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16358 Expr *CalleeExpr = E->getCallee();
16362 FK_FunctionPointer,
16367 QualType CalleeType = CalleeExpr->getType();
16368 if (CalleeType == S.Context.BoundMemberTy) {
16369 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16370 Kind = FK_MemberFunction;
16371 CalleeType = Expr::findBoundMemberType(CalleeExpr);
16372 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16373 CalleeType = Ptr->getPointeeType();
16374 Kind = FK_FunctionPointer;
16376 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16377 Kind = FK_BlockPointer;
16379 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16381 // Verify that this is a legal result type of a function.
16382 if (DestType->isArrayType() || DestType->isFunctionType()) {
16383 unsigned diagID = diag::err_func_returning_array_function;
16384 if (Kind == FK_BlockPointer)
16385 diagID = diag::err_block_returning_array_function;
16387 S.Diag(E->getExprLoc(), diagID)
16388 << DestType->isFunctionType() << DestType;
16389 return ExprError();
16392 // Otherwise, go ahead and set DestType as the call's result.
16393 E->setType(DestType.getNonLValueExprType(S.Context));
16394 E->setValueKind(Expr::getValueKindForType(DestType));
16395 assert(E->getObjectKind() == OK_Ordinary);
16397 // Rebuild the function type, replacing the result type with DestType.
16398 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16400 // __unknown_anytype(...) is a special case used by the debugger when
16401 // it has no idea what a function's signature is.
16403 // We want to build this call essentially under the K&R
16404 // unprototyped rules, but making a FunctionNoProtoType in C++
16405 // would foul up all sorts of assumptions. However, we cannot
16406 // simply pass all arguments as variadic arguments, nor can we
16407 // portably just call the function under a non-variadic type; see
16408 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16409 // However, it turns out that in practice it is generally safe to
16410 // call a function declared as "A foo(B,C,D);" under the prototype
16411 // "A foo(B,C,D,...);". The only known exception is with the
16412 // Windows ABI, where any variadic function is implicitly cdecl
16413 // regardless of its normal CC. Therefore we change the parameter
16414 // types to match the types of the arguments.
16416 // This is a hack, but it is far superior to moving the
16417 // corresponding target-specific code from IR-gen to Sema/AST.
16419 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16420 SmallVector<QualType, 8> ArgTypes;
16421 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16422 ArgTypes.reserve(E->getNumArgs());
16423 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16424 Expr *Arg = E->getArg(i);
16425 QualType ArgType = Arg->getType();
16426 if (E->isLValue()) {
16427 ArgType = S.Context.getLValueReferenceType(ArgType);
16428 } else if (E->isXValue()) {
16429 ArgType = S.Context.getRValueReferenceType(ArgType);
16431 ArgTypes.push_back(ArgType);
16433 ParamTypes = ArgTypes;
16435 DestType = S.Context.getFunctionType(DestType, ParamTypes,
16436 Proto->getExtProtoInfo());
16438 DestType = S.Context.getFunctionNoProtoType(DestType,
16439 FnType->getExtInfo());
16442 // Rebuild the appropriate pointer-to-function type.
16444 case FK_MemberFunction:
16448 case FK_FunctionPointer:
16449 DestType = S.Context.getPointerType(DestType);
16452 case FK_BlockPointer:
16453 DestType = S.Context.getBlockPointerType(DestType);
16457 // Finally, we can recurse.
16458 ExprResult CalleeResult = Visit(CalleeExpr);
16459 if (!CalleeResult.isUsable()) return ExprError();
16460 E->setCallee(CalleeResult.get());
16462 // Bind a temporary if necessary.
16463 return S.MaybeBindToTemporary(E);
16466 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16467 // Verify that this is a legal result type of a call.
16468 if (DestType->isArrayType() || DestType->isFunctionType()) {
16469 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16470 << DestType->isFunctionType() << DestType;
16471 return ExprError();
16474 // Rewrite the method result type if available.
16475 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16476 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16477 Method->setReturnType(DestType);
16480 // Change the type of the message.
16481 E->setType(DestType.getNonReferenceType());
16482 E->setValueKind(Expr::getValueKindForType(DestType));
16484 return S.MaybeBindToTemporary(E);
16487 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16488 // The only case we should ever see here is a function-to-pointer decay.
16489 if (E->getCastKind() == CK_FunctionToPointerDecay) {
16490 assert(E->getValueKind() == VK_RValue);
16491 assert(E->getObjectKind() == OK_Ordinary);
16493 E->setType(DestType);
16495 // Rebuild the sub-expression as the pointee (function) type.
16496 DestType = DestType->castAs<PointerType>()->getPointeeType();
16498 ExprResult Result = Visit(E->getSubExpr());
16499 if (!Result.isUsable()) return ExprError();
16501 E->setSubExpr(Result.get());
16503 } else if (E->getCastKind() == CK_LValueToRValue) {
16504 assert(E->getValueKind() == VK_RValue);
16505 assert(E->getObjectKind() == OK_Ordinary);
16507 assert(isa<BlockPointerType>(E->getType()));
16509 E->setType(DestType);
16511 // The sub-expression has to be a lvalue reference, so rebuild it as such.
16512 DestType = S.Context.getLValueReferenceType(DestType);
16514 ExprResult Result = Visit(E->getSubExpr());
16515 if (!Result.isUsable()) return ExprError();
16517 E->setSubExpr(Result.get());
16520 llvm_unreachable("Unhandled cast type!");
16524 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16525 ExprValueKind ValueKind = VK_LValue;
16526 QualType Type = DestType;
16528 // We know how to make this work for certain kinds of decls:
16531 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16532 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16533 DestType = Ptr->getPointeeType();
16534 ExprResult Result = resolveDecl(E, VD);
16535 if (Result.isInvalid()) return ExprError();
16536 return S.ImpCastExprToType(Result.get(), Type,
16537 CK_FunctionToPointerDecay, VK_RValue);
16540 if (!Type->isFunctionType()) {
16541 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16542 << VD << E->getSourceRange();
16543 return ExprError();
16545 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16546 // We must match the FunctionDecl's type to the hack introduced in
16547 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16548 // type. See the lengthy commentary in that routine.
16549 QualType FDT = FD->getType();
16550 const FunctionType *FnType = FDT->castAs<FunctionType>();
16551 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16552 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16553 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16554 SourceLocation Loc = FD->getLocation();
16555 FunctionDecl *NewFD = FunctionDecl::Create(S.Context,
16556 FD->getDeclContext(),
16557 Loc, Loc, FD->getNameInfo().getName(),
16558 DestType, FD->getTypeSourceInfo(),
16559 SC_None, false/*isInlineSpecified*/,
16560 FD->hasPrototype(),
16561 false/*isConstexprSpecified*/);
16563 if (FD->getQualifier())
16564 NewFD->setQualifierInfo(FD->getQualifierLoc());
16566 SmallVector<ParmVarDecl*, 16> Params;
16567 for (const auto &AI : FT->param_types()) {
16568 ParmVarDecl *Param =
16569 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16570 Param->setScopeInfo(0, Params.size());
16571 Params.push_back(Param);
16573 NewFD->setParams(Params);
16574 DRE->setDecl(NewFD);
16575 VD = DRE->getDecl();
16579 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16580 if (MD->isInstance()) {
16581 ValueKind = VK_RValue;
16582 Type = S.Context.BoundMemberTy;
16585 // Function references aren't l-values in C.
16586 if (!S.getLangOpts().CPlusPlus)
16587 ValueKind = VK_RValue;
16590 } else if (isa<VarDecl>(VD)) {
16591 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16592 Type = RefTy->getPointeeType();
16593 } else if (Type->isFunctionType()) {
16594 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16595 << VD << E->getSourceRange();
16596 return ExprError();
16601 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16602 << VD << E->getSourceRange();
16603 return ExprError();
16606 // Modifying the declaration like this is friendly to IR-gen but
16607 // also really dangerous.
16608 VD->setType(DestType);
16610 E->setValueKind(ValueKind);
16614 /// Check a cast of an unknown-any type. We intentionally only
16615 /// trigger this for C-style casts.
16616 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16617 Expr *CastExpr, CastKind &CastKind,
16618 ExprValueKind &VK, CXXCastPath &Path) {
16619 // The type we're casting to must be either void or complete.
16620 if (!CastType->isVoidType() &&
16621 RequireCompleteType(TypeRange.getBegin(), CastType,
16622 diag::err_typecheck_cast_to_incomplete))
16623 return ExprError();
16625 // Rewrite the casted expression from scratch.
16626 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16627 if (!result.isUsable()) return ExprError();
16629 CastExpr = result.get();
16630 VK = CastExpr->getValueKind();
16631 CastKind = CK_NoOp;
16636 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16637 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16640 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16641 Expr *arg, QualType ¶mType) {
16642 // If the syntactic form of the argument is not an explicit cast of
16643 // any sort, just do default argument promotion.
16644 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16646 ExprResult result = DefaultArgumentPromotion(arg);
16647 if (result.isInvalid()) return ExprError();
16648 paramType = result.get()->getType();
16652 // Otherwise, use the type that was written in the explicit cast.
16653 assert(!arg->hasPlaceholderType());
16654 paramType = castArg->getTypeAsWritten();
16656 // Copy-initialize a parameter of that type.
16657 InitializedEntity entity =
16658 InitializedEntity::InitializeParameter(Context, paramType,
16659 /*consumed*/ false);
16660 return PerformCopyInitialization(entity, callLoc, arg);
16663 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16665 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16667 E = E->IgnoreParenImpCasts();
16668 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16669 E = call->getCallee();
16670 diagID = diag::err_uncasted_call_of_unknown_any;
16676 SourceLocation loc;
16678 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16679 loc = ref->getLocation();
16680 d = ref->getDecl();
16681 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16682 loc = mem->getMemberLoc();
16683 d = mem->getMemberDecl();
16684 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16685 diagID = diag::err_uncasted_call_of_unknown_any;
16686 loc = msg->getSelectorStartLoc();
16687 d = msg->getMethodDecl();
16689 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16690 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16691 << orig->getSourceRange();
16692 return ExprError();
16695 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16696 << E->getSourceRange();
16697 return ExprError();
16700 S.Diag(loc, diagID) << d << orig->getSourceRange();
16702 // Never recoverable.
16703 return ExprError();
16706 /// Check for operands with placeholder types and complain if found.
16707 /// Returns ExprError() if there was an error and no recovery was possible.
16708 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16709 if (!getLangOpts().CPlusPlus) {
16710 // C cannot handle TypoExpr nodes on either side of a binop because it
16711 // doesn't handle dependent types properly, so make sure any TypoExprs have
16712 // been dealt with before checking the operands.
16713 ExprResult Result = CorrectDelayedTyposInExpr(E);
16714 if (!Result.isUsable()) return ExprError();
16718 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16719 if (!placeholderType) return E;
16721 switch (placeholderType->getKind()) {
16723 // Overloaded expressions.
16724 case BuiltinType::Overload: {
16725 // Try to resolve a single function template specialization.
16726 // This is obligatory.
16727 ExprResult Result = E;
16728 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16731 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16732 // leaves Result unchanged on failure.
16734 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16737 // If that failed, try to recover with a call.
16738 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16739 /*complain*/ true);
16743 // Bound member functions.
16744 case BuiltinType::BoundMember: {
16745 ExprResult result = E;
16746 const Expr *BME = E->IgnoreParens();
16747 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16748 // Try to give a nicer diagnostic if it is a bound member that we recognize.
16749 if (isa<CXXPseudoDestructorExpr>(BME)) {
16750 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16751 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16752 if (ME->getMemberNameInfo().getName().getNameKind() ==
16753 DeclarationName::CXXDestructorName)
16754 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16756 tryToRecoverWithCall(result, PD,
16757 /*complain*/ true);
16761 // ARC unbridged casts.
16762 case BuiltinType::ARCUnbridgedCast: {
16763 Expr *realCast = stripARCUnbridgedCast(E);
16764 diagnoseARCUnbridgedCast(realCast);
16768 // Expressions of unknown type.
16769 case BuiltinType::UnknownAny:
16770 return diagnoseUnknownAnyExpr(*this, E);
16773 case BuiltinType::PseudoObject:
16774 return checkPseudoObjectRValue(E);
16776 case BuiltinType::BuiltinFn: {
16777 // Accept __noop without parens by implicitly converting it to a call expr.
16778 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16780 auto *FD = cast<FunctionDecl>(DRE->getDecl());
16781 if (FD->getBuiltinID() == Builtin::BI__noop) {
16782 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16783 CK_BuiltinFnToFnPtr)
16785 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
16786 VK_RValue, SourceLocation());
16790 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16791 return ExprError();
16794 // Expressions of unknown type.
16795 case BuiltinType::OMPArraySection:
16796 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16797 return ExprError();
16799 // Everything else should be impossible.
16800 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16801 case BuiltinType::Id:
16802 #include "clang/Basic/OpenCLImageTypes.def"
16803 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16804 case BuiltinType::Id:
16805 #include "clang/Basic/OpenCLExtensionTypes.def"
16806 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16807 #define PLACEHOLDER_TYPE(Id, SingletonId)
16808 #include "clang/AST/BuiltinTypes.def"
16812 llvm_unreachable("invalid placeholder type!");
16815 bool Sema::CheckCaseExpression(Expr *E) {
16816 if (E->isTypeDependent())
16818 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16819 return E->getType()->isIntegralOrEnumerationType();
16823 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16825 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16826 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16827 "Unknown Objective-C Boolean value!");
16828 QualType BoolT = Context.ObjCBuiltinBoolTy;
16829 if (!Context.getBOOLDecl()) {
16830 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16831 Sema::LookupOrdinaryName);
16832 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16833 NamedDecl *ND = Result.getFoundDecl();
16834 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16835 Context.setBOOLDecl(TD);
16838 if (Context.getBOOLDecl())
16839 BoolT = Context.getBOOLType();
16840 return new (Context)
16841 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16844 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16845 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16846 SourceLocation RParen) {
16848 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16850 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16851 [&](const AvailabilitySpec &Spec) {
16852 return Spec.getPlatform() == Platform;
16855 VersionTuple Version;
16856 if (Spec != AvailSpecs.end())
16857 Version = Spec->getVersion();
16859 // The use of `@available` in the enclosing function should be analyzed to
16860 // warn when it's used inappropriately (i.e. not if(@available)).
16861 if (getCurFunctionOrMethodDecl())
16862 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16863 else if (getCurBlock() || getCurLambda())
16864 getCurFunction()->HasPotentialAvailabilityViolations = true;
16866 return new (Context)
16867 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);