1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for expressions.
12 //===----------------------------------------------------------------------===//
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54 // See if this is an auto-typed variable whose initializer we are parsing.
55 if (ParsingInitForAutoVars.count(D))
58 // See if this is a deleted function.
59 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
63 // If the function has a deduced return type, and we can't deduce it,
64 // then we can't use it either.
65 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
70 // See if this function is unavailable.
71 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
72 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
78 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
79 // Warn if this is used but marked unused.
80 if (const auto *A = D->getAttr<UnusedAttr>()) {
81 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
82 // should diagnose them.
83 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
84 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
85 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
86 if (DC && !DC->hasAttr<UnusedAttr>())
87 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
92 /// Emit a note explaining that this function is deleted.
93 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
94 assert(Decl->isDeleted());
96 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
98 if (Method && Method->isDeleted() && Method->isDefaulted()) {
99 // If the method was explicitly defaulted, point at that declaration.
100 if (!Method->isImplicit())
101 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
103 // Try to diagnose why this special member function was implicitly
104 // deleted. This might fail, if that reason no longer applies.
105 CXXSpecialMember CSM = getSpecialMember(Method);
106 if (CSM != CXXInvalid)
107 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
112 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
113 if (Ctor && Ctor->isInheritingConstructor())
114 return NoteDeletedInheritingConstructor(Ctor);
116 Diag(Decl->getLocation(), diag::note_availability_specified_here)
120 /// Determine whether a FunctionDecl was ever declared with an
121 /// explicit storage class.
122 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
123 for (auto I : D->redecls()) {
124 if (I->getStorageClass() != SC_None)
130 /// Check whether we're in an extern inline function and referring to a
131 /// variable or function with internal linkage (C11 6.7.4p3).
133 /// This is only a warning because we used to silently accept this code, but
134 /// in many cases it will not behave correctly. This is not enabled in C++ mode
135 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
136 /// and so while there may still be user mistakes, most of the time we can't
137 /// prove that there are errors.
138 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
140 SourceLocation Loc) {
141 // This is disabled under C++; there are too many ways for this to fire in
142 // contexts where the warning is a false positive, or where it is technically
143 // correct but benign.
144 if (S.getLangOpts().CPlusPlus)
147 // Check if this is an inlined function or method.
148 FunctionDecl *Current = S.getCurFunctionDecl();
151 if (!Current->isInlined())
153 if (!Current->isExternallyVisible())
156 // Check if the decl has internal linkage.
157 if (D->getFormalLinkage() != InternalLinkage)
160 // Downgrade from ExtWarn to Extension if
161 // (1) the supposedly external inline function is in the main file,
162 // and probably won't be included anywhere else.
163 // (2) the thing we're referencing is a pure function.
164 // (3) the thing we're referencing is another inline function.
165 // This last can give us false negatives, but it's better than warning on
166 // wrappers for simple C library functions.
167 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
168 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
169 if (!DowngradeWarning && UsedFn)
170 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
172 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
173 : diag::ext_internal_in_extern_inline)
174 << /*IsVar=*/!UsedFn << D;
176 S.MaybeSuggestAddingStaticToDecl(Current);
178 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
182 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
183 const FunctionDecl *First = Cur->getFirstDecl();
185 // Suggest "static" on the function, if possible.
186 if (!hasAnyExplicitStorageClass(First)) {
187 SourceLocation DeclBegin = First->getSourceRange().getBegin();
188 Diag(DeclBegin, diag::note_convert_inline_to_static)
189 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
193 /// Determine whether the use of this declaration is valid, and
194 /// emit any corresponding diagnostics.
196 /// This routine diagnoses various problems with referencing
197 /// declarations that can occur when using a declaration. For example,
198 /// it might warn if a deprecated or unavailable declaration is being
199 /// used, or produce an error (and return true) if a C++0x deleted
200 /// function is being used.
202 /// \returns true if there was an error (this declaration cannot be
203 /// referenced), false otherwise.
205 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
206 const ObjCInterfaceDecl *UnknownObjCClass,
207 bool ObjCPropertyAccess,
208 bool AvoidPartialAvailabilityChecks) {
209 SourceLocation Loc = Locs.front();
210 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
211 // If there were any diagnostics suppressed by template argument deduction,
213 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
214 if (Pos != SuppressedDiagnostics.end()) {
215 for (const PartialDiagnosticAt &Suppressed : Pos->second)
216 Diag(Suppressed.first, Suppressed.second);
218 // Clear out the list of suppressed diagnostics, so that we don't emit
219 // them again for this specialization. However, we don't obsolete this
220 // entry from the table, because we want to avoid ever emitting these
221 // diagnostics again.
225 // C++ [basic.start.main]p3:
226 // The function 'main' shall not be used within a program.
227 if (cast<FunctionDecl>(D)->isMain())
228 Diag(Loc, diag::ext_main_used);
231 // See if this is an auto-typed variable whose initializer we are parsing.
232 if (ParsingInitForAutoVars.count(D)) {
233 if (isa<BindingDecl>(D)) {
234 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
237 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
238 << D->getDeclName() << cast<VarDecl>(D)->getType();
243 // See if this is a deleted function.
244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245 if (FD->isDeleted()) {
246 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
247 if (Ctor && Ctor->isInheritingConstructor())
248 Diag(Loc, diag::err_deleted_inherited_ctor_use)
250 << Ctor->getInheritedConstructor().getConstructor()->getParent();
252 Diag(Loc, diag::err_deleted_function_use);
253 NoteDeletedFunction(FD);
257 // If the function has a deduced return type, and we can't deduce it,
258 // then we can't use it either.
259 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
260 DeduceReturnType(FD, Loc))
263 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
267 auto getReferencedObjCProp = [](const NamedDecl *D) ->
268 const ObjCPropertyDecl * {
269 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
270 return MD->findPropertyDecl();
273 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
274 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
276 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
280 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
281 // Only the variables omp_in and omp_out are allowed in the combiner.
282 // Only the variables omp_priv and omp_orig are allowed in the
283 // initializer-clause.
284 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
285 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
287 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
288 << getCurFunction()->HasOMPDeclareReductionCombiner;
289 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
293 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
294 AvoidPartialAvailabilityChecks);
296 DiagnoseUnusedOfDecl(*this, D, Loc);
298 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
303 /// Retrieve the message suffix that should be added to a
304 /// diagnostic complaining about the given function being deleted or
306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
308 if (FD->getAvailability(&Message))
309 return ": " + Message;
311 return std::string();
314 /// DiagnoseSentinelCalls - This routine checks whether a call or
315 /// message-send is to a declaration with the sentinel attribute, and
316 /// if so, it checks that the requirements of the sentinel are
318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
319 ArrayRef<Expr *> Args) {
320 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
324 // The number of formal parameters of the declaration.
325 unsigned numFormalParams;
327 // The kind of declaration. This is also an index into a %select in
329 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
331 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
332 numFormalParams = MD->param_size();
333 calleeType = CT_Method;
334 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
335 numFormalParams = FD->param_size();
336 calleeType = CT_Function;
337 } else if (isa<VarDecl>(D)) {
338 QualType type = cast<ValueDecl>(D)->getType();
339 const FunctionType *fn = nullptr;
340 if (const PointerType *ptr = type->getAs<PointerType>()) {
341 fn = ptr->getPointeeType()->getAs<FunctionType>();
343 calleeType = CT_Function;
344 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
345 fn = ptr->getPointeeType()->castAs<FunctionType>();
346 calleeType = CT_Block;
351 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
352 numFormalParams = proto->getNumParams();
360 // "nullPos" is the number of formal parameters at the end which
361 // effectively count as part of the variadic arguments. This is
362 // useful if you would prefer to not have *any* formal parameters,
363 // but the language forces you to have at least one.
364 unsigned nullPos = attr->getNullPos();
365 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
366 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
368 // The number of arguments which should follow the sentinel.
369 unsigned numArgsAfterSentinel = attr->getSentinel();
371 // If there aren't enough arguments for all the formal parameters,
372 // the sentinel, and the args after the sentinel, complain.
373 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
374 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
375 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
379 // Otherwise, find the sentinel expression.
380 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
381 if (!sentinelExpr) return;
382 if (sentinelExpr->isValueDependent()) return;
383 if (Context.isSentinelNullExpr(sentinelExpr)) return;
385 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
386 // or 'NULL' if those are actually defined in the context. Only use
387 // 'nil' for ObjC methods, where it's much more likely that the
388 // variadic arguments form a list of object pointers.
389 SourceLocation MissingNilLoc
390 = getLocForEndOfToken(sentinelExpr->getLocEnd());
391 std::string NullValue;
392 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
394 else if (getLangOpts().CPlusPlus11)
395 NullValue = "nullptr";
396 else if (PP.isMacroDefined("NULL"))
399 NullValue = "(void*) 0";
401 if (MissingNilLoc.isInvalid())
402 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
404 Diag(MissingNilLoc, diag::warn_missing_sentinel)
406 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
407 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
410 SourceRange Sema::getExprRange(Expr *E) const {
411 return E ? E->getSourceRange() : SourceRange();
414 //===----------------------------------------------------------------------===//
415 // Standard Promotions and Conversions
416 //===----------------------------------------------------------------------===//
418 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
419 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
420 // Handle any placeholder expressions which made it here.
421 if (E->getType()->isPlaceholderType()) {
422 ExprResult result = CheckPlaceholderExpr(E);
423 if (result.isInvalid()) return ExprError();
427 QualType Ty = E->getType();
428 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
430 if (Ty->isFunctionType()) {
431 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
432 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
433 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
436 E = ImpCastExprToType(E, Context.getPointerType(Ty),
437 CK_FunctionToPointerDecay).get();
438 } else if (Ty->isArrayType()) {
439 // In C90 mode, arrays only promote to pointers if the array expression is
440 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
441 // type 'array of type' is converted to an expression that has type 'pointer
442 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
443 // that has type 'array of type' ...". The relevant change is "an lvalue"
444 // (C90) to "an expression" (C99).
447 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
448 // T" can be converted to an rvalue of type "pointer to T".
450 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
451 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
452 CK_ArrayToPointerDecay).get();
457 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
458 // Check to see if we are dereferencing a null pointer. If so,
459 // and if not volatile-qualified, this is undefined behavior that the
460 // optimizer will delete, so warn about it. People sometimes try to use this
461 // to get a deterministic trap and are surprised by clang's behavior. This
462 // only handles the pattern "*null", which is a very syntactic check.
463 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
464 if (UO->getOpcode() == UO_Deref &&
465 UO->getSubExpr()->IgnoreParenCasts()->
466 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
467 !UO->getType().isVolatileQualified()) {
468 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
469 S.PDiag(diag::warn_indirection_through_null)
470 << UO->getSubExpr()->getSourceRange());
471 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
472 S.PDiag(diag::note_indirection_through_null));
476 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
477 SourceLocation AssignLoc,
479 const ObjCIvarDecl *IV = OIRE->getDecl();
483 DeclarationName MemberName = IV->getDeclName();
484 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
485 if (!Member || !Member->isStr("isa"))
488 const Expr *Base = OIRE->getBase();
489 QualType BaseType = Base->getType();
491 BaseType = BaseType->getPointeeType();
492 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
493 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
494 ObjCInterfaceDecl *ClassDeclared = nullptr;
495 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
496 if (!ClassDeclared->getSuperClass()
497 && (*ClassDeclared->ivar_begin()) == IV) {
499 NamedDecl *ObjectSetClass =
500 S.LookupSingleName(S.TUScope,
501 &S.Context.Idents.get("object_setClass"),
502 SourceLocation(), S.LookupOrdinaryName);
503 if (ObjectSetClass) {
504 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
505 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
506 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
507 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
509 FixItHint::CreateInsertion(RHSLocEnd, ")");
512 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
514 NamedDecl *ObjectGetClass =
515 S.LookupSingleName(S.TUScope,
516 &S.Context.Idents.get("object_getClass"),
517 SourceLocation(), S.LookupOrdinaryName);
519 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
520 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
521 FixItHint::CreateReplacement(
522 SourceRange(OIRE->getOpLoc(),
523 OIRE->getLocEnd()), ")");
525 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
527 S.Diag(IV->getLocation(), diag::note_ivar_decl);
532 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
533 // Handle any placeholder expressions which made it here.
534 if (E->getType()->isPlaceholderType()) {
535 ExprResult result = CheckPlaceholderExpr(E);
536 if (result.isInvalid()) return ExprError();
540 // C++ [conv.lval]p1:
541 // A glvalue of a non-function, non-array type T can be
542 // converted to a prvalue.
543 if (!E->isGLValue()) return E;
545 QualType T = E->getType();
546 assert(!T.isNull() && "r-value conversion on typeless expression?");
548 // We don't want to throw lvalue-to-rvalue casts on top of
549 // expressions of certain types in C++.
550 if (getLangOpts().CPlusPlus &&
551 (E->getType() == Context.OverloadTy ||
552 T->isDependentType() ||
556 // The C standard is actually really unclear on this point, and
557 // DR106 tells us what the result should be but not why. It's
558 // generally best to say that void types just doesn't undergo
559 // lvalue-to-rvalue at all. Note that expressions of unqualified
560 // 'void' type are never l-values, but qualified void can be.
564 // OpenCL usually rejects direct accesses to values of 'half' type.
565 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
567 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
572 CheckForNullPointerDereference(*this, E);
573 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
574 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
575 &Context.Idents.get("object_getClass"),
576 SourceLocation(), LookupOrdinaryName);
578 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
579 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
580 FixItHint::CreateReplacement(
581 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
583 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
585 else if (const ObjCIvarRefExpr *OIRE =
586 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
587 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
589 // C++ [conv.lval]p1:
590 // [...] If T is a non-class type, the type of the prvalue is the
591 // cv-unqualified version of T. Otherwise, the type of the
595 // If the lvalue has qualified type, the value has the unqualified
596 // version of the type of the lvalue; otherwise, the value has the
597 // type of the lvalue.
598 if (T.hasQualifiers())
599 T = T.getUnqualifiedType();
601 // Under the MS ABI, lock down the inheritance model now.
602 if (T->isMemberPointerType() &&
603 Context.getTargetInfo().getCXXABI().isMicrosoft())
604 (void)isCompleteType(E->getExprLoc(), T);
606 UpdateMarkingForLValueToRValue(E);
608 // Loading a __weak object implicitly retains the value, so we need a cleanup to
610 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
611 Cleanup.setExprNeedsCleanups(true);
613 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
617 // ... if the lvalue has atomic type, the value has the non-atomic version
618 // of the type of the lvalue ...
619 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
620 T = Atomic->getValueType().getUnqualifiedType();
621 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
628 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
629 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
632 Res = DefaultLvalueConversion(Res.get());
638 /// CallExprUnaryConversions - a special case of an unary conversion
639 /// performed on a function designator of a call expression.
640 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
641 QualType Ty = E->getType();
643 // Only do implicit cast for a function type, but not for a pointer
645 if (Ty->isFunctionType()) {
646 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
647 CK_FunctionToPointerDecay).get();
651 Res = DefaultLvalueConversion(Res.get());
657 /// UsualUnaryConversions - Performs various conversions that are common to most
658 /// operators (C99 6.3). The conversions of array and function types are
659 /// sometimes suppressed. For example, the array->pointer conversion doesn't
660 /// apply if the array is an argument to the sizeof or address (&) operators.
661 /// In these instances, this routine should *not* be called.
662 ExprResult Sema::UsualUnaryConversions(Expr *E) {
663 // First, convert to an r-value.
664 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
669 QualType Ty = E->getType();
670 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
672 // Half FP have to be promoted to float unless it is natively supported
673 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
674 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
676 // Try to perform integral promotions if the object has a theoretically
678 if (Ty->isIntegralOrUnscopedEnumerationType()) {
681 // The following may be used in an expression wherever an int or
682 // unsigned int may be used:
683 // - an object or expression with an integer type whose integer
684 // conversion rank is less than or equal to the rank of int
686 // - A bit-field of type _Bool, int, signed int, or unsigned int.
688 // If an int can represent all values of the original type, the
689 // value is converted to an int; otherwise, it is converted to an
690 // unsigned int. These are called the integer promotions. All
691 // other types are unchanged by the integer promotions.
693 QualType PTy = Context.isPromotableBitField(E);
695 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
698 if (Ty->isPromotableIntegerType()) {
699 QualType PT = Context.getPromotedIntegerType(Ty);
700 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
707 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
708 /// do not have a prototype. Arguments that have type float or __fp16
709 /// are promoted to double. All other argument types are converted by
710 /// UsualUnaryConversions().
711 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
712 QualType Ty = E->getType();
713 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
715 ExprResult Res = UsualUnaryConversions(E);
720 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
721 // promote to double.
722 // Note that default argument promotion applies only to float (and
723 // half/fp16); it does not apply to _Float16.
724 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
725 if (BTy && (BTy->getKind() == BuiltinType::Half ||
726 BTy->getKind() == BuiltinType::Float)) {
727 if (getLangOpts().OpenCL &&
728 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
729 if (BTy->getKind() == BuiltinType::Half) {
730 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
733 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
737 // C++ performs lvalue-to-rvalue conversion as a default argument
738 // promotion, even on class types, but note:
739 // C++11 [conv.lval]p2:
740 // When an lvalue-to-rvalue conversion occurs in an unevaluated
741 // operand or a subexpression thereof the value contained in the
742 // referenced object is not accessed. Otherwise, if the glvalue
743 // has a class type, the conversion copy-initializes a temporary
744 // of type T from the glvalue and the result of the conversion
745 // is a prvalue for the temporary.
746 // FIXME: add some way to gate this entire thing for correctness in
747 // potentially potentially evaluated contexts.
748 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
749 ExprResult Temp = PerformCopyInitialization(
750 InitializedEntity::InitializeTemporary(E->getType()),
752 if (Temp.isInvalid())
760 /// Determine the degree of POD-ness for an expression.
761 /// Incomplete types are considered POD, since this check can be performed
762 /// when we're in an unevaluated context.
763 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
764 if (Ty->isIncompleteType()) {
765 // C++11 [expr.call]p7:
766 // After these conversions, if the argument does not have arithmetic,
767 // enumeration, pointer, pointer to member, or class type, the program
770 // Since we've already performed array-to-pointer and function-to-pointer
771 // decay, the only such type in C++ is cv void. This also handles
772 // initializer lists as variadic arguments.
773 if (Ty->isVoidType())
776 if (Ty->isObjCObjectType())
781 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
784 if (Ty.isCXX98PODType(Context))
787 // C++11 [expr.call]p7:
788 // Passing a potentially-evaluated argument of class type (Clause 9)
789 // having a non-trivial copy constructor, a non-trivial move constructor,
790 // or a non-trivial destructor, with no corresponding parameter,
791 // is conditionally-supported with implementation-defined semantics.
792 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
793 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
794 if (!Record->hasNonTrivialCopyConstructor() &&
795 !Record->hasNonTrivialMoveConstructor() &&
796 !Record->hasNonTrivialDestructor())
797 return VAK_ValidInCXX11;
799 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
802 if (Ty->isObjCObjectType())
805 if (getLangOpts().MSVCCompat)
806 return VAK_MSVCUndefined;
808 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
809 // permitted to reject them. We should consider doing so.
810 return VAK_Undefined;
813 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
814 // Don't allow one to pass an Objective-C interface to a vararg.
815 const QualType &Ty = E->getType();
816 VarArgKind VAK = isValidVarArgType(Ty);
818 // Complain about passing non-POD types through varargs.
820 case VAK_ValidInCXX11:
822 E->getLocStart(), nullptr,
823 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
827 if (Ty->isRecordType()) {
828 // This is unlikely to be what the user intended. If the class has a
829 // 'c_str' member function, the user probably meant to call that.
830 DiagRuntimeBehavior(E->getLocStart(), nullptr,
831 PDiag(diag::warn_pass_class_arg_to_vararg)
832 << Ty << CT << hasCStrMethod(E) << ".c_str()");
837 case VAK_MSVCUndefined:
839 E->getLocStart(), nullptr,
840 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
841 << getLangOpts().CPlusPlus11 << Ty << CT);
845 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
846 Diag(E->getLocStart(),
847 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
848 else if (Ty->isObjCObjectType())
850 E->getLocStart(), nullptr,
851 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
854 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
855 << isa<InitListExpr>(E) << Ty << CT;
860 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
861 /// will create a trap if the resulting type is not a POD type.
862 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
863 FunctionDecl *FDecl) {
864 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
865 // Strip the unbridged-cast placeholder expression off, if applicable.
866 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
867 (CT == VariadicMethod ||
868 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
869 E = stripARCUnbridgedCast(E);
871 // Otherwise, do normal placeholder checking.
873 ExprResult ExprRes = CheckPlaceholderExpr(E);
874 if (ExprRes.isInvalid())
880 ExprResult ExprRes = DefaultArgumentPromotion(E);
881 if (ExprRes.isInvalid())
885 // Diagnostics regarding non-POD argument types are
886 // emitted along with format string checking in Sema::CheckFunctionCall().
887 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
888 // Turn this into a trap.
890 SourceLocation TemplateKWLoc;
892 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
894 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
896 if (TrapFn.isInvalid())
899 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
900 E->getLocStart(), None,
902 if (Call.isInvalid())
905 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
907 if (Comma.isInvalid())
912 if (!getLangOpts().CPlusPlus &&
913 RequireCompleteType(E->getExprLoc(), E->getType(),
914 diag::err_call_incomplete_argument))
920 /// Converts an integer to complex float type. Helper function of
921 /// UsualArithmeticConversions()
923 /// \return false if the integer expression is an integer type and is
924 /// successfully converted to the complex type.
925 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
926 ExprResult &ComplexExpr,
930 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
931 if (SkipCast) return false;
932 if (IntTy->isIntegerType()) {
933 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
934 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
935 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
936 CK_FloatingRealToComplex);
938 assert(IntTy->isComplexIntegerType());
939 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
940 CK_IntegralComplexToFloatingComplex);
945 /// Handle arithmetic conversion with complex types. Helper function of
946 /// UsualArithmeticConversions()
947 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
948 ExprResult &RHS, QualType LHSType,
951 // if we have an integer operand, the result is the complex type.
952 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
955 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
956 /*skipCast*/IsCompAssign))
959 // This handles complex/complex, complex/float, or float/complex.
960 // When both operands are complex, the shorter operand is converted to the
961 // type of the longer, and that is the type of the result. This corresponds
962 // to what is done when combining two real floating-point operands.
963 // The fun begins when size promotion occur across type domains.
964 // From H&S 6.3.4: When one operand is complex and the other is a real
965 // floating-point type, the less precise type is converted, within it's
966 // real or complex domain, to the precision of the other type. For example,
967 // when combining a "long double" with a "double _Complex", the
968 // "double _Complex" is promoted to "long double _Complex".
970 // Compute the rank of the two types, regardless of whether they are complex.
971 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
973 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
974 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
975 QualType LHSElementType =
976 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
977 QualType RHSElementType =
978 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
980 QualType ResultType = S.Context.getComplexType(LHSElementType);
982 // Promote the precision of the LHS if not an assignment.
983 ResultType = S.Context.getComplexType(RHSElementType);
987 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
989 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
991 } else if (Order > 0) {
992 // Promote the precision of the RHS.
994 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
996 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1001 /// Handle arithmetic conversion from integer to float. Helper function
1002 /// of UsualArithmeticConversions()
1003 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1004 ExprResult &IntExpr,
1005 QualType FloatTy, QualType IntTy,
1006 bool ConvertFloat, bool ConvertInt) {
1007 if (IntTy->isIntegerType()) {
1009 // Convert intExpr to the lhs floating point type.
1010 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1011 CK_IntegralToFloating);
1015 // Convert both sides to the appropriate complex float.
1016 assert(IntTy->isComplexIntegerType());
1017 QualType result = S.Context.getComplexType(FloatTy);
1019 // _Complex int -> _Complex float
1021 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1022 CK_IntegralComplexToFloatingComplex);
1024 // float -> _Complex float
1026 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1027 CK_FloatingRealToComplex);
1032 /// Handle arithmethic conversion with floating point types. Helper
1033 /// function of UsualArithmeticConversions()
1034 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1035 ExprResult &RHS, QualType LHSType,
1036 QualType RHSType, bool IsCompAssign) {
1037 bool LHSFloat = LHSType->isRealFloatingType();
1038 bool RHSFloat = RHSType->isRealFloatingType();
1040 // If we have two real floating types, convert the smaller operand
1041 // to the bigger result.
1042 if (LHSFloat && RHSFloat) {
1043 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1045 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1049 assert(order < 0 && "illegal float comparison");
1051 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1056 // Half FP has to be promoted to float unless it is natively supported
1057 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1058 LHSType = S.Context.FloatTy;
1060 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1061 /*convertFloat=*/!IsCompAssign,
1062 /*convertInt=*/ true);
1065 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1066 /*convertInt=*/ true,
1067 /*convertFloat=*/!IsCompAssign);
1070 /// Diagnose attempts to convert between __float128 and long double if
1071 /// there is no support for such conversion. Helper function of
1072 /// UsualArithmeticConversions().
1073 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1075 /* No issue converting if at least one of the types is not a floating point
1076 type or the two types have the same rank.
1078 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1079 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1082 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1083 "The remaining types must be floating point types.");
1085 auto *LHSComplex = LHSType->getAs<ComplexType>();
1086 auto *RHSComplex = RHSType->getAs<ComplexType>();
1088 QualType LHSElemType = LHSComplex ?
1089 LHSComplex->getElementType() : LHSType;
1090 QualType RHSElemType = RHSComplex ?
1091 RHSComplex->getElementType() : RHSType;
1093 // No issue if the two types have the same representation
1094 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1095 &S.Context.getFloatTypeSemantics(RHSElemType))
1098 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1099 RHSElemType == S.Context.LongDoubleTy);
1100 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1101 RHSElemType == S.Context.Float128Ty);
1103 // We've handled the situation where __float128 and long double have the same
1104 // representation. We allow all conversions for all possible long double types
1105 // except PPC's double double.
1106 return Float128AndLongDouble &&
1107 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1108 &llvm::APFloat::PPCDoubleDouble());
1111 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1114 /// These helper callbacks are placed in an anonymous namespace to
1115 /// permit their use as function template parameters.
1116 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1117 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1120 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1121 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1122 CK_IntegralComplexCast);
1126 /// Handle integer arithmetic conversions. Helper function of
1127 /// UsualArithmeticConversions()
1128 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1129 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1130 ExprResult &RHS, QualType LHSType,
1131 QualType RHSType, bool IsCompAssign) {
1132 // The rules for this case are in C99 6.3.1.8
1133 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1134 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1135 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1136 if (LHSSigned == RHSSigned) {
1137 // Same signedness; use the higher-ranked type
1139 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1141 } else if (!IsCompAssign)
1142 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1144 } else if (order != (LHSSigned ? 1 : -1)) {
1145 // The unsigned type has greater than or equal rank to the
1146 // signed type, so use the unsigned type
1148 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1150 } else if (!IsCompAssign)
1151 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1153 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1154 // The two types are different widths; if we are here, that
1155 // means the signed type is larger than the unsigned type, so
1156 // use the signed type.
1158 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1160 } else if (!IsCompAssign)
1161 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1164 // The signed type is higher-ranked than the unsigned type,
1165 // but isn't actually any bigger (like unsigned int and long
1166 // on most 32-bit systems). Use the unsigned type corresponding
1167 // to the signed type.
1169 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1170 RHS = (*doRHSCast)(S, RHS.get(), result);
1172 LHS = (*doLHSCast)(S, LHS.get(), result);
1177 /// Handle conversions with GCC complex int extension. Helper function
1178 /// of UsualArithmeticConversions()
1179 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1180 ExprResult &RHS, QualType LHSType,
1182 bool IsCompAssign) {
1183 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1184 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1186 if (LHSComplexInt && RHSComplexInt) {
1187 QualType LHSEltType = LHSComplexInt->getElementType();
1188 QualType RHSEltType = RHSComplexInt->getElementType();
1189 QualType ScalarType =
1190 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1191 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1193 return S.Context.getComplexType(ScalarType);
1196 if (LHSComplexInt) {
1197 QualType LHSEltType = LHSComplexInt->getElementType();
1198 QualType ScalarType =
1199 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1200 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1201 QualType ComplexType = S.Context.getComplexType(ScalarType);
1202 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1203 CK_IntegralRealToComplex);
1208 assert(RHSComplexInt);
1210 QualType RHSEltType = RHSComplexInt->getElementType();
1211 QualType ScalarType =
1212 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1213 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1214 QualType ComplexType = S.Context.getComplexType(ScalarType);
1217 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1218 CK_IntegralRealToComplex);
1222 /// UsualArithmeticConversions - Performs various conversions that are common to
1223 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1224 /// routine returns the first non-arithmetic type found. The client is
1225 /// responsible for emitting appropriate error diagnostics.
1226 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1227 bool IsCompAssign) {
1228 if (!IsCompAssign) {
1229 LHS = UsualUnaryConversions(LHS.get());
1230 if (LHS.isInvalid())
1234 RHS = UsualUnaryConversions(RHS.get());
1235 if (RHS.isInvalid())
1238 // For conversion purposes, we ignore any qualifiers.
1239 // For example, "const float" and "float" are equivalent.
1241 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1243 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1245 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1246 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1247 LHSType = AtomicLHS->getValueType();
1249 // If both types are identical, no conversion is needed.
1250 if (LHSType == RHSType)
1253 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1254 // The caller can deal with this (e.g. pointer + int).
1255 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1258 // Apply unary and bitfield promotions to the LHS's type.
1259 QualType LHSUnpromotedType = LHSType;
1260 if (LHSType->isPromotableIntegerType())
1261 LHSType = Context.getPromotedIntegerType(LHSType);
1262 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1263 if (!LHSBitfieldPromoteTy.isNull())
1264 LHSType = LHSBitfieldPromoteTy;
1265 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1266 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1268 // If both types are identical, no conversion is needed.
1269 if (LHSType == RHSType)
1272 // At this point, we have two different arithmetic types.
1274 // Diagnose attempts to convert between __float128 and long double where
1275 // such conversions currently can't be handled.
1276 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1279 // Handle complex types first (C99 6.3.1.8p1).
1280 if (LHSType->isComplexType() || RHSType->isComplexType())
1281 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1284 // Now handle "real" floating types (i.e. float, double, long double).
1285 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1286 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1289 // Handle GCC complex int extension.
1290 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1291 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1294 // Finally, we have two differing integer types.
1295 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1296 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1300 //===----------------------------------------------------------------------===//
1301 // Semantic Analysis for various Expression Types
1302 //===----------------------------------------------------------------------===//
1306 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1307 SourceLocation DefaultLoc,
1308 SourceLocation RParenLoc,
1309 Expr *ControllingExpr,
1310 ArrayRef<ParsedType> ArgTypes,
1311 ArrayRef<Expr *> ArgExprs) {
1312 unsigned NumAssocs = ArgTypes.size();
1313 assert(NumAssocs == ArgExprs.size());
1315 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1316 for (unsigned i = 0; i < NumAssocs; ++i) {
1318 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1323 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1325 llvm::makeArrayRef(Types, NumAssocs),
1332 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1333 SourceLocation DefaultLoc,
1334 SourceLocation RParenLoc,
1335 Expr *ControllingExpr,
1336 ArrayRef<TypeSourceInfo *> Types,
1337 ArrayRef<Expr *> Exprs) {
1338 unsigned NumAssocs = Types.size();
1339 assert(NumAssocs == Exprs.size());
1341 // Decay and strip qualifiers for the controlling expression type, and handle
1342 // placeholder type replacement. See committee discussion from WG14 DR423.
1344 EnterExpressionEvaluationContext Unevaluated(
1345 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1346 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1349 ControllingExpr = R.get();
1352 // The controlling expression is an unevaluated operand, so side effects are
1353 // likely unintended.
1354 if (!inTemplateInstantiation() &&
1355 ControllingExpr->HasSideEffects(Context, false))
1356 Diag(ControllingExpr->getExprLoc(),
1357 diag::warn_side_effects_unevaluated_context);
1359 bool TypeErrorFound = false,
1360 IsResultDependent = ControllingExpr->isTypeDependent(),
1361 ContainsUnexpandedParameterPack
1362 = ControllingExpr->containsUnexpandedParameterPack();
1364 for (unsigned i = 0; i < NumAssocs; ++i) {
1365 if (Exprs[i]->containsUnexpandedParameterPack())
1366 ContainsUnexpandedParameterPack = true;
1369 if (Types[i]->getType()->containsUnexpandedParameterPack())
1370 ContainsUnexpandedParameterPack = true;
1372 if (Types[i]->getType()->isDependentType()) {
1373 IsResultDependent = true;
1375 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1376 // complete object type other than a variably modified type."
1378 if (Types[i]->getType()->isIncompleteType())
1379 D = diag::err_assoc_type_incomplete;
1380 else if (!Types[i]->getType()->isObjectType())
1381 D = diag::err_assoc_type_nonobject;
1382 else if (Types[i]->getType()->isVariablyModifiedType())
1383 D = diag::err_assoc_type_variably_modified;
1386 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1387 << Types[i]->getTypeLoc().getSourceRange()
1388 << Types[i]->getType();
1389 TypeErrorFound = true;
1392 // C11 6.5.1.1p2 "No two generic associations in the same generic
1393 // selection shall specify compatible types."
1394 for (unsigned j = i+1; j < NumAssocs; ++j)
1395 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1396 Context.typesAreCompatible(Types[i]->getType(),
1397 Types[j]->getType())) {
1398 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1399 diag::err_assoc_compatible_types)
1400 << Types[j]->getTypeLoc().getSourceRange()
1401 << Types[j]->getType()
1402 << Types[i]->getType();
1403 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1404 diag::note_compat_assoc)
1405 << Types[i]->getTypeLoc().getSourceRange()
1406 << Types[i]->getType();
1407 TypeErrorFound = true;
1415 // If we determined that the generic selection is result-dependent, don't
1416 // try to compute the result expression.
1417 if (IsResultDependent)
1418 return new (Context) GenericSelectionExpr(
1419 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1420 ContainsUnexpandedParameterPack);
1422 SmallVector<unsigned, 1> CompatIndices;
1423 unsigned DefaultIndex = -1U;
1424 for (unsigned i = 0; i < NumAssocs; ++i) {
1427 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1428 Types[i]->getType()))
1429 CompatIndices.push_back(i);
1432 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1433 // type compatible with at most one of the types named in its generic
1434 // association list."
1435 if (CompatIndices.size() > 1) {
1436 // We strip parens here because the controlling expression is typically
1437 // parenthesized in macro definitions.
1438 ControllingExpr = ControllingExpr->IgnoreParens();
1439 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1440 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1441 << (unsigned) CompatIndices.size();
1442 for (unsigned I : CompatIndices) {
1443 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1444 diag::note_compat_assoc)
1445 << Types[I]->getTypeLoc().getSourceRange()
1446 << Types[I]->getType();
1451 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1452 // its controlling expression shall have type compatible with exactly one of
1453 // the types named in its generic association list."
1454 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1455 // We strip parens here because the controlling expression is typically
1456 // parenthesized in macro definitions.
1457 ControllingExpr = ControllingExpr->IgnoreParens();
1458 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1459 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1463 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1464 // type name that is compatible with the type of the controlling expression,
1465 // then the result expression of the generic selection is the expression
1466 // in that generic association. Otherwise, the result expression of the
1467 // generic selection is the expression in the default generic association."
1468 unsigned ResultIndex =
1469 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1471 return new (Context) GenericSelectionExpr(
1472 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1473 ContainsUnexpandedParameterPack, ResultIndex);
1476 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1477 /// location of the token and the offset of the ud-suffix within it.
1478 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1480 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1484 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1485 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1486 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1487 IdentifierInfo *UDSuffix,
1488 SourceLocation UDSuffixLoc,
1489 ArrayRef<Expr*> Args,
1490 SourceLocation LitEndLoc) {
1491 assert(Args.size() <= 2 && "too many arguments for literal operator");
1494 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1495 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1496 if (ArgTy[ArgIdx]->isArrayType())
1497 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1500 DeclarationName OpName =
1501 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1502 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1503 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1505 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1506 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1507 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1508 /*AllowStringTemplate*/ false,
1509 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1512 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1515 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1516 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1517 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1518 /// multiple tokens. However, the common case is that StringToks points to one
1522 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1523 assert(!StringToks.empty() && "Must have at least one string!");
1525 StringLiteralParser Literal(StringToks, PP);
1526 if (Literal.hadError)
1529 SmallVector<SourceLocation, 4> StringTokLocs;
1530 for (const Token &Tok : StringToks)
1531 StringTokLocs.push_back(Tok.getLocation());
1533 QualType CharTy = Context.CharTy;
1534 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1535 if (Literal.isWide()) {
1536 CharTy = Context.getWideCharType();
1537 Kind = StringLiteral::Wide;
1538 } else if (Literal.isUTF8()) {
1539 if (getLangOpts().Char8)
1540 CharTy = Context.Char8Ty;
1541 Kind = StringLiteral::UTF8;
1542 } else if (Literal.isUTF16()) {
1543 CharTy = Context.Char16Ty;
1544 Kind = StringLiteral::UTF16;
1545 } else if (Literal.isUTF32()) {
1546 CharTy = Context.Char32Ty;
1547 Kind = StringLiteral::UTF32;
1548 } else if (Literal.isPascal()) {
1549 CharTy = Context.UnsignedCharTy;
1552 QualType CharTyConst = CharTy;
1553 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1554 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1555 CharTyConst.addConst();
1557 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1559 // Get an array type for the string, according to C99 6.4.5. This includes
1560 // the nul terminator character as well as the string length for pascal
1562 QualType StrTy = Context.getConstantArrayType(
1563 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1564 ArrayType::Normal, 0);
1566 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1567 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1568 Kind, Literal.Pascal, StrTy,
1570 StringTokLocs.size());
1571 if (Literal.getUDSuffix().empty())
1574 // We're building a user-defined literal.
1575 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1576 SourceLocation UDSuffixLoc =
1577 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1578 Literal.getUDSuffixOffset());
1580 // Make sure we're allowed user-defined literals here.
1582 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1584 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1585 // operator "" X (str, len)
1586 QualType SizeType = Context.getSizeType();
1588 DeclarationName OpName =
1589 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1593 QualType ArgTy[] = {
1594 Context.getArrayDecayedType(StrTy), SizeType
1597 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1598 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1599 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1600 /*AllowStringTemplate*/ true,
1601 /*DiagnoseMissing*/ true)) {
1604 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1605 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1607 Expr *Args[] = { Lit, LenArg };
1609 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1612 case LOLR_StringTemplate: {
1613 TemplateArgumentListInfo ExplicitArgs;
1615 unsigned CharBits = Context.getIntWidth(CharTy);
1616 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1617 llvm::APSInt Value(CharBits, CharIsUnsigned);
1619 TemplateArgument TypeArg(CharTy);
1620 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1621 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1623 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1624 Value = Lit->getCodeUnit(I);
1625 TemplateArgument Arg(Context, Value, CharTy);
1626 TemplateArgumentLocInfo ArgInfo;
1627 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1629 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1634 case LOLR_ErrorNoDiagnostic:
1635 llvm_unreachable("unexpected literal operator lookup result");
1639 llvm_unreachable("unexpected literal operator lookup result");
1643 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1645 const CXXScopeSpec *SS) {
1646 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1647 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1650 /// BuildDeclRefExpr - Build an expression that references a
1651 /// declaration that does not require a closure capture.
1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1654 const DeclarationNameInfo &NameInfo,
1655 const CXXScopeSpec *SS, NamedDecl *FoundD,
1656 const TemplateArgumentListInfo *TemplateArgs) {
1657 bool RefersToCapturedVariable =
1659 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1662 if (isa<VarTemplateSpecializationDecl>(D)) {
1663 VarTemplateSpecializationDecl *VarSpec =
1664 cast<VarTemplateSpecializationDecl>(D);
1666 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1667 : NestedNameSpecifierLoc(),
1668 VarSpec->getTemplateKeywordLoc(), D,
1669 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1670 FoundD, TemplateArgs);
1672 assert(!TemplateArgs && "No template arguments for non-variable"
1673 " template specialization references");
1674 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1675 : NestedNameSpecifierLoc(),
1676 SourceLocation(), D, RefersToCapturedVariable,
1677 NameInfo, Ty, VK, FoundD);
1680 MarkDeclRefReferenced(E);
1682 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1683 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1684 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1685 getCurFunction()->recordUseOfWeak(E);
1687 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1688 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1689 FD = IFD->getAnonField();
1691 UnusedPrivateFields.remove(FD);
1692 // Just in case we're building an illegal pointer-to-member.
1693 if (FD->isBitField())
1694 E->setObjectKind(OK_BitField);
1697 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1698 // designates a bit-field.
1699 if (auto *BD = dyn_cast<BindingDecl>(D))
1700 if (auto *BE = BD->getBinding())
1701 E->setObjectKind(BE->getObjectKind());
1706 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1707 /// possibly a list of template arguments.
1709 /// If this produces template arguments, it is permitted to call
1710 /// DecomposeTemplateName.
1712 /// This actually loses a lot of source location information for
1713 /// non-standard name kinds; we should consider preserving that in
1716 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1717 TemplateArgumentListInfo &Buffer,
1718 DeclarationNameInfo &NameInfo,
1719 const TemplateArgumentListInfo *&TemplateArgs) {
1720 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1721 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1722 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1724 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1725 Id.TemplateId->NumArgs);
1726 translateTemplateArguments(TemplateArgsPtr, Buffer);
1728 TemplateName TName = Id.TemplateId->Template.get();
1729 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1730 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1731 TemplateArgs = &Buffer;
1733 NameInfo = GetNameFromUnqualifiedId(Id);
1734 TemplateArgs = nullptr;
1738 static void emitEmptyLookupTypoDiagnostic(
1739 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1740 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1741 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1743 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1745 // Emit a special diagnostic for failed member lookups.
1746 // FIXME: computing the declaration context might fail here (?)
1748 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1751 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1755 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1756 bool DroppedSpecifier =
1757 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1758 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1759 ? diag::note_implicit_param_decl
1760 : diag::note_previous_decl;
1762 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1763 SemaRef.PDiag(NoteID));
1765 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1766 << Typo << Ctx << DroppedSpecifier
1768 SemaRef.PDiag(NoteID));
1771 /// Diagnose an empty lookup.
1773 /// \return false if new lookup candidates were found
1775 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1776 std::unique_ptr<CorrectionCandidateCallback> CCC,
1777 TemplateArgumentListInfo *ExplicitTemplateArgs,
1778 ArrayRef<Expr *> Args, TypoExpr **Out) {
1779 DeclarationName Name = R.getLookupName();
1781 unsigned diagnostic = diag::err_undeclared_var_use;
1782 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1783 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1784 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1785 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1786 diagnostic = diag::err_undeclared_use;
1787 diagnostic_suggest = diag::err_undeclared_use_suggest;
1790 // If the original lookup was an unqualified lookup, fake an
1791 // unqualified lookup. This is useful when (for example) the
1792 // original lookup would not have found something because it was a
1794 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1796 if (isa<CXXRecordDecl>(DC)) {
1797 LookupQualifiedName(R, DC);
1800 // Don't give errors about ambiguities in this lookup.
1801 R.suppressDiagnostics();
1803 // During a default argument instantiation the CurContext points
1804 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1805 // function parameter list, hence add an explicit check.
1806 bool isDefaultArgument =
1807 !CodeSynthesisContexts.empty() &&
1808 CodeSynthesisContexts.back().Kind ==
1809 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1810 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1811 bool isInstance = CurMethod &&
1812 CurMethod->isInstance() &&
1813 DC == CurMethod->getParent() && !isDefaultArgument;
1815 // Give a code modification hint to insert 'this->'.
1816 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1817 // Actually quite difficult!
1818 if (getLangOpts().MSVCCompat)
1819 diagnostic = diag::ext_found_via_dependent_bases_lookup;
1821 Diag(R.getNameLoc(), diagnostic) << Name
1822 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1823 CheckCXXThisCapture(R.getNameLoc());
1825 Diag(R.getNameLoc(), diagnostic) << Name;
1828 // Do we really want to note all of these?
1829 for (NamedDecl *D : R)
1830 Diag(D->getLocation(), diag::note_dependent_var_use);
1832 // Return true if we are inside a default argument instantiation
1833 // and the found name refers to an instance member function, otherwise
1834 // the function calling DiagnoseEmptyLookup will try to create an
1835 // implicit member call and this is wrong for default argument.
1836 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1837 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1841 // Tell the callee to try to recover.
1848 // In Microsoft mode, if we are performing lookup from within a friend
1849 // function definition declared at class scope then we must set
1850 // DC to the lexical parent to be able to search into the parent
1852 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1853 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1854 DC->getLexicalParent()->isRecord())
1855 DC = DC->getLexicalParent();
1857 DC = DC->getParent();
1860 // We didn't find anything, so try to correct for a typo.
1861 TypoCorrection Corrected;
1863 SourceLocation TypoLoc = R.getNameLoc();
1864 assert(!ExplicitTemplateArgs &&
1865 "Diagnosing an empty lookup with explicit template args!");
1866 *Out = CorrectTypoDelayed(
1867 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1868 [=](const TypoCorrection &TC) {
1869 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1870 diagnostic, diagnostic_suggest);
1872 nullptr, CTK_ErrorRecovery);
1875 } else if (S && (Corrected =
1876 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1877 &SS, std::move(CCC), CTK_ErrorRecovery))) {
1878 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1879 bool DroppedSpecifier =
1880 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1881 R.setLookupName(Corrected.getCorrection());
1883 bool AcceptableWithRecovery = false;
1884 bool AcceptableWithoutRecovery = false;
1885 NamedDecl *ND = Corrected.getFoundDecl();
1887 if (Corrected.isOverloaded()) {
1888 OverloadCandidateSet OCS(R.getNameLoc(),
1889 OverloadCandidateSet::CSK_Normal);
1890 OverloadCandidateSet::iterator Best;
1891 for (NamedDecl *CD : Corrected) {
1892 if (FunctionTemplateDecl *FTD =
1893 dyn_cast<FunctionTemplateDecl>(CD))
1894 AddTemplateOverloadCandidate(
1895 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1897 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1898 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1899 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1902 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1904 ND = Best->FoundDecl;
1905 Corrected.setCorrectionDecl(ND);
1908 // FIXME: Arbitrarily pick the first declaration for the note.
1909 Corrected.setCorrectionDecl(ND);
1914 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1915 CXXRecordDecl *Record = nullptr;
1916 if (Corrected.getCorrectionSpecifier()) {
1917 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1918 Record = Ty->getAsCXXRecordDecl();
1921 Record = cast<CXXRecordDecl>(
1922 ND->getDeclContext()->getRedeclContext());
1923 R.setNamingClass(Record);
1926 auto *UnderlyingND = ND->getUnderlyingDecl();
1927 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1928 isa<FunctionTemplateDecl>(UnderlyingND);
1929 // FIXME: If we ended up with a typo for a type name or
1930 // Objective-C class name, we're in trouble because the parser
1931 // is in the wrong place to recover. Suggest the typo
1932 // correction, but don't make it a fix-it since we're not going
1933 // to recover well anyway.
1934 AcceptableWithoutRecovery =
1935 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1937 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1938 // because we aren't able to recover.
1939 AcceptableWithoutRecovery = true;
1942 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1943 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1944 ? diag::note_implicit_param_decl
1945 : diag::note_previous_decl;
1947 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1948 PDiag(NoteID), AcceptableWithRecovery);
1950 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1951 << Name << computeDeclContext(SS, false)
1952 << DroppedSpecifier << SS.getRange(),
1953 PDiag(NoteID), AcceptableWithRecovery);
1955 // Tell the callee whether to try to recover.
1956 return !AcceptableWithRecovery;
1961 // Emit a special diagnostic for failed member lookups.
1962 // FIXME: computing the declaration context might fail here (?)
1963 if (!SS.isEmpty()) {
1964 Diag(R.getNameLoc(), diag::err_no_member)
1965 << Name << computeDeclContext(SS, false)
1970 // Give up, we can't recover.
1971 Diag(R.getNameLoc(), diagnostic) << Name;
1975 /// In Microsoft mode, if we are inside a template class whose parent class has
1976 /// dependent base classes, and we can't resolve an unqualified identifier, then
1977 /// assume the identifier is a member of a dependent base class. We can only
1978 /// recover successfully in static methods, instance methods, and other contexts
1979 /// where 'this' is available. This doesn't precisely match MSVC's
1980 /// instantiation model, but it's close enough.
1982 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1983 DeclarationNameInfo &NameInfo,
1984 SourceLocation TemplateKWLoc,
1985 const TemplateArgumentListInfo *TemplateArgs) {
1986 // Only try to recover from lookup into dependent bases in static methods or
1987 // contexts where 'this' is available.
1988 QualType ThisType = S.getCurrentThisType();
1989 const CXXRecordDecl *RD = nullptr;
1990 if (!ThisType.isNull())
1991 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1992 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1993 RD = MD->getParent();
1994 if (!RD || !RD->hasAnyDependentBases())
1997 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
1998 // is available, suggest inserting 'this->' as a fixit.
1999 SourceLocation Loc = NameInfo.getLoc();
2000 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2001 DB << NameInfo.getName() << RD;
2003 if (!ThisType.isNull()) {
2004 DB << FixItHint::CreateInsertion(Loc, "this->");
2005 return CXXDependentScopeMemberExpr::Create(
2006 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2007 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2008 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2011 // Synthesize a fake NNS that points to the derived class. This will
2012 // perform name lookup during template instantiation.
2015 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2016 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2017 return DependentScopeDeclRefExpr::Create(
2018 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2023 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2024 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2025 bool HasTrailingLParen, bool IsAddressOfOperand,
2026 std::unique_ptr<CorrectionCandidateCallback> CCC,
2027 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2028 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2029 "cannot be direct & operand and have a trailing lparen");
2033 TemplateArgumentListInfo TemplateArgsBuffer;
2035 // Decompose the UnqualifiedId into the following data.
2036 DeclarationNameInfo NameInfo;
2037 const TemplateArgumentListInfo *TemplateArgs;
2038 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2040 DeclarationName Name = NameInfo.getName();
2041 IdentifierInfo *II = Name.getAsIdentifierInfo();
2042 SourceLocation NameLoc = NameInfo.getLoc();
2044 if (II && II->isEditorPlaceholder()) {
2045 // FIXME: When typed placeholders are supported we can create a typed
2046 // placeholder expression node.
2050 // C++ [temp.dep.expr]p3:
2051 // An id-expression is type-dependent if it contains:
2052 // -- an identifier that was declared with a dependent type,
2053 // (note: handled after lookup)
2054 // -- a template-id that is dependent,
2055 // (note: handled in BuildTemplateIdExpr)
2056 // -- a conversion-function-id that specifies a dependent type,
2057 // -- a nested-name-specifier that contains a class-name that
2058 // names a dependent type.
2059 // Determine whether this is a member of an unknown specialization;
2060 // we need to handle these differently.
2061 bool DependentID = false;
2062 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2063 Name.getCXXNameType()->isDependentType()) {
2065 } else if (SS.isSet()) {
2066 if (DeclContext *DC = computeDeclContext(SS, false)) {
2067 if (RequireCompleteDeclContext(SS, DC))
2075 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2076 IsAddressOfOperand, TemplateArgs);
2078 // Perform the required lookup.
2079 LookupResult R(*this, NameInfo,
2080 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2081 ? LookupObjCImplicitSelfParam
2082 : LookupOrdinaryName);
2083 if (TemplateKWLoc.isValid() || TemplateArgs) {
2084 // Lookup the template name again to correctly establish the context in
2085 // which it was found. This is really unfortunate as we already did the
2086 // lookup to determine that it was a template name in the first place. If
2087 // this becomes a performance hit, we can work harder to preserve those
2088 // results until we get here but it's likely not worth it.
2089 bool MemberOfUnknownSpecialization;
2090 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2091 MemberOfUnknownSpecialization, TemplateKWLoc))
2094 if (MemberOfUnknownSpecialization ||
2095 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2096 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2097 IsAddressOfOperand, TemplateArgs);
2099 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2100 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2102 // If the result might be in a dependent base class, this is a dependent
2104 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2105 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2106 IsAddressOfOperand, TemplateArgs);
2108 // If this reference is in an Objective-C method, then we need to do
2109 // some special Objective-C lookup, too.
2110 if (IvarLookupFollowUp) {
2111 ExprResult E(LookupInObjCMethod(R, S, II, true));
2115 if (Expr *Ex = E.getAs<Expr>())
2120 if (R.isAmbiguous())
2123 // This could be an implicitly declared function reference (legal in C90,
2124 // extension in C99, forbidden in C++).
2125 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2126 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2127 if (D) R.addDecl(D);
2130 // Determine whether this name might be a candidate for
2131 // argument-dependent lookup.
2132 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2134 if (R.empty() && !ADL) {
2135 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2136 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2137 TemplateKWLoc, TemplateArgs))
2141 // Don't diagnose an empty lookup for inline assembly.
2142 if (IsInlineAsmIdentifier)
2145 // If this name wasn't predeclared and if this is not a function
2146 // call, diagnose the problem.
2147 TypoExpr *TE = nullptr;
2148 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2149 II, SS.isValid() ? SS.getScopeRep() : nullptr);
2150 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2151 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2152 "Typo correction callback misconfigured");
2154 // Make sure the callback knows what the typo being diagnosed is.
2155 CCC->setTypoName(II);
2157 CCC->setTypoNNS(SS.getScopeRep());
2159 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2160 // a template name, but we happen to have always already looked up the name
2161 // before we get here if it must be a template name.
2162 if (DiagnoseEmptyLookup(S, SS, R,
2163 CCC ? std::move(CCC) : std::move(DefaultValidator),
2164 nullptr, None, &TE)) {
2165 if (TE && KeywordReplacement) {
2166 auto &State = getTypoExprState(TE);
2167 auto BestTC = State.Consumer->getNextCorrection();
2168 if (BestTC.isKeyword()) {
2169 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2170 if (State.DiagHandler)
2171 State.DiagHandler(BestTC);
2172 KeywordReplacement->startToken();
2173 KeywordReplacement->setKind(II->getTokenID());
2174 KeywordReplacement->setIdentifierInfo(II);
2175 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2176 // Clean up the state associated with the TypoExpr, since it has
2177 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2178 clearDelayedTypo(TE);
2179 // Signal that a correction to a keyword was performed by returning a
2180 // valid-but-null ExprResult.
2181 return (Expr*)nullptr;
2183 State.Consumer->resetCorrectionStream();
2185 return TE ? TE : ExprError();
2188 assert(!R.empty() &&
2189 "DiagnoseEmptyLookup returned false but added no results");
2191 // If we found an Objective-C instance variable, let
2192 // LookupInObjCMethod build the appropriate expression to
2193 // reference the ivar.
2194 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2196 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2197 // In a hopelessly buggy code, Objective-C instance variable
2198 // lookup fails and no expression will be built to reference it.
2199 if (!E.isInvalid() && !E.get())
2205 // This is guaranteed from this point on.
2206 assert(!R.empty() || ADL);
2208 // Check whether this might be a C++ implicit instance member access.
2209 // C++ [class.mfct.non-static]p3:
2210 // When an id-expression that is not part of a class member access
2211 // syntax and not used to form a pointer to member is used in the
2212 // body of a non-static member function of class X, if name lookup
2213 // resolves the name in the id-expression to a non-static non-type
2214 // member of some class C, the id-expression is transformed into a
2215 // class member access expression using (*this) as the
2216 // postfix-expression to the left of the . operator.
2218 // But we don't actually need to do this for '&' operands if R
2219 // resolved to a function or overloaded function set, because the
2220 // expression is ill-formed if it actually works out to be a
2221 // non-static member function:
2223 // C++ [expr.ref]p4:
2224 // Otherwise, if E1.E2 refers to a non-static member function. . .
2225 // [t]he expression can be used only as the left-hand operand of a
2226 // member function call.
2228 // There are other safeguards against such uses, but it's important
2229 // to get this right here so that we don't end up making a
2230 // spuriously dependent expression if we're inside a dependent
2232 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2233 bool MightBeImplicitMember;
2234 if (!IsAddressOfOperand)
2235 MightBeImplicitMember = true;
2236 else if (!SS.isEmpty())
2237 MightBeImplicitMember = false;
2238 else if (R.isOverloadedResult())
2239 MightBeImplicitMember = false;
2240 else if (R.isUnresolvableResult())
2241 MightBeImplicitMember = true;
2243 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2244 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2245 isa<MSPropertyDecl>(R.getFoundDecl());
2247 if (MightBeImplicitMember)
2248 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2249 R, TemplateArgs, S);
2252 if (TemplateArgs || TemplateKWLoc.isValid()) {
2254 // In C++1y, if this is a variable template id, then check it
2255 // in BuildTemplateIdExpr().
2256 // The single lookup result must be a variable template declaration.
2257 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2258 Id.TemplateId->Kind == TNK_Var_template) {
2259 assert(R.getAsSingle<VarTemplateDecl>() &&
2260 "There should only be one declaration found.");
2263 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2266 return BuildDeclarationNameExpr(SS, R, ADL);
2269 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2270 /// declaration name, generally during template instantiation.
2271 /// There's a large number of things which don't need to be done along
2273 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2274 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2275 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2276 DeclContext *DC = computeDeclContext(SS, false);
2278 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2279 NameInfo, /*TemplateArgs=*/nullptr);
2281 if (RequireCompleteDeclContext(SS, DC))
2284 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2285 LookupQualifiedName(R, DC);
2287 if (R.isAmbiguous())
2290 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2291 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2292 NameInfo, /*TemplateArgs=*/nullptr);
2295 Diag(NameInfo.getLoc(), diag::err_no_member)
2296 << NameInfo.getName() << DC << SS.getRange();
2300 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2301 // Diagnose a missing typename if this resolved unambiguously to a type in
2302 // a dependent context. If we can recover with a type, downgrade this to
2303 // a warning in Microsoft compatibility mode.
2304 unsigned DiagID = diag::err_typename_missing;
2305 if (RecoveryTSI && getLangOpts().MSVCCompat)
2306 DiagID = diag::ext_typename_missing;
2307 SourceLocation Loc = SS.getBeginLoc();
2308 auto D = Diag(Loc, DiagID);
2309 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2310 << SourceRange(Loc, NameInfo.getEndLoc());
2312 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2317 // Only issue the fixit if we're prepared to recover.
2318 D << FixItHint::CreateInsertion(Loc, "typename ");
2320 // Recover by pretending this was an elaborated type.
2321 QualType Ty = Context.getTypeDeclType(TD);
2323 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2325 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2326 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2327 QTL.setElaboratedKeywordLoc(SourceLocation());
2328 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2330 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2335 // Defend against this resolving to an implicit member access. We usually
2336 // won't get here if this might be a legitimate a class member (we end up in
2337 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2338 // a pointer-to-member or in an unevaluated context in C++11.
2339 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2340 return BuildPossibleImplicitMemberExpr(SS,
2341 /*TemplateKWLoc=*/SourceLocation(),
2342 R, /*TemplateArgs=*/nullptr, S);
2344 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2347 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2348 /// detected that we're currently inside an ObjC method. Perform some
2349 /// additional lookup.
2351 /// Ideally, most of this would be done by lookup, but there's
2352 /// actually quite a lot of extra work involved.
2354 /// Returns a null sentinel to indicate trivial success.
2356 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2357 IdentifierInfo *II, bool AllowBuiltinCreation) {
2358 SourceLocation Loc = Lookup.getNameLoc();
2359 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2361 // Check for error condition which is already reported.
2365 // There are two cases to handle here. 1) scoped lookup could have failed,
2366 // in which case we should look for an ivar. 2) scoped lookup could have
2367 // found a decl, but that decl is outside the current instance method (i.e.
2368 // a global variable). In these two cases, we do a lookup for an ivar with
2369 // this name, if the lookup sucedes, we replace it our current decl.
2371 // If we're in a class method, we don't normally want to look for
2372 // ivars. But if we don't find anything else, and there's an
2373 // ivar, that's an error.
2374 bool IsClassMethod = CurMethod->isClassMethod();
2378 LookForIvars = true;
2379 else if (IsClassMethod)
2380 LookForIvars = false;
2382 LookForIvars = (Lookup.isSingleResult() &&
2383 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2384 ObjCInterfaceDecl *IFace = nullptr;
2386 IFace = CurMethod->getClassInterface();
2387 ObjCInterfaceDecl *ClassDeclared;
2388 ObjCIvarDecl *IV = nullptr;
2389 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2390 // Diagnose using an ivar in a class method.
2392 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2393 << IV->getDeclName());
2395 // If we're referencing an invalid decl, just return this as a silent
2396 // error node. The error diagnostic was already emitted on the decl.
2397 if (IV->isInvalidDecl())
2400 // Check if referencing a field with __attribute__((deprecated)).
2401 if (DiagnoseUseOfDecl(IV, Loc))
2404 // Diagnose the use of an ivar outside of the declaring class.
2405 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2406 !declaresSameEntity(ClassDeclared, IFace) &&
2407 !getLangOpts().DebuggerSupport)
2408 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2410 // FIXME: This should use a new expr for a direct reference, don't
2411 // turn this into Self->ivar, just return a BareIVarExpr or something.
2412 IdentifierInfo &II = Context.Idents.get("self");
2413 UnqualifiedId SelfName;
2414 SelfName.setIdentifier(&II, SourceLocation());
2415 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2416 CXXScopeSpec SelfScopeSpec;
2417 SourceLocation TemplateKWLoc;
2418 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2419 SelfName, false, false);
2420 if (SelfExpr.isInvalid())
2423 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2424 if (SelfExpr.isInvalid())
2427 MarkAnyDeclReferenced(Loc, IV, true);
2429 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2430 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2431 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2432 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2434 ObjCIvarRefExpr *Result = new (Context)
2435 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2436 IV->getLocation(), SelfExpr.get(), true, true);
2438 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2439 if (!isUnevaluatedContext() &&
2440 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2441 getCurFunction()->recordUseOfWeak(Result);
2443 if (getLangOpts().ObjCAutoRefCount) {
2444 if (CurContext->isClosure())
2445 Diag(Loc, diag::warn_implicitly_retains_self)
2446 << FixItHint::CreateInsertion(Loc, "self->");
2451 } else if (CurMethod->isInstanceMethod()) {
2452 // We should warn if a local variable hides an ivar.
2453 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2454 ObjCInterfaceDecl *ClassDeclared;
2455 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2456 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2457 declaresSameEntity(IFace, ClassDeclared))
2458 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2461 } else if (Lookup.isSingleResult() &&
2462 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2463 // If accessing a stand-alone ivar in a class method, this is an error.
2464 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2465 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2466 << IV->getDeclName());
2469 if (Lookup.empty() && II && AllowBuiltinCreation) {
2470 // FIXME. Consolidate this with similar code in LookupName.
2471 if (unsigned BuiltinID = II->getBuiltinID()) {
2472 if (!(getLangOpts().CPlusPlus &&
2473 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2474 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2475 S, Lookup.isForRedeclaration(),
2476 Lookup.getNameLoc());
2477 if (D) Lookup.addDecl(D);
2481 // Sentinel value saying that we didn't do anything special.
2482 return ExprResult((Expr *)nullptr);
2485 /// Cast a base object to a member's actual type.
2487 /// Logically this happens in three phases:
2489 /// * First we cast from the base type to the naming class.
2490 /// The naming class is the class into which we were looking
2491 /// when we found the member; it's the qualifier type if a
2492 /// qualifier was provided, and otherwise it's the base type.
2494 /// * Next we cast from the naming class to the declaring class.
2495 /// If the member we found was brought into a class's scope by
2496 /// a using declaration, this is that class; otherwise it's
2497 /// the class declaring the member.
2499 /// * Finally we cast from the declaring class to the "true"
2500 /// declaring class of the member. This conversion does not
2501 /// obey access control.
2503 Sema::PerformObjectMemberConversion(Expr *From,
2504 NestedNameSpecifier *Qualifier,
2505 NamedDecl *FoundDecl,
2506 NamedDecl *Member) {
2507 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2511 QualType DestRecordType;
2513 QualType FromRecordType;
2514 QualType FromType = From->getType();
2515 bool PointerConversions = false;
2516 if (isa<FieldDecl>(Member)) {
2517 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2519 if (FromType->getAs<PointerType>()) {
2520 DestType = Context.getPointerType(DestRecordType);
2521 FromRecordType = FromType->getPointeeType();
2522 PointerConversions = true;
2524 DestType = DestRecordType;
2525 FromRecordType = FromType;
2527 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2528 if (Method->isStatic())
2531 DestType = Method->getThisType(Context);
2532 DestRecordType = DestType->getPointeeType();
2534 if (FromType->getAs<PointerType>()) {
2535 FromRecordType = FromType->getPointeeType();
2536 PointerConversions = true;
2538 FromRecordType = FromType;
2539 DestType = DestRecordType;
2542 // No conversion necessary.
2546 if (DestType->isDependentType() || FromType->isDependentType())
2549 // If the unqualified types are the same, no conversion is necessary.
2550 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2553 SourceRange FromRange = From->getSourceRange();
2554 SourceLocation FromLoc = FromRange.getBegin();
2556 ExprValueKind VK = From->getValueKind();
2558 // C++ [class.member.lookup]p8:
2559 // [...] Ambiguities can often be resolved by qualifying a name with its
2562 // If the member was a qualified name and the qualified referred to a
2563 // specific base subobject type, we'll cast to that intermediate type
2564 // first and then to the object in which the member is declared. That allows
2565 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2567 // class Base { public: int x; };
2568 // class Derived1 : public Base { };
2569 // class Derived2 : public Base { };
2570 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2572 // void VeryDerived::f() {
2573 // x = 17; // error: ambiguous base subobjects
2574 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2576 if (Qualifier && Qualifier->getAsType()) {
2577 QualType QType = QualType(Qualifier->getAsType(), 0);
2578 assert(QType->isRecordType() && "lookup done with non-record type");
2580 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2582 // In C++98, the qualifier type doesn't actually have to be a base
2583 // type of the object type, in which case we just ignore it.
2584 // Otherwise build the appropriate casts.
2585 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2586 CXXCastPath BasePath;
2587 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2588 FromLoc, FromRange, &BasePath))
2591 if (PointerConversions)
2592 QType = Context.getPointerType(QType);
2593 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2594 VK, &BasePath).get();
2597 FromRecordType = QRecordType;
2599 // If the qualifier type was the same as the destination type,
2601 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2606 bool IgnoreAccess = false;
2608 // If we actually found the member through a using declaration, cast
2609 // down to the using declaration's type.
2611 // Pointer equality is fine here because only one declaration of a
2612 // class ever has member declarations.
2613 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2614 assert(isa<UsingShadowDecl>(FoundDecl));
2615 QualType URecordType = Context.getTypeDeclType(
2616 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2618 // We only need to do this if the naming-class to declaring-class
2619 // conversion is non-trivial.
2620 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2621 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2622 CXXCastPath BasePath;
2623 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2624 FromLoc, FromRange, &BasePath))
2627 QualType UType = URecordType;
2628 if (PointerConversions)
2629 UType = Context.getPointerType(UType);
2630 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2631 VK, &BasePath).get();
2633 FromRecordType = URecordType;
2636 // We don't do access control for the conversion from the
2637 // declaring class to the true declaring class.
2638 IgnoreAccess = true;
2641 CXXCastPath BasePath;
2642 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2643 FromLoc, FromRange, &BasePath,
2647 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2651 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2652 const LookupResult &R,
2653 bool HasTrailingLParen) {
2654 // Only when used directly as the postfix-expression of a call.
2655 if (!HasTrailingLParen)
2658 // Never if a scope specifier was provided.
2662 // Only in C++ or ObjC++.
2663 if (!getLangOpts().CPlusPlus)
2666 // Turn off ADL when we find certain kinds of declarations during
2668 for (NamedDecl *D : R) {
2669 // C++0x [basic.lookup.argdep]p3:
2670 // -- a declaration of a class member
2671 // Since using decls preserve this property, we check this on the
2673 if (D->isCXXClassMember())
2676 // C++0x [basic.lookup.argdep]p3:
2677 // -- a block-scope function declaration that is not a
2678 // using-declaration
2679 // NOTE: we also trigger this for function templates (in fact, we
2680 // don't check the decl type at all, since all other decl types
2681 // turn off ADL anyway).
2682 if (isa<UsingShadowDecl>(D))
2683 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2684 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2687 // C++0x [basic.lookup.argdep]p3:
2688 // -- a declaration that is neither a function or a function
2690 // And also for builtin functions.
2691 if (isa<FunctionDecl>(D)) {
2692 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2694 // But also builtin functions.
2695 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2697 } else if (!isa<FunctionTemplateDecl>(D))
2705 /// Diagnoses obvious problems with the use of the given declaration
2706 /// as an expression. This is only actually called for lookups that
2707 /// were not overloaded, and it doesn't promise that the declaration
2708 /// will in fact be used.
2709 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2710 if (D->isInvalidDecl())
2713 if (isa<TypedefNameDecl>(D)) {
2714 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2718 if (isa<ObjCInterfaceDecl>(D)) {
2719 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2723 if (isa<NamespaceDecl>(D)) {
2724 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2731 // Certain multiversion types should be treated as overloaded even when there is
2733 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2734 assert(R.isSingleResult() && "Expected only a single result");
2735 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2737 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2740 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2741 LookupResult &R, bool NeedsADL,
2742 bool AcceptInvalidDecl) {
2743 // If this is a single, fully-resolved result and we don't need ADL,
2744 // just build an ordinary singleton decl ref.
2745 if (!NeedsADL && R.isSingleResult() &&
2746 !R.getAsSingle<FunctionTemplateDecl>() &&
2747 !ShouldLookupResultBeMultiVersionOverload(R))
2748 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2749 R.getRepresentativeDecl(), nullptr,
2752 // We only need to check the declaration if there's exactly one
2753 // result, because in the overloaded case the results can only be
2754 // functions and function templates.
2755 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2756 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2759 // Otherwise, just build an unresolved lookup expression. Suppress
2760 // any lookup-related diagnostics; we'll hash these out later, when
2761 // we've picked a target.
2762 R.suppressDiagnostics();
2764 UnresolvedLookupExpr *ULE
2765 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2766 SS.getWithLocInContext(Context),
2767 R.getLookupNameInfo(),
2768 NeedsADL, R.isOverloadedResult(),
2769 R.begin(), R.end());
2775 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2776 ValueDecl *var, DeclContext *DC);
2778 /// Complete semantic analysis for a reference to the given declaration.
2779 ExprResult Sema::BuildDeclarationNameExpr(
2780 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2781 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2782 bool AcceptInvalidDecl) {
2783 assert(D && "Cannot refer to a NULL declaration");
2784 assert(!isa<FunctionTemplateDecl>(D) &&
2785 "Cannot refer unambiguously to a function template");
2787 SourceLocation Loc = NameInfo.getLoc();
2788 if (CheckDeclInExpr(*this, Loc, D))
2791 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2792 // Specifically diagnose references to class templates that are missing
2793 // a template argument list.
2794 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2798 // Make sure that we're referring to a value.
2799 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2801 Diag(Loc, diag::err_ref_non_value)
2802 << D << SS.getRange();
2803 Diag(D->getLocation(), diag::note_declared_at);
2807 // Check whether this declaration can be used. Note that we suppress
2808 // this check when we're going to perform argument-dependent lookup
2809 // on this function name, because this might not be the function
2810 // that overload resolution actually selects.
2811 if (DiagnoseUseOfDecl(VD, Loc))
2814 // Only create DeclRefExpr's for valid Decl's.
2815 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2818 // Handle members of anonymous structs and unions. If we got here,
2819 // and the reference is to a class member indirect field, then this
2820 // must be the subject of a pointer-to-member expression.
2821 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2822 if (!indirectField->isCXXClassMember())
2823 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2827 QualType type = VD->getType();
2830 if (auto *FPT = type->getAs<FunctionProtoType>()) {
2831 // C++ [except.spec]p17:
2832 // An exception-specification is considered to be needed when:
2833 // - in an expression, the function is the unique lookup result or
2834 // the selected member of a set of overloaded functions.
2835 ResolveExceptionSpec(Loc, FPT);
2836 type = VD->getType();
2838 ExprValueKind valueKind = VK_RValue;
2840 switch (D->getKind()) {
2841 // Ignore all the non-ValueDecl kinds.
2842 #define ABSTRACT_DECL(kind)
2843 #define VALUE(type, base)
2844 #define DECL(type, base) \
2846 #include "clang/AST/DeclNodes.inc"
2847 llvm_unreachable("invalid value decl kind");
2849 // These shouldn't make it here.
2850 case Decl::ObjCAtDefsField:
2851 case Decl::ObjCIvar:
2852 llvm_unreachable("forming non-member reference to ivar?");
2854 // Enum constants are always r-values and never references.
2855 // Unresolved using declarations are dependent.
2856 case Decl::EnumConstant:
2857 case Decl::UnresolvedUsingValue:
2858 case Decl::OMPDeclareReduction:
2859 valueKind = VK_RValue;
2862 // Fields and indirect fields that got here must be for
2863 // pointer-to-member expressions; we just call them l-values for
2864 // internal consistency, because this subexpression doesn't really
2865 // exist in the high-level semantics.
2867 case Decl::IndirectField:
2868 assert(getLangOpts().CPlusPlus &&
2869 "building reference to field in C?");
2871 // These can't have reference type in well-formed programs, but
2872 // for internal consistency we do this anyway.
2873 type = type.getNonReferenceType();
2874 valueKind = VK_LValue;
2877 // Non-type template parameters are either l-values or r-values
2878 // depending on the type.
2879 case Decl::NonTypeTemplateParm: {
2880 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2881 type = reftype->getPointeeType();
2882 valueKind = VK_LValue; // even if the parameter is an r-value reference
2886 // For non-references, we need to strip qualifiers just in case
2887 // the template parameter was declared as 'const int' or whatever.
2888 valueKind = VK_RValue;
2889 type = type.getUnqualifiedType();
2894 case Decl::VarTemplateSpecialization:
2895 case Decl::VarTemplatePartialSpecialization:
2896 case Decl::Decomposition:
2897 case Decl::OMPCapturedExpr:
2898 // In C, "extern void blah;" is valid and is an r-value.
2899 if (!getLangOpts().CPlusPlus &&
2900 !type.hasQualifiers() &&
2901 type->isVoidType()) {
2902 valueKind = VK_RValue;
2907 case Decl::ImplicitParam:
2908 case Decl::ParmVar: {
2909 // These are always l-values.
2910 valueKind = VK_LValue;
2911 type = type.getNonReferenceType();
2913 // FIXME: Does the addition of const really only apply in
2914 // potentially-evaluated contexts? Since the variable isn't actually
2915 // captured in an unevaluated context, it seems that the answer is no.
2916 if (!isUnevaluatedContext()) {
2917 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2918 if (!CapturedType.isNull())
2919 type = CapturedType;
2925 case Decl::Binding: {
2926 // These are always lvalues.
2927 valueKind = VK_LValue;
2928 type = type.getNonReferenceType();
2929 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2930 // decides how that's supposed to work.
2931 auto *BD = cast<BindingDecl>(VD);
2932 if (BD->getDeclContext()->isFunctionOrMethod() &&
2933 BD->getDeclContext() != CurContext)
2934 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2938 case Decl::Function: {
2939 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2940 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2941 type = Context.BuiltinFnTy;
2942 valueKind = VK_RValue;
2947 const FunctionType *fty = type->castAs<FunctionType>();
2949 // If we're referring to a function with an __unknown_anytype
2950 // result type, make the entire expression __unknown_anytype.
2951 if (fty->getReturnType() == Context.UnknownAnyTy) {
2952 type = Context.UnknownAnyTy;
2953 valueKind = VK_RValue;
2957 // Functions are l-values in C++.
2958 if (getLangOpts().CPlusPlus) {
2959 valueKind = VK_LValue;
2963 // C99 DR 316 says that, if a function type comes from a
2964 // function definition (without a prototype), that type is only
2965 // used for checking compatibility. Therefore, when referencing
2966 // the function, we pretend that we don't have the full function
2968 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2969 isa<FunctionProtoType>(fty))
2970 type = Context.getFunctionNoProtoType(fty->getReturnType(),
2973 // Functions are r-values in C.
2974 valueKind = VK_RValue;
2978 case Decl::CXXDeductionGuide:
2979 llvm_unreachable("building reference to deduction guide");
2981 case Decl::MSProperty:
2982 valueKind = VK_LValue;
2985 case Decl::CXXMethod:
2986 // If we're referring to a method with an __unknown_anytype
2987 // result type, make the entire expression __unknown_anytype.
2988 // This should only be possible with a type written directly.
2989 if (const FunctionProtoType *proto
2990 = dyn_cast<FunctionProtoType>(VD->getType()))
2991 if (proto->getReturnType() == Context.UnknownAnyTy) {
2992 type = Context.UnknownAnyTy;
2993 valueKind = VK_RValue;
2997 // C++ methods are l-values if static, r-values if non-static.
2998 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2999 valueKind = VK_LValue;
3004 case Decl::CXXConversion:
3005 case Decl::CXXDestructor:
3006 case Decl::CXXConstructor:
3007 valueKind = VK_RValue;
3011 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3016 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3017 SmallString<32> &Target) {
3018 Target.resize(CharByteWidth * (Source.size() + 1));
3019 char *ResultPtr = &Target[0];
3020 const llvm::UTF8 *ErrorPtr;
3022 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3025 Target.resize(ResultPtr - &Target[0]);
3028 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3029 PredefinedExpr::IdentType IT) {
3030 // Pick the current block, lambda, captured statement or function.
3031 Decl *currentDecl = nullptr;
3032 if (const BlockScopeInfo *BSI = getCurBlock())
3033 currentDecl = BSI->TheDecl;
3034 else if (const LambdaScopeInfo *LSI = getCurLambda())
3035 currentDecl = LSI->CallOperator;
3036 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3037 currentDecl = CSI->TheCapturedDecl;
3039 currentDecl = getCurFunctionOrMethodDecl();
3042 Diag(Loc, diag::ext_predef_outside_function);
3043 currentDecl = Context.getTranslationUnitDecl();
3047 StringLiteral *SL = nullptr;
3048 if (cast<DeclContext>(currentDecl)->isDependentContext())
3049 ResTy = Context.DependentTy;
3051 // Pre-defined identifiers are of type char[x], where x is the length of
3053 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3054 unsigned Length = Str.length();
3056 llvm::APInt LengthI(32, Length + 1);
3057 if (IT == PredefinedExpr::LFunction || IT == PredefinedExpr::LFuncSig) {
3059 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3060 SmallString<32> RawChars;
3061 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3063 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3064 /*IndexTypeQuals*/ 0);
3065 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3066 /*Pascal*/ false, ResTy, Loc);
3068 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3069 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3070 /*IndexTypeQuals*/ 0);
3071 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3072 /*Pascal*/ false, ResTy, Loc);
3076 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3079 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3080 PredefinedExpr::IdentType IT;
3083 default: llvm_unreachable("Unknown simple primary expr!");
3084 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3085 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3086 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3087 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3088 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; // [MS]
3089 case tok::kw_L__FUNCSIG__: IT = PredefinedExpr::LFuncSig; break; // [MS]
3090 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3093 return BuildPredefinedExpr(Loc, IT);
3096 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3097 SmallString<16> CharBuffer;
3098 bool Invalid = false;
3099 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3103 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3105 if (Literal.hadError())
3109 if (Literal.isWide())
3110 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3111 else if (Literal.isUTF8() && getLangOpts().Char8)
3112 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3113 else if (Literal.isUTF16())
3114 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3115 else if (Literal.isUTF32())
3116 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3117 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3118 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3120 Ty = Context.CharTy; // 'x' -> char in C++
3122 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3123 if (Literal.isWide())
3124 Kind = CharacterLiteral::Wide;
3125 else if (Literal.isUTF16())
3126 Kind = CharacterLiteral::UTF16;
3127 else if (Literal.isUTF32())
3128 Kind = CharacterLiteral::UTF32;
3129 else if (Literal.isUTF8())
3130 Kind = CharacterLiteral::UTF8;
3132 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3135 if (Literal.getUDSuffix().empty())
3138 // We're building a user-defined literal.
3139 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3140 SourceLocation UDSuffixLoc =
3141 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3143 // Make sure we're allowed user-defined literals here.
3145 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3147 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3148 // operator "" X (ch)
3149 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3150 Lit, Tok.getLocation());
3153 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3154 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3155 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3156 Context.IntTy, Loc);
3159 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3160 QualType Ty, SourceLocation Loc) {
3161 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3163 using llvm::APFloat;
3164 APFloat Val(Format);
3166 APFloat::opStatus result = Literal.GetFloatValue(Val);
3168 // Overflow is always an error, but underflow is only an error if
3169 // we underflowed to zero (APFloat reports denormals as underflow).
3170 if ((result & APFloat::opOverflow) ||
3171 ((result & APFloat::opUnderflow) && Val.isZero())) {
3172 unsigned diagnostic;
3173 SmallString<20> buffer;
3174 if (result & APFloat::opOverflow) {
3175 diagnostic = diag::warn_float_overflow;
3176 APFloat::getLargest(Format).toString(buffer);
3178 diagnostic = diag::warn_float_underflow;
3179 APFloat::getSmallest(Format).toString(buffer);
3182 S.Diag(Loc, diagnostic)
3184 << StringRef(buffer.data(), buffer.size());
3187 bool isExact = (result == APFloat::opOK);
3188 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3191 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3192 assert(E && "Invalid expression");
3194 if (E->isValueDependent())
3197 QualType QT = E->getType();
3198 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3199 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3203 llvm::APSInt ValueAPS;
3204 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3209 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3210 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3211 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3212 << ValueAPS.toString(10) << ValueIsPositive;
3219 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3220 // Fast path for a single digit (which is quite common). A single digit
3221 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3222 if (Tok.getLength() == 1) {
3223 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3224 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3227 SmallString<128> SpellingBuffer;
3228 // NumericLiteralParser wants to overread by one character. Add padding to
3229 // the buffer in case the token is copied to the buffer. If getSpelling()
3230 // returns a StringRef to the memory buffer, it should have a null char at
3231 // the EOF, so it is also safe.
3232 SpellingBuffer.resize(Tok.getLength() + 1);
3234 // Get the spelling of the token, which eliminates trigraphs, etc.
3235 bool Invalid = false;
3236 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3240 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3241 if (Literal.hadError)
3244 if (Literal.hasUDSuffix()) {
3245 // We're building a user-defined literal.
3246 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3247 SourceLocation UDSuffixLoc =
3248 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3250 // Make sure we're allowed user-defined literals here.
3252 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3255 if (Literal.isFloatingLiteral()) {
3256 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3257 // long double, the literal is treated as a call of the form
3258 // operator "" X (f L)
3259 CookedTy = Context.LongDoubleTy;
3261 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3262 // unsigned long long, the literal is treated as a call of the form
3263 // operator "" X (n ULL)
3264 CookedTy = Context.UnsignedLongLongTy;
3267 DeclarationName OpName =
3268 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3269 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3270 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3272 SourceLocation TokLoc = Tok.getLocation();
3274 // Perform literal operator lookup to determine if we're building a raw
3275 // literal or a cooked one.
3276 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3277 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3278 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3279 /*AllowStringTemplate*/ false,
3280 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3281 case LOLR_ErrorNoDiagnostic:
3282 // Lookup failure for imaginary constants isn't fatal, there's still the
3283 // GNU extension producing _Complex types.
3289 if (Literal.isFloatingLiteral()) {
3290 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3292 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3293 if (Literal.GetIntegerValue(ResultVal))
3294 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3295 << /* Unsigned */ 1;
3296 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3299 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3303 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3304 // literal is treated as a call of the form
3305 // operator "" X ("n")
3306 unsigned Length = Literal.getUDSuffixOffset();
3307 QualType StrTy = Context.getConstantArrayType(
3308 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3309 llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3310 Expr *Lit = StringLiteral::Create(
3311 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3312 /*Pascal*/false, StrTy, &TokLoc, 1);
3313 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3316 case LOLR_Template: {
3317 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3318 // template), L is treated as a call fo the form
3319 // operator "" X <'c1', 'c2', ... 'ck'>()
3320 // where n is the source character sequence c1 c2 ... ck.
3321 TemplateArgumentListInfo ExplicitArgs;
3322 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3323 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3324 llvm::APSInt Value(CharBits, CharIsUnsigned);
3325 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3326 Value = TokSpelling[I];
3327 TemplateArgument Arg(Context, Value, Context.CharTy);
3328 TemplateArgumentLocInfo ArgInfo;
3329 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3331 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3334 case LOLR_StringTemplate:
3335 llvm_unreachable("unexpected literal operator lookup result");
3341 if (Literal.isFixedPointLiteral()) {
3344 if (Literal.isAccum) {
3345 if (Literal.isHalf) {
3346 Ty = Context.ShortAccumTy;
3347 } else if (Literal.isLong) {
3348 Ty = Context.LongAccumTy;
3350 Ty = Context.AccumTy;
3352 } else if (Literal.isFract) {
3353 if (Literal.isHalf) {
3354 Ty = Context.ShortFractTy;
3355 } else if (Literal.isLong) {
3356 Ty = Context.LongFractTy;
3358 Ty = Context.FractTy;
3362 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3364 bool isSigned = !Literal.isUnsigned;
3365 unsigned scale = Context.getFixedPointScale(Ty);
3366 unsigned ibits = Context.getFixedPointIBits(Ty);
3367 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3369 llvm::APInt Val(bit_width, 0, isSigned);
3370 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3372 // Do not use bit_width since some types may have padding like _Fract or
3373 // unsigned _Accums if PaddingOnUnsignedFixedPoint is set.
3374 auto MaxVal = llvm::APInt::getMaxValue(ibits + scale).zextOrSelf(bit_width);
3375 if (Literal.isFract && Val == MaxVal + 1)
3376 // Clause 6.4.4 - The value of a constant shall be in the range of
3377 // representable values for its type, with exception for constants of a
3378 // fract type with a value of exactly 1; such a constant shall denote
3379 // the maximal value for the type.
3381 else if (Val.ugt(MaxVal) || Overflowed)
3382 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3384 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3385 Tok.getLocation(), scale);
3386 } else if (Literal.isFloatingLiteral()) {
3388 if (Literal.isHalf){
3389 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3390 Ty = Context.HalfTy;
3392 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3395 } else if (Literal.isFloat)
3396 Ty = Context.FloatTy;
3397 else if (Literal.isLong)
3398 Ty = Context.LongDoubleTy;
3399 else if (Literal.isFloat16)
3400 Ty = Context.Float16Ty;
3401 else if (Literal.isFloat128)
3402 Ty = Context.Float128Ty;
3404 Ty = Context.DoubleTy;
3406 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3408 if (Ty == Context.DoubleTy) {
3409 if (getLangOpts().SinglePrecisionConstants) {
3410 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3411 if (BTy->getKind() != BuiltinType::Float) {
3412 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3414 } else if (getLangOpts().OpenCL &&
3415 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3416 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3417 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3418 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3421 } else if (!Literal.isIntegerLiteral()) {
3426 // 'long long' is a C99 or C++11 feature.
3427 if (!getLangOpts().C99 && Literal.isLongLong) {
3428 if (getLangOpts().CPlusPlus)
3429 Diag(Tok.getLocation(),
3430 getLangOpts().CPlusPlus11 ?
3431 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3433 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3436 // Get the value in the widest-possible width.
3437 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3438 llvm::APInt ResultVal(MaxWidth, 0);
3440 if (Literal.GetIntegerValue(ResultVal)) {
3441 // If this value didn't fit into uintmax_t, error and force to ull.
3442 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3443 << /* Unsigned */ 1;
3444 Ty = Context.UnsignedLongLongTy;
3445 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3446 "long long is not intmax_t?");
3448 // If this value fits into a ULL, try to figure out what else it fits into
3449 // according to the rules of C99 6.4.4.1p5.
3451 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3452 // be an unsigned int.
3453 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3455 // Check from smallest to largest, picking the smallest type we can.
3458 // Microsoft specific integer suffixes are explicitly sized.
3459 if (Literal.MicrosoftInteger) {
3460 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3462 Ty = Context.CharTy;
3464 Width = Literal.MicrosoftInteger;
3465 Ty = Context.getIntTypeForBitwidth(Width,
3466 /*Signed=*/!Literal.isUnsigned);
3470 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3471 // Are int/unsigned possibilities?
3472 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3474 // Does it fit in a unsigned int?
3475 if (ResultVal.isIntN(IntSize)) {
3476 // Does it fit in a signed int?
3477 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3479 else if (AllowUnsigned)
3480 Ty = Context.UnsignedIntTy;
3485 // Are long/unsigned long possibilities?
3486 if (Ty.isNull() && !Literal.isLongLong) {
3487 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3489 // Does it fit in a unsigned long?
3490 if (ResultVal.isIntN(LongSize)) {
3491 // Does it fit in a signed long?
3492 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3493 Ty = Context.LongTy;
3494 else if (AllowUnsigned)
3495 Ty = Context.UnsignedLongTy;
3496 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3498 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3499 const unsigned LongLongSize =
3500 Context.getTargetInfo().getLongLongWidth();
3501 Diag(Tok.getLocation(),
3502 getLangOpts().CPlusPlus
3504 ? diag::warn_old_implicitly_unsigned_long_cxx
3505 : /*C++98 UB*/ diag::
3506 ext_old_implicitly_unsigned_long_cxx
3507 : diag::warn_old_implicitly_unsigned_long)
3508 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3509 : /*will be ill-formed*/ 1);
3510 Ty = Context.UnsignedLongTy;
3516 // Check long long if needed.
3518 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3520 // Does it fit in a unsigned long long?
3521 if (ResultVal.isIntN(LongLongSize)) {
3522 // Does it fit in a signed long long?
3523 // To be compatible with MSVC, hex integer literals ending with the
3524 // LL or i64 suffix are always signed in Microsoft mode.
3525 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3526 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3527 Ty = Context.LongLongTy;
3528 else if (AllowUnsigned)
3529 Ty = Context.UnsignedLongLongTy;
3530 Width = LongLongSize;
3534 // If we still couldn't decide a type, we probably have something that
3535 // does not fit in a signed long long, but has no U suffix.
3537 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3538 Ty = Context.UnsignedLongLongTy;
3539 Width = Context.getTargetInfo().getLongLongWidth();
3542 if (ResultVal.getBitWidth() != Width)
3543 ResultVal = ResultVal.trunc(Width);
3545 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3548 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3549 if (Literal.isImaginary) {
3550 Res = new (Context) ImaginaryLiteral(Res,
3551 Context.getComplexType(Res->getType()));
3553 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3558 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3559 assert(E && "ActOnParenExpr() missing expr");
3560 return new (Context) ParenExpr(L, R, E);
3563 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3565 SourceRange ArgRange) {
3566 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3567 // scalar or vector data type argument..."
3568 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3569 // type (C99 6.2.5p18) or void.
3570 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3571 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3576 assert((T->isVoidType() || !T->isIncompleteType()) &&
3577 "Scalar types should always be complete");
3581 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3583 SourceRange ArgRange,
3584 UnaryExprOrTypeTrait TraitKind) {
3585 // Invalid types must be hard errors for SFINAE in C++.
3586 if (S.LangOpts.CPlusPlus)
3590 if (T->isFunctionType() &&
3591 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3592 // sizeof(function)/alignof(function) is allowed as an extension.
3593 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3594 << TraitKind << ArgRange;
3598 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3599 // this is an error (OpenCL v1.1 s6.3.k)
3600 if (T->isVoidType()) {
3601 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3602 : diag::ext_sizeof_alignof_void_type;
3603 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3610 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3612 SourceRange ArgRange,
3613 UnaryExprOrTypeTrait TraitKind) {
3614 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3615 // runtime doesn't allow it.
3616 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3617 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3618 << T << (TraitKind == UETT_SizeOf)
3626 /// Check whether E is a pointer from a decayed array type (the decayed
3627 /// pointer type is equal to T) and emit a warning if it is.
3628 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3630 // Don't warn if the operation changed the type.
3631 if (T != E->getType())
3634 // Now look for array decays.
3635 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3636 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3639 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3641 << ICE->getSubExpr()->getType();
3644 /// Check the constraints on expression operands to unary type expression
3645 /// and type traits.
3647 /// Completes any types necessary and validates the constraints on the operand
3648 /// expression. The logic mostly mirrors the type-based overload, but may modify
3649 /// the expression as it completes the type for that expression through template
3650 /// instantiation, etc.
3651 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3652 UnaryExprOrTypeTrait ExprKind) {
3653 QualType ExprTy = E->getType();
3654 assert(!ExprTy->isReferenceType());
3656 if (ExprKind == UETT_VecStep)
3657 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3658 E->getSourceRange());
3660 // Whitelist some types as extensions
3661 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3662 E->getSourceRange(), ExprKind))
3665 // 'alignof' applied to an expression only requires the base element type of
3666 // the expression to be complete. 'sizeof' requires the expression's type to
3667 // be complete (and will attempt to complete it if it's an array of unknown
3669 if (ExprKind == UETT_AlignOf) {
3670 if (RequireCompleteType(E->getExprLoc(),
3671 Context.getBaseElementType(E->getType()),
3672 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3673 E->getSourceRange()))
3676 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3677 ExprKind, E->getSourceRange()))
3681 // Completing the expression's type may have changed it.
3682 ExprTy = E->getType();
3683 assert(!ExprTy->isReferenceType());
3685 if (ExprTy->isFunctionType()) {
3686 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3687 << ExprKind << E->getSourceRange();
3691 // The operand for sizeof and alignof is in an unevaluated expression context,
3692 // so side effects could result in unintended consequences.
3693 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3694 !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3695 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3697 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3698 E->getSourceRange(), ExprKind))
3701 if (ExprKind == UETT_SizeOf) {
3702 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3703 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3704 QualType OType = PVD->getOriginalType();
3705 QualType Type = PVD->getType();
3706 if (Type->isPointerType() && OType->isArrayType()) {
3707 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3709 Diag(PVD->getLocation(), diag::note_declared_at);
3714 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3715 // decays into a pointer and returns an unintended result. This is most
3716 // likely a typo for "sizeof(array) op x".
3717 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3718 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3720 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3728 /// Check the constraints on operands to unary expression and type
3731 /// This will complete any types necessary, and validate the various constraints
3732 /// on those operands.
3734 /// The UsualUnaryConversions() function is *not* called by this routine.
3735 /// C99 6.3.2.1p[2-4] all state:
3736 /// Except when it is the operand of the sizeof operator ...
3738 /// C++ [expr.sizeof]p4
3739 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3740 /// standard conversions are not applied to the operand of sizeof.
3742 /// This policy is followed for all of the unary trait expressions.
3743 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3744 SourceLocation OpLoc,
3745 SourceRange ExprRange,
3746 UnaryExprOrTypeTrait ExprKind) {
3747 if (ExprType->isDependentType())
3750 // C++ [expr.sizeof]p2:
3751 // When applied to a reference or a reference type, the result
3752 // is the size of the referenced type.
3753 // C++11 [expr.alignof]p3:
3754 // When alignof is applied to a reference type, the result
3755 // shall be the alignment of the referenced type.
3756 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3757 ExprType = Ref->getPointeeType();
3759 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3760 // When alignof or _Alignof is applied to an array type, the result
3761 // is the alignment of the element type.
3762 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3763 ExprType = Context.getBaseElementType(ExprType);
3765 if (ExprKind == UETT_VecStep)
3766 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3768 // Whitelist some types as extensions
3769 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3773 if (RequireCompleteType(OpLoc, ExprType,
3774 diag::err_sizeof_alignof_incomplete_type,
3775 ExprKind, ExprRange))
3778 if (ExprType->isFunctionType()) {
3779 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3780 << ExprKind << ExprRange;
3784 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3791 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3792 E = E->IgnoreParens();
3794 // Cannot know anything else if the expression is dependent.
3795 if (E->isTypeDependent())
3798 if (E->getObjectKind() == OK_BitField) {
3799 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3800 << 1 << E->getSourceRange();
3804 ValueDecl *D = nullptr;
3805 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3807 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3808 D = ME->getMemberDecl();
3811 // If it's a field, require the containing struct to have a
3812 // complete definition so that we can compute the layout.
3814 // This can happen in C++11 onwards, either by naming the member
3815 // in a way that is not transformed into a member access expression
3816 // (in an unevaluated operand, for instance), or by naming the member
3817 // in a trailing-return-type.
3819 // For the record, since __alignof__ on expressions is a GCC
3820 // extension, GCC seems to permit this but always gives the
3821 // nonsensical answer 0.
3823 // We don't really need the layout here --- we could instead just
3824 // directly check for all the appropriate alignment-lowing
3825 // attributes --- but that would require duplicating a lot of
3826 // logic that just isn't worth duplicating for such a marginal
3828 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3829 // Fast path this check, since we at least know the record has a
3830 // definition if we can find a member of it.
3831 if (!FD->getParent()->isCompleteDefinition()) {
3832 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3833 << E->getSourceRange();
3837 // Otherwise, if it's a field, and the field doesn't have
3838 // reference type, then it must have a complete type (or be a
3839 // flexible array member, which we explicitly want to
3840 // white-list anyway), which makes the following checks trivial.
3841 if (!FD->getType()->isReferenceType())
3845 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3848 bool Sema::CheckVecStepExpr(Expr *E) {
3849 E = E->IgnoreParens();
3851 // Cannot know anything else if the expression is dependent.
3852 if (E->isTypeDependent())
3855 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3858 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3859 CapturingScopeInfo *CSI) {
3860 assert(T->isVariablyModifiedType());
3861 assert(CSI != nullptr);
3863 // We're going to walk down into the type and look for VLA expressions.
3865 const Type *Ty = T.getTypePtr();
3866 switch (Ty->getTypeClass()) {
3867 #define TYPE(Class, Base)
3868 #define ABSTRACT_TYPE(Class, Base)
3869 #define NON_CANONICAL_TYPE(Class, Base)
3870 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3871 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3872 #include "clang/AST/TypeNodes.def"
3875 // These types are never variably-modified.
3879 case Type::ExtVector:
3882 case Type::Elaborated:
3883 case Type::TemplateSpecialization:
3884 case Type::ObjCObject:
3885 case Type::ObjCInterface:
3886 case Type::ObjCObjectPointer:
3887 case Type::ObjCTypeParam:
3889 llvm_unreachable("type class is never variably-modified!");
3890 case Type::Adjusted:
3891 T = cast<AdjustedType>(Ty)->getOriginalType();
3894 T = cast<DecayedType>(Ty)->getPointeeType();
3897 T = cast<PointerType>(Ty)->getPointeeType();
3899 case Type::BlockPointer:
3900 T = cast<BlockPointerType>(Ty)->getPointeeType();
3902 case Type::LValueReference:
3903 case Type::RValueReference:
3904 T = cast<ReferenceType>(Ty)->getPointeeType();
3906 case Type::MemberPointer:
3907 T = cast<MemberPointerType>(Ty)->getPointeeType();
3909 case Type::ConstantArray:
3910 case Type::IncompleteArray:
3911 // Losing element qualification here is fine.
3912 T = cast<ArrayType>(Ty)->getElementType();
3914 case Type::VariableArray: {
3915 // Losing element qualification here is fine.
3916 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3918 // Unknown size indication requires no size computation.
3919 // Otherwise, evaluate and record it.
3920 if (auto Size = VAT->getSizeExpr()) {
3921 if (!CSI->isVLATypeCaptured(VAT)) {
3922 RecordDecl *CapRecord = nullptr;
3923 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3924 CapRecord = LSI->Lambda;
3925 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3926 CapRecord = CRSI->TheRecordDecl;
3929 auto ExprLoc = Size->getExprLoc();
3930 auto SizeType = Context.getSizeType();
3931 // Build the non-static data member.
3933 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3934 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3935 /*BW*/ nullptr, /*Mutable*/ false,
3936 /*InitStyle*/ ICIS_NoInit);
3937 Field->setImplicit(true);
3938 Field->setAccess(AS_private);
3939 Field->setCapturedVLAType(VAT);
3940 CapRecord->addDecl(Field);
3942 CSI->addVLATypeCapture(ExprLoc, SizeType);
3946 T = VAT->getElementType();
3949 case Type::FunctionProto:
3950 case Type::FunctionNoProto:
3951 T = cast<FunctionType>(Ty)->getReturnType();
3955 case Type::UnaryTransform:
3956 case Type::Attributed:
3957 case Type::SubstTemplateTypeParm:
3958 case Type::PackExpansion:
3959 // Keep walking after single level desugaring.
3960 T = T.getSingleStepDesugaredType(Context);
3963 T = cast<TypedefType>(Ty)->desugar();
3965 case Type::Decltype:
3966 T = cast<DecltypeType>(Ty)->desugar();
3969 case Type::DeducedTemplateSpecialization:
3970 T = cast<DeducedType>(Ty)->getDeducedType();
3972 case Type::TypeOfExpr:
3973 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3976 T = cast<AtomicType>(Ty)->getValueType();
3979 } while (!T.isNull() && T->isVariablyModifiedType());
3982 /// Build a sizeof or alignof expression given a type operand.
3984 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3985 SourceLocation OpLoc,
3986 UnaryExprOrTypeTrait ExprKind,
3991 QualType T = TInfo->getType();
3993 if (!T->isDependentType() &&
3994 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3997 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3998 if (auto *TT = T->getAs<TypedefType>()) {
3999 for (auto I = FunctionScopes.rbegin(),
4000 E = std::prev(FunctionScopes.rend());
4002 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4005 DeclContext *DC = nullptr;
4006 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4007 DC = LSI->CallOperator;
4008 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4009 DC = CRSI->TheCapturedDecl;
4010 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4013 if (DC->containsDecl(TT->getDecl()))
4015 captureVariablyModifiedType(Context, T, CSI);
4021 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4022 return new (Context) UnaryExprOrTypeTraitExpr(
4023 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4026 /// Build a sizeof or alignof expression given an expression
4029 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4030 UnaryExprOrTypeTrait ExprKind) {
4031 ExprResult PE = CheckPlaceholderExpr(E);
4037 // Verify that the operand is valid.
4038 bool isInvalid = false;
4039 if (E->isTypeDependent()) {
4040 // Delay type-checking for type-dependent expressions.
4041 } else if (ExprKind == UETT_AlignOf) {
4042 isInvalid = CheckAlignOfExpr(*this, E);
4043 } else if (ExprKind == UETT_VecStep) {
4044 isInvalid = CheckVecStepExpr(E);
4045 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4046 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4048 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4049 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4052 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4058 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4059 PE = TransformToPotentiallyEvaluated(E);
4060 if (PE.isInvalid()) return ExprError();
4064 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4065 return new (Context) UnaryExprOrTypeTraitExpr(
4066 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4069 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4070 /// expr and the same for @c alignof and @c __alignof
4071 /// Note that the ArgRange is invalid if isType is false.
4073 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4074 UnaryExprOrTypeTrait ExprKind, bool IsType,
4075 void *TyOrEx, SourceRange ArgRange) {
4076 // If error parsing type, ignore.
4077 if (!TyOrEx) return ExprError();
4080 TypeSourceInfo *TInfo;
4081 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4082 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4085 Expr *ArgEx = (Expr *)TyOrEx;
4086 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4090 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4092 if (V.get()->isTypeDependent())
4093 return S.Context.DependentTy;
4095 // _Real and _Imag are only l-values for normal l-values.
4096 if (V.get()->getObjectKind() != OK_Ordinary) {
4097 V = S.DefaultLvalueConversion(V.get());
4102 // These operators return the element type of a complex type.
4103 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4104 return CT->getElementType();
4106 // Otherwise they pass through real integer and floating point types here.
4107 if (V.get()->getType()->isArithmeticType())
4108 return V.get()->getType();
4110 // Test for placeholders.
4111 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4112 if (PR.isInvalid()) return QualType();
4113 if (PR.get() != V.get()) {
4115 return CheckRealImagOperand(S, V, Loc, IsReal);
4118 // Reject anything else.
4119 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4120 << (IsReal ? "__real" : "__imag");
4127 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4128 tok::TokenKind Kind, Expr *Input) {
4129 UnaryOperatorKind Opc;
4131 default: llvm_unreachable("Unknown unary op!");
4132 case tok::plusplus: Opc = UO_PostInc; break;
4133 case tok::minusminus: Opc = UO_PostDec; break;
4136 // Since this might is a postfix expression, get rid of ParenListExprs.
4137 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4138 if (Result.isInvalid()) return ExprError();
4139 Input = Result.get();
4141 return BuildUnaryOp(S, OpLoc, Opc, Input);
4144 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4146 /// \return true on error
4147 static bool checkArithmeticOnObjCPointer(Sema &S,
4148 SourceLocation opLoc,
4150 assert(op->getType()->isObjCObjectPointerType());
4151 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4152 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4155 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4156 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4157 << op->getSourceRange();
4161 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4162 auto *BaseNoParens = Base->IgnoreParens();
4163 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4164 return MSProp->getPropertyDecl()->getType()->isArrayType();
4165 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4169 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4170 Expr *idx, SourceLocation rbLoc) {
4171 if (base && !base->getType().isNull() &&
4172 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4173 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4174 /*Length=*/nullptr, rbLoc);
4176 // Since this might be a postfix expression, get rid of ParenListExprs.
4177 if (isa<ParenListExpr>(base)) {
4178 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4179 if (result.isInvalid()) return ExprError();
4180 base = result.get();
4183 // Handle any non-overload placeholder types in the base and index
4184 // expressions. We can't handle overloads here because the other
4185 // operand might be an overloadable type, in which case the overload
4186 // resolution for the operator overload should get the first crack
4188 bool IsMSPropertySubscript = false;
4189 if (base->getType()->isNonOverloadPlaceholderType()) {
4190 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4191 if (!IsMSPropertySubscript) {
4192 ExprResult result = CheckPlaceholderExpr(base);
4193 if (result.isInvalid())
4195 base = result.get();
4198 if (idx->getType()->isNonOverloadPlaceholderType()) {
4199 ExprResult result = CheckPlaceholderExpr(idx);
4200 if (result.isInvalid()) return ExprError();
4204 // Build an unanalyzed expression if either operand is type-dependent.
4205 if (getLangOpts().CPlusPlus &&
4206 (base->isTypeDependent() || idx->isTypeDependent())) {
4207 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4208 VK_LValue, OK_Ordinary, rbLoc);
4211 // MSDN, property (C++)
4212 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4213 // This attribute can also be used in the declaration of an empty array in a
4214 // class or structure definition. For example:
4215 // __declspec(property(get=GetX, put=PutX)) int x[];
4216 // The above statement indicates that x[] can be used with one or more array
4217 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4218 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4219 if (IsMSPropertySubscript) {
4220 // Build MS property subscript expression if base is MS property reference
4221 // or MS property subscript.
4222 return new (Context) MSPropertySubscriptExpr(
4223 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4226 // Use C++ overloaded-operator rules if either operand has record
4227 // type. The spec says to do this if either type is *overloadable*,
4228 // but enum types can't declare subscript operators or conversion
4229 // operators, so there's nothing interesting for overload resolution
4230 // to do if there aren't any record types involved.
4232 // ObjC pointers have their own subscripting logic that is not tied
4233 // to overload resolution and so should not take this path.
4234 if (getLangOpts().CPlusPlus &&
4235 (base->getType()->isRecordType() ||
4236 (!base->getType()->isObjCObjectPointerType() &&
4237 idx->getType()->isRecordType()))) {
4238 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4241 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4244 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4246 SourceLocation ColonLoc, Expr *Length,
4247 SourceLocation RBLoc) {
4248 if (Base->getType()->isPlaceholderType() &&
4249 !Base->getType()->isSpecificPlaceholderType(
4250 BuiltinType::OMPArraySection)) {
4251 ExprResult Result = CheckPlaceholderExpr(Base);
4252 if (Result.isInvalid())
4254 Base = Result.get();
4256 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4257 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4258 if (Result.isInvalid())
4260 Result = DefaultLvalueConversion(Result.get());
4261 if (Result.isInvalid())
4263 LowerBound = Result.get();
4265 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4266 ExprResult Result = CheckPlaceholderExpr(Length);
4267 if (Result.isInvalid())
4269 Result = DefaultLvalueConversion(Result.get());
4270 if (Result.isInvalid())
4272 Length = Result.get();
4275 // Build an unanalyzed expression if either operand is type-dependent.
4276 if (Base->isTypeDependent() ||
4278 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4279 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4280 return new (Context)
4281 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4282 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4285 // Perform default conversions.
4286 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4288 if (OriginalTy->isAnyPointerType()) {
4289 ResultTy = OriginalTy->getPointeeType();
4290 } else if (OriginalTy->isArrayType()) {
4291 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4294 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4295 << Base->getSourceRange());
4299 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4301 if (Res.isInvalid())
4302 return ExprError(Diag(LowerBound->getExprLoc(),
4303 diag::err_omp_typecheck_section_not_integer)
4304 << 0 << LowerBound->getSourceRange());
4305 LowerBound = Res.get();
4307 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4308 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4309 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4310 << 0 << LowerBound->getSourceRange();
4314 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4315 if (Res.isInvalid())
4316 return ExprError(Diag(Length->getExprLoc(),
4317 diag::err_omp_typecheck_section_not_integer)
4318 << 1 << Length->getSourceRange());
4321 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4322 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4323 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4324 << 1 << Length->getSourceRange();
4327 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4328 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4329 // type. Note that functions are not objects, and that (in C99 parlance)
4330 // incomplete types are not object types.
4331 if (ResultTy->isFunctionType()) {
4332 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4333 << ResultTy << Base->getSourceRange();
4337 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4338 diag::err_omp_section_incomplete_type, Base))
4341 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4342 llvm::APSInt LowerBoundValue;
4343 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4344 // OpenMP 4.5, [2.4 Array Sections]
4345 // The array section must be a subset of the original array.
4346 if (LowerBoundValue.isNegative()) {
4347 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4348 << LowerBound->getSourceRange();
4355 llvm::APSInt LengthValue;
4356 if (Length->EvaluateAsInt(LengthValue, Context)) {
4357 // OpenMP 4.5, [2.4 Array Sections]
4358 // The length must evaluate to non-negative integers.
4359 if (LengthValue.isNegative()) {
4360 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4361 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4362 << Length->getSourceRange();
4366 } else if (ColonLoc.isValid() &&
4367 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4368 !OriginalTy->isVariableArrayType()))) {
4369 // OpenMP 4.5, [2.4 Array Sections]
4370 // When the size of the array dimension is not known, the length must be
4371 // specified explicitly.
4372 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4373 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4377 if (!Base->getType()->isSpecificPlaceholderType(
4378 BuiltinType::OMPArraySection)) {
4379 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4380 if (Result.isInvalid())
4382 Base = Result.get();
4384 return new (Context)
4385 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4386 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4390 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4391 Expr *Idx, SourceLocation RLoc) {
4392 Expr *LHSExp = Base;
4395 ExprValueKind VK = VK_LValue;
4396 ExprObjectKind OK = OK_Ordinary;
4398 // Per C++ core issue 1213, the result is an xvalue if either operand is
4399 // a non-lvalue array, and an lvalue otherwise.
4400 if (getLangOpts().CPlusPlus11) {
4401 for (auto *Op : {LHSExp, RHSExp}) {
4402 Op = Op->IgnoreImplicit();
4403 if (Op->getType()->isArrayType() && !Op->isLValue())
4408 // Perform default conversions.
4409 if (!LHSExp->getType()->getAs<VectorType>()) {
4410 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4411 if (Result.isInvalid())
4413 LHSExp = Result.get();
4415 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4416 if (Result.isInvalid())
4418 RHSExp = Result.get();
4420 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4422 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4423 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4424 // in the subscript position. As a result, we need to derive the array base
4425 // and index from the expression types.
4426 Expr *BaseExpr, *IndexExpr;
4427 QualType ResultType;
4428 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4431 ResultType = Context.DependentTy;
4432 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4435 ResultType = PTy->getPointeeType();
4436 } else if (const ObjCObjectPointerType *PTy =
4437 LHSTy->getAs<ObjCObjectPointerType>()) {
4441 // Use custom logic if this should be the pseudo-object subscript
4443 if (!LangOpts.isSubscriptPointerArithmetic())
4444 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4447 ResultType = PTy->getPointeeType();
4448 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4449 // Handle the uncommon case of "123[Ptr]".
4452 ResultType = PTy->getPointeeType();
4453 } else if (const ObjCObjectPointerType *PTy =
4454 RHSTy->getAs<ObjCObjectPointerType>()) {
4455 // Handle the uncommon case of "123[Ptr]".
4458 ResultType = PTy->getPointeeType();
4459 if (!LangOpts.isSubscriptPointerArithmetic()) {
4460 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4461 << ResultType << BaseExpr->getSourceRange();
4464 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4465 BaseExpr = LHSExp; // vectors: V[123]
4467 // We apply C++ DR1213 to vector subscripting too.
4468 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4469 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4470 if (Materialized.isInvalid())
4472 LHSExp = Materialized.get();
4474 VK = LHSExp->getValueKind();
4475 if (VK != VK_RValue)
4476 OK = OK_VectorComponent;
4478 ResultType = VTy->getElementType();
4479 QualType BaseType = BaseExpr->getType();
4480 Qualifiers BaseQuals = BaseType.getQualifiers();
4481 Qualifiers MemberQuals = ResultType.getQualifiers();
4482 Qualifiers Combined = BaseQuals + MemberQuals;
4483 if (Combined != MemberQuals)
4484 ResultType = Context.getQualifiedType(ResultType, Combined);
4485 } else if (LHSTy->isArrayType()) {
4486 // If we see an array that wasn't promoted by
4487 // DefaultFunctionArrayLvalueConversion, it must be an array that
4488 // wasn't promoted because of the C90 rule that doesn't
4489 // allow promoting non-lvalue arrays. Warn, then
4490 // force the promotion here.
4491 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4492 LHSExp->getSourceRange();
4493 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4494 CK_ArrayToPointerDecay).get();
4495 LHSTy = LHSExp->getType();
4499 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4500 } else if (RHSTy->isArrayType()) {
4501 // Same as previous, except for 123[f().a] case
4502 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4503 RHSExp->getSourceRange();
4504 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4505 CK_ArrayToPointerDecay).get();
4506 RHSTy = RHSExp->getType();
4510 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4512 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4513 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4516 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4517 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4518 << IndexExpr->getSourceRange());
4520 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4521 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4522 && !IndexExpr->isTypeDependent())
4523 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4525 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4526 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4527 // type. Note that Functions are not objects, and that (in C99 parlance)
4528 // incomplete types are not object types.
4529 if (ResultType->isFunctionType()) {
4530 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4531 << ResultType << BaseExpr->getSourceRange();
4535 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4536 // GNU extension: subscripting on pointer to void
4537 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4538 << BaseExpr->getSourceRange();
4540 // C forbids expressions of unqualified void type from being l-values.
4541 // See IsCForbiddenLValueType.
4542 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4543 } else if (!ResultType->isDependentType() &&
4544 RequireCompleteType(LLoc, ResultType,
4545 diag::err_subscript_incomplete_type, BaseExpr))
4548 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4549 !ResultType.isCForbiddenLValueType());
4551 return new (Context)
4552 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4555 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4556 ParmVarDecl *Param) {
4557 if (Param->hasUnparsedDefaultArg()) {
4559 diag::err_use_of_default_argument_to_function_declared_later) <<
4560 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4561 Diag(UnparsedDefaultArgLocs[Param],
4562 diag::note_default_argument_declared_here);
4566 if (Param->hasUninstantiatedDefaultArg()) {
4567 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4569 EnterExpressionEvaluationContext EvalContext(
4570 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4572 // Instantiate the expression.
4574 // FIXME: Pass in a correct Pattern argument, otherwise
4575 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4577 // template<typename T>
4579 // static int FooImpl();
4581 // template<typename Tp>
4582 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4583 // // template argument list [[T], [Tp]], should be [[Tp]].
4584 // friend A<Tp> Foo(int a);
4587 // template<typename T>
4588 // A<T> Foo(int a = A<T>::FooImpl());
4589 MultiLevelTemplateArgumentList MutiLevelArgList
4590 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4592 InstantiatingTemplate Inst(*this, CallLoc, Param,
4593 MutiLevelArgList.getInnermost());
4594 if (Inst.isInvalid())
4596 if (Inst.isAlreadyInstantiating()) {
4597 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4598 Param->setInvalidDecl();
4604 // C++ [dcl.fct.default]p5:
4605 // The names in the [default argument] expression are bound, and
4606 // the semantic constraints are checked, at the point where the
4607 // default argument expression appears.
4608 ContextRAII SavedContext(*this, FD);
4609 LocalInstantiationScope Local(*this);
4610 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4611 /*DirectInit*/false);
4613 if (Result.isInvalid())
4616 // Check the expression as an initializer for the parameter.
4617 InitializedEntity Entity
4618 = InitializedEntity::InitializeParameter(Context, Param);
4619 InitializationKind Kind
4620 = InitializationKind::CreateCopy(Param->getLocation(),
4621 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4622 Expr *ResultE = Result.getAs<Expr>();
4624 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4625 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4626 if (Result.isInvalid())
4629 Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4630 Param->getOuterLocStart());
4631 if (Result.isInvalid())
4634 // Remember the instantiated default argument.
4635 Param->setDefaultArg(Result.getAs<Expr>());
4636 if (ASTMutationListener *L = getASTMutationListener()) {
4637 L->DefaultArgumentInstantiated(Param);
4641 // If the default argument expression is not set yet, we are building it now.
4642 if (!Param->hasInit()) {
4643 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4644 Param->setInvalidDecl();
4648 // If the default expression creates temporaries, we need to
4649 // push them to the current stack of expression temporaries so they'll
4650 // be properly destroyed.
4651 // FIXME: We should really be rebuilding the default argument with new
4652 // bound temporaries; see the comment in PR5810.
4653 // We don't need to do that with block decls, though, because
4654 // blocks in default argument expression can never capture anything.
4655 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4656 // Set the "needs cleanups" bit regardless of whether there are
4657 // any explicit objects.
4658 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4660 // Append all the objects to the cleanup list. Right now, this
4661 // should always be a no-op, because blocks in default argument
4662 // expressions should never be able to capture anything.
4663 assert(!Init->getNumObjects() &&
4664 "default argument expression has capturing blocks?");
4667 // We already type-checked the argument, so we know it works.
4668 // Just mark all of the declarations in this potentially-evaluated expression
4669 // as being "referenced".
4670 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4671 /*SkipLocalVariables=*/true);
4675 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4676 FunctionDecl *FD, ParmVarDecl *Param) {
4677 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4679 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4682 Sema::VariadicCallType
4683 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4685 if (Proto && Proto->isVariadic()) {
4686 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4687 return VariadicConstructor;
4688 else if (Fn && Fn->getType()->isBlockPointerType())
4689 return VariadicBlock;
4691 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4692 if (Method->isInstance())
4693 return VariadicMethod;
4694 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4695 return VariadicMethod;
4696 return VariadicFunction;
4698 return VariadicDoesNotApply;
4702 class FunctionCallCCC : public FunctionCallFilterCCC {
4704 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4705 unsigned NumArgs, MemberExpr *ME)
4706 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4707 FunctionName(FuncName) {}
4709 bool ValidateCandidate(const TypoCorrection &candidate) override {
4710 if (!candidate.getCorrectionSpecifier() ||
4711 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4715 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4719 const IdentifierInfo *const FunctionName;
4723 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4724 FunctionDecl *FDecl,
4725 ArrayRef<Expr *> Args) {
4726 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4727 DeclarationName FuncName = FDecl->getDeclName();
4728 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4730 if (TypoCorrection Corrected = S.CorrectTypo(
4731 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4732 S.getScopeForContext(S.CurContext), nullptr,
4733 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4735 Sema::CTK_ErrorRecovery)) {
4736 if (NamedDecl *ND = Corrected.getFoundDecl()) {
4737 if (Corrected.isOverloaded()) {
4738 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4739 OverloadCandidateSet::iterator Best;
4740 for (NamedDecl *CD : Corrected) {
4741 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4742 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4745 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4747 ND = Best->FoundDecl;
4748 Corrected.setCorrectionDecl(ND);
4754 ND = ND->getUnderlyingDecl();
4755 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4759 return TypoCorrection();
4762 /// ConvertArgumentsForCall - Converts the arguments specified in
4763 /// Args/NumArgs to the parameter types of the function FDecl with
4764 /// function prototype Proto. Call is the call expression itself, and
4765 /// Fn is the function expression. For a C++ member function, this
4766 /// routine does not attempt to convert the object argument. Returns
4767 /// true if the call is ill-formed.
4769 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4770 FunctionDecl *FDecl,
4771 const FunctionProtoType *Proto,
4772 ArrayRef<Expr *> Args,
4773 SourceLocation RParenLoc,
4774 bool IsExecConfig) {
4775 // Bail out early if calling a builtin with custom typechecking.
4777 if (unsigned ID = FDecl->getBuiltinID())
4778 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4781 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4782 // assignment, to the types of the corresponding parameter, ...
4783 unsigned NumParams = Proto->getNumParams();
4784 bool Invalid = false;
4785 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4786 unsigned FnKind = Fn->getType()->isBlockPointerType()
4788 : (IsExecConfig ? 3 /* kernel function (exec config) */
4789 : 0 /* function */);
4791 // If too few arguments are available (and we don't have default
4792 // arguments for the remaining parameters), don't make the call.
4793 if (Args.size() < NumParams) {
4794 if (Args.size() < MinArgs) {
4796 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4798 MinArgs == NumParams && !Proto->isVariadic()
4799 ? diag::err_typecheck_call_too_few_args_suggest
4800 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4801 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4802 << static_cast<unsigned>(Args.size())
4803 << TC.getCorrectionRange());
4804 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4806 MinArgs == NumParams && !Proto->isVariadic()
4807 ? diag::err_typecheck_call_too_few_args_one
4808 : diag::err_typecheck_call_too_few_args_at_least_one)
4809 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4811 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4812 ? diag::err_typecheck_call_too_few_args
4813 : diag::err_typecheck_call_too_few_args_at_least)
4814 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4815 << Fn->getSourceRange();
4817 // Emit the location of the prototype.
4818 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4819 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4824 Call->setNumArgs(Context, NumParams);
4827 // If too many are passed and not variadic, error on the extras and drop
4829 if (Args.size() > NumParams) {
4830 if (!Proto->isVariadic()) {
4832 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4834 MinArgs == NumParams && !Proto->isVariadic()
4835 ? diag::err_typecheck_call_too_many_args_suggest
4836 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4837 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4838 << static_cast<unsigned>(Args.size())
4839 << TC.getCorrectionRange());
4840 } else if (NumParams == 1 && FDecl &&
4841 FDecl->getParamDecl(0)->getDeclName())
4842 Diag(Args[NumParams]->getLocStart(),
4843 MinArgs == NumParams
4844 ? diag::err_typecheck_call_too_many_args_one
4845 : diag::err_typecheck_call_too_many_args_at_most_one)
4846 << FnKind << FDecl->getParamDecl(0)
4847 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4848 << SourceRange(Args[NumParams]->getLocStart(),
4849 Args.back()->getLocEnd());
4851 Diag(Args[NumParams]->getLocStart(),
4852 MinArgs == NumParams
4853 ? diag::err_typecheck_call_too_many_args
4854 : diag::err_typecheck_call_too_many_args_at_most)
4855 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4856 << Fn->getSourceRange()
4857 << SourceRange(Args[NumParams]->getLocStart(),
4858 Args.back()->getLocEnd());
4860 // Emit the location of the prototype.
4861 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4862 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4865 // This deletes the extra arguments.
4866 Call->setNumArgs(Context, NumParams);
4870 SmallVector<Expr *, 8> AllArgs;
4871 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4873 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4874 Proto, 0, Args, AllArgs, CallType);
4877 unsigned TotalNumArgs = AllArgs.size();
4878 for (unsigned i = 0; i < TotalNumArgs; ++i)
4879 Call->setArg(i, AllArgs[i]);
4884 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4885 const FunctionProtoType *Proto,
4886 unsigned FirstParam, ArrayRef<Expr *> Args,
4887 SmallVectorImpl<Expr *> &AllArgs,
4888 VariadicCallType CallType, bool AllowExplicit,
4889 bool IsListInitialization) {
4890 unsigned NumParams = Proto->getNumParams();
4891 bool Invalid = false;
4893 // Continue to check argument types (even if we have too few/many args).
4894 for (unsigned i = FirstParam; i < NumParams; i++) {
4895 QualType ProtoArgType = Proto->getParamType(i);
4898 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4899 if (ArgIx < Args.size()) {
4900 Arg = Args[ArgIx++];
4902 if (RequireCompleteType(Arg->getLocStart(),
4904 diag::err_call_incomplete_argument, Arg))
4907 // Strip the unbridged-cast placeholder expression off, if applicable.
4908 bool CFAudited = false;
4909 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4910 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4911 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4912 Arg = stripARCUnbridgedCast(Arg);
4913 else if (getLangOpts().ObjCAutoRefCount &&
4914 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4915 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4918 if (Proto->getExtParameterInfo(i).isNoEscape())
4919 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4920 BE->getBlockDecl()->setDoesNotEscape();
4922 InitializedEntity Entity =
4923 Param ? InitializedEntity::InitializeParameter(Context, Param,
4925 : InitializedEntity::InitializeParameter(
4926 Context, ProtoArgType, Proto->isParamConsumed(i));
4928 // Remember that parameter belongs to a CF audited API.
4930 Entity.setParameterCFAudited();
4932 ExprResult ArgE = PerformCopyInitialization(
4933 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4934 if (ArgE.isInvalid())
4937 Arg = ArgE.getAs<Expr>();
4939 assert(Param && "can't use default arguments without a known callee");
4941 ExprResult ArgExpr =
4942 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4943 if (ArgExpr.isInvalid())
4946 Arg = ArgExpr.getAs<Expr>();
4949 // Check for array bounds violations for each argument to the call. This
4950 // check only triggers warnings when the argument isn't a more complex Expr
4951 // with its own checking, such as a BinaryOperator.
4952 CheckArrayAccess(Arg);
4954 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4955 CheckStaticArrayArgument(CallLoc, Param, Arg);
4957 AllArgs.push_back(Arg);
4960 // If this is a variadic call, handle args passed through "...".
4961 if (CallType != VariadicDoesNotApply) {
4962 // Assume that extern "C" functions with variadic arguments that
4963 // return __unknown_anytype aren't *really* variadic.
4964 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4965 FDecl->isExternC()) {
4966 for (Expr *A : Args.slice(ArgIx)) {
4967 QualType paramType; // ignored
4968 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4969 Invalid |= arg.isInvalid();
4970 AllArgs.push_back(arg.get());
4973 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4975 for (Expr *A : Args.slice(ArgIx)) {
4976 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4977 Invalid |= Arg.isInvalid();
4978 AllArgs.push_back(Arg.get());
4982 // Check for array bounds violations.
4983 for (Expr *A : Args.slice(ArgIx))
4984 CheckArrayAccess(A);
4989 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4990 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4991 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4992 TL = DTL.getOriginalLoc();
4993 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4994 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4995 << ATL.getLocalSourceRange();
4998 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4999 /// array parameter, check that it is non-null, and that if it is formed by
5000 /// array-to-pointer decay, the underlying array is sufficiently large.
5002 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5003 /// array type derivation, then for each call to the function, the value of the
5004 /// corresponding actual argument shall provide access to the first element of
5005 /// an array with at least as many elements as specified by the size expression.
5007 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5009 const Expr *ArgExpr) {
5010 // Static array parameters are not supported in C++.
5011 if (!Param || getLangOpts().CPlusPlus)
5014 QualType OrigTy = Param->getOriginalType();
5016 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5017 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5020 if (ArgExpr->isNullPointerConstant(Context,
5021 Expr::NPC_NeverValueDependent)) {
5022 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5023 DiagnoseCalleeStaticArrayParam(*this, Param);
5027 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5031 const ConstantArrayType *ArgCAT =
5032 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5036 if (ArgCAT->getSize().ult(CAT->getSize())) {
5037 Diag(CallLoc, diag::warn_static_array_too_small)
5038 << ArgExpr->getSourceRange()
5039 << (unsigned) ArgCAT->getSize().getZExtValue()
5040 << (unsigned) CAT->getSize().getZExtValue();
5041 DiagnoseCalleeStaticArrayParam(*this, Param);
5045 /// Given a function expression of unknown-any type, try to rebuild it
5046 /// to have a function type.
5047 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5049 /// Is the given type a placeholder that we need to lower out
5050 /// immediately during argument processing?
5051 static bool isPlaceholderToRemoveAsArg(QualType type) {
5052 // Placeholders are never sugared.
5053 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5054 if (!placeholder) return false;
5056 switch (placeholder->getKind()) {
5057 // Ignore all the non-placeholder types.
5058 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5059 case BuiltinType::Id:
5060 #include "clang/Basic/OpenCLImageTypes.def"
5061 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5062 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5063 #include "clang/AST/BuiltinTypes.def"
5066 // We cannot lower out overload sets; they might validly be resolved
5067 // by the call machinery.
5068 case BuiltinType::Overload:
5071 // Unbridged casts in ARC can be handled in some call positions and
5072 // should be left in place.
5073 case BuiltinType::ARCUnbridgedCast:
5076 // Pseudo-objects should be converted as soon as possible.
5077 case BuiltinType::PseudoObject:
5080 // The debugger mode could theoretically but currently does not try
5081 // to resolve unknown-typed arguments based on known parameter types.
5082 case BuiltinType::UnknownAny:
5085 // These are always invalid as call arguments and should be reported.
5086 case BuiltinType::BoundMember:
5087 case BuiltinType::BuiltinFn:
5088 case BuiltinType::OMPArraySection:
5092 llvm_unreachable("bad builtin type kind");
5095 /// Check an argument list for placeholders that we won't try to
5097 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5098 // Apply this processing to all the arguments at once instead of
5099 // dying at the first failure.
5100 bool hasInvalid = false;
5101 for (size_t i = 0, e = args.size(); i != e; i++) {
5102 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5103 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5104 if (result.isInvalid()) hasInvalid = true;
5105 else args[i] = result.get();
5106 } else if (hasInvalid) {
5107 (void)S.CorrectDelayedTyposInExpr(args[i]);
5113 /// If a builtin function has a pointer argument with no explicit address
5114 /// space, then it should be able to accept a pointer to any address
5115 /// space as input. In order to do this, we need to replace the
5116 /// standard builtin declaration with one that uses the same address space
5119 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5120 /// it does not contain any pointer arguments without
5121 /// an address space qualifer. Otherwise the rewritten
5122 /// FunctionDecl is returned.
5123 /// TODO: Handle pointer return types.
5124 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5125 const FunctionDecl *FDecl,
5126 MultiExprArg ArgExprs) {
5128 QualType DeclType = FDecl->getType();
5129 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5131 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5132 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5135 bool NeedsNewDecl = false;
5137 SmallVector<QualType, 8> OverloadParams;
5139 for (QualType ParamType : FT->param_types()) {
5141 // Convert array arguments to pointer to simplify type lookup.
5143 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5144 if (ArgRes.isInvalid())
5146 Expr *Arg = ArgRes.get();
5147 QualType ArgType = Arg->getType();
5148 if (!ParamType->isPointerType() ||
5149 ParamType.getQualifiers().hasAddressSpace() ||
5150 !ArgType->isPointerType() ||
5151 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5152 OverloadParams.push_back(ParamType);
5156 NeedsNewDecl = true;
5157 LangAS AS = ArgType->getPointeeType().getAddressSpace();
5159 QualType PointeeType = ParamType->getPointeeType();
5160 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5161 OverloadParams.push_back(Context.getPointerType(PointeeType));
5167 FunctionProtoType::ExtProtoInfo EPI;
5168 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5169 OverloadParams, EPI);
5170 DeclContext *Parent = Context.getTranslationUnitDecl();
5171 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5172 FDecl->getLocation(),
5173 FDecl->getLocation(),
5174 FDecl->getIdentifier(),
5178 /*hasPrototype=*/true);
5179 SmallVector<ParmVarDecl*, 16> Params;
5180 FT = cast<FunctionProtoType>(OverloadTy);
5181 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5182 QualType ParamType = FT->getParamType(i);
5184 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5185 SourceLocation(), nullptr, ParamType,
5186 /*TInfo=*/nullptr, SC_None, nullptr);
5187 Parm->setScopeInfo(0, i);
5188 Params.push_back(Parm);
5190 OverloadDecl->setParams(Params);
5191 return OverloadDecl;
5194 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5195 FunctionDecl *Callee,
5196 MultiExprArg ArgExprs) {
5197 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5198 // similar attributes) really don't like it when functions are called with an
5199 // invalid number of args.
5200 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5201 /*PartialOverloading=*/false) &&
5202 !Callee->isVariadic())
5204 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5207 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5208 S.Diag(Fn->getLocStart(),
5209 isa<CXXMethodDecl>(Callee)
5210 ? diag::err_ovl_no_viable_member_function_in_call
5211 : diag::err_ovl_no_viable_function_in_call)
5212 << Callee << Callee->getSourceRange();
5213 S.Diag(Callee->getLocation(),
5214 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5215 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5220 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5221 const UnresolvedMemberExpr *const UME, Sema &S) {
5223 const auto GetFunctionLevelDCIfCXXClass =
5224 [](Sema &S) -> const CXXRecordDecl * {
5225 const DeclContext *const DC = S.getFunctionLevelDeclContext();
5226 if (!DC || !DC->getParent())
5229 // If the call to some member function was made from within a member
5230 // function body 'M' return return 'M's parent.
5231 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5232 return MD->getParent()->getCanonicalDecl();
5233 // else the call was made from within a default member initializer of a
5234 // class, so return the class.
5235 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5236 return RD->getCanonicalDecl();
5239 // If our DeclContext is neither a member function nor a class (in the
5240 // case of a lambda in a default member initializer), we can't have an
5241 // enclosing 'this'.
5243 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5244 if (!CurParentClass)
5247 // The naming class for implicit member functions call is the class in which
5248 // name lookup starts.
5249 const CXXRecordDecl *const NamingClass =
5250 UME->getNamingClass()->getCanonicalDecl();
5251 assert(NamingClass && "Must have naming class even for implicit access");
5253 // If the unresolved member functions were found in a 'naming class' that is
5254 // related (either the same or derived from) to the class that contains the
5255 // member function that itself contained the implicit member access.
5257 return CurParentClass == NamingClass ||
5258 CurParentClass->isDerivedFrom(NamingClass);
5262 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5263 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5268 LambdaScopeInfo *const CurLSI = S.getCurLambda();
5269 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5270 // already been captured, or if this is an implicit member function call (if
5271 // it isn't, an attempt to capture 'this' should already have been made).
5272 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5273 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5276 // Check if the naming class in which the unresolved members were found is
5277 // related (same as or is a base of) to the enclosing class.
5279 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5283 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5284 // If the enclosing function is not dependent, then this lambda is
5285 // capture ready, so if we can capture this, do so.
5286 if (!EnclosingFunctionCtx->isDependentContext()) {
5287 // If the current lambda and all enclosing lambdas can capture 'this' -
5288 // then go ahead and capture 'this' (since our unresolved overload set
5289 // contains at least one non-static member function).
5290 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5291 S.CheckCXXThisCapture(CallLoc);
5292 } else if (S.CurContext->isDependentContext()) {
5293 // ... since this is an implicit member reference, that might potentially
5294 // involve a 'this' capture, mark 'this' for potential capture in
5295 // enclosing lambdas.
5296 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5297 CurLSI->addPotentialThisCapture(CallLoc);
5301 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5302 /// This provides the location of the left/right parens and a list of comma
5304 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5305 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5306 Expr *ExecConfig, bool IsExecConfig) {
5307 // Since this might be a postfix expression, get rid of ParenListExprs.
5308 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5309 if (Result.isInvalid()) return ExprError();
5312 if (checkArgsForPlaceholders(*this, ArgExprs))
5315 if (getLangOpts().CPlusPlus) {
5316 // If this is a pseudo-destructor expression, build the call immediately.
5317 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5318 if (!ArgExprs.empty()) {
5319 // Pseudo-destructor calls should not have any arguments.
5320 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5321 << FixItHint::CreateRemoval(
5322 SourceRange(ArgExprs.front()->getLocStart(),
5323 ArgExprs.back()->getLocEnd()));
5326 return new (Context)
5327 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5329 if (Fn->getType() == Context.PseudoObjectTy) {
5330 ExprResult result = CheckPlaceholderExpr(Fn);
5331 if (result.isInvalid()) return ExprError();
5335 // Determine whether this is a dependent call inside a C++ template,
5336 // in which case we won't do any semantic analysis now.
5337 bool Dependent = false;
5338 if (Fn->isTypeDependent())
5340 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5345 return new (Context) CUDAKernelCallExpr(
5346 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5347 Context.DependentTy, VK_RValue, RParenLoc);
5350 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5351 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5354 return new (Context) CallExpr(
5355 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5359 // Determine whether this is a call to an object (C++ [over.call.object]).
5360 if (Fn->getType()->isRecordType())
5361 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5364 if (Fn->getType() == Context.UnknownAnyTy) {
5365 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5366 if (result.isInvalid()) return ExprError();
5370 if (Fn->getType() == Context.BoundMemberTy) {
5371 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5376 // Check for overloaded calls. This can happen even in C due to extensions.
5377 if (Fn->getType() == Context.OverloadTy) {
5378 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5380 // We aren't supposed to apply this logic if there's an '&' involved.
5381 if (!find.HasFormOfMemberPointer) {
5382 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5383 return new (Context) CallExpr(
5384 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5385 OverloadExpr *ovl = find.Expression;
5386 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5387 return BuildOverloadedCallExpr(
5388 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5389 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5390 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5395 // If we're directly calling a function, get the appropriate declaration.
5396 if (Fn->getType() == Context.UnknownAnyTy) {
5397 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5398 if (result.isInvalid()) return ExprError();
5402 Expr *NakedFn = Fn->IgnoreParens();
5404 bool CallingNDeclIndirectly = false;
5405 NamedDecl *NDecl = nullptr;
5406 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5407 if (UnOp->getOpcode() == UO_AddrOf) {
5408 CallingNDeclIndirectly = true;
5409 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5413 if (isa<DeclRefExpr>(NakedFn)) {
5414 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5416 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5417 if (FDecl && FDecl->getBuiltinID()) {
5418 // Rewrite the function decl for this builtin by replacing parameters
5419 // with no explicit address space with the address space of the arguments
5422 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5424 Fn = DeclRefExpr::Create(
5425 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5426 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5429 } else if (isa<MemberExpr>(NakedFn))
5430 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5432 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5433 if (CallingNDeclIndirectly &&
5434 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5438 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5441 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5444 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5445 ExecConfig, IsExecConfig);
5448 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5450 /// __builtin_astype( value, dst type )
5452 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5453 SourceLocation BuiltinLoc,
5454 SourceLocation RParenLoc) {
5455 ExprValueKind VK = VK_RValue;
5456 ExprObjectKind OK = OK_Ordinary;
5457 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5458 QualType SrcTy = E->getType();
5459 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5460 return ExprError(Diag(BuiltinLoc,
5461 diag::err_invalid_astype_of_different_size)
5464 << E->getSourceRange());
5465 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5468 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5469 /// provided arguments.
5471 /// __builtin_convertvector( value, dst type )
5473 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5474 SourceLocation BuiltinLoc,
5475 SourceLocation RParenLoc) {
5476 TypeSourceInfo *TInfo;
5477 GetTypeFromParser(ParsedDestTy, &TInfo);
5478 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5481 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5482 /// i.e. an expression not of \p OverloadTy. The expression should
5483 /// unary-convert to an expression of function-pointer or
5484 /// block-pointer type.
5486 /// \param NDecl the declaration being called, if available
5488 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5489 SourceLocation LParenLoc,
5490 ArrayRef<Expr *> Args,
5491 SourceLocation RParenLoc,
5492 Expr *Config, bool IsExecConfig) {
5493 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5494 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5496 // Functions with 'interrupt' attribute cannot be called directly.
5497 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5498 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5502 // Interrupt handlers don't save off the VFP regs automatically on ARM,
5503 // so there's some risk when calling out to non-interrupt handler functions
5504 // that the callee might not preserve them. This is easy to diagnose here,
5505 // but can be very challenging to debug.
5506 if (auto *Caller = getCurFunctionDecl())
5507 if (Caller->hasAttr<ARMInterruptAttr>()) {
5508 bool VFP = Context.getTargetInfo().hasFeature("vfp");
5509 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5510 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5513 // Promote the function operand.
5514 // We special-case function promotion here because we only allow promoting
5515 // builtin functions to function pointers in the callee of a call.
5518 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5519 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5520 CK_BuiltinFnToFnPtr).get();
5522 Result = CallExprUnaryConversions(Fn);
5524 if (Result.isInvalid())
5528 // Make the call expr early, before semantic checks. This guarantees cleanup
5529 // of arguments and function on error.
5532 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5533 cast<CallExpr>(Config), Args,
5534 Context.BoolTy, VK_RValue,
5537 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5538 VK_RValue, RParenLoc);
5540 if (!getLangOpts().CPlusPlus) {
5541 // C cannot always handle TypoExpr nodes in builtin calls and direct
5542 // function calls as their argument checking don't necessarily handle
5543 // dependent types properly, so make sure any TypoExprs have been
5545 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5546 if (!Result.isUsable()) return ExprError();
5547 TheCall = dyn_cast<CallExpr>(Result.get());
5548 if (!TheCall) return Result;
5549 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5552 // Bail out early if calling a builtin with custom typechecking.
5553 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5554 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5557 const FunctionType *FuncT;
5558 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5559 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5560 // have type pointer to function".
5561 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5563 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5564 << Fn->getType() << Fn->getSourceRange());
5565 } else if (const BlockPointerType *BPT =
5566 Fn->getType()->getAs<BlockPointerType>()) {
5567 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5569 // Handle calls to expressions of unknown-any type.
5570 if (Fn->getType() == Context.UnknownAnyTy) {
5571 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5572 if (rewrite.isInvalid()) return ExprError();
5574 TheCall->setCallee(Fn);
5578 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5579 << Fn->getType() << Fn->getSourceRange());
5582 if (getLangOpts().CUDA) {
5584 // CUDA: Kernel calls must be to global functions
5585 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5586 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5587 << FDecl << Fn->getSourceRange());
5589 // CUDA: Kernel function must have 'void' return type
5590 if (!FuncT->getReturnType()->isVoidType())
5591 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5592 << Fn->getType() << Fn->getSourceRange());
5594 // CUDA: Calls to global functions must be configured
5595 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5596 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5597 << FDecl << Fn->getSourceRange());
5601 // Check for a valid return type
5602 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5606 // We know the result type of the call, set it.
5607 TheCall->setType(FuncT->getCallResultType(Context));
5608 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5610 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5612 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5616 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5619 // Check if we have too few/too many template arguments, based
5620 // on our knowledge of the function definition.
5621 const FunctionDecl *Def = nullptr;
5622 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5623 Proto = Def->getType()->getAs<FunctionProtoType>();
5624 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5625 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5626 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5629 // If the function we're calling isn't a function prototype, but we have
5630 // a function prototype from a prior declaratiom, use that prototype.
5631 if (!FDecl->hasPrototype())
5632 Proto = FDecl->getType()->getAs<FunctionProtoType>();
5635 // Promote the arguments (C99 6.5.2.2p6).
5636 for (unsigned i = 0, e = Args.size(); i != e; i++) {
5637 Expr *Arg = Args[i];
5639 if (Proto && i < Proto->getNumParams()) {
5640 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5641 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5643 PerformCopyInitialization(Entity, SourceLocation(), Arg);
5644 if (ArgE.isInvalid())
5647 Arg = ArgE.getAs<Expr>();
5650 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5652 if (ArgE.isInvalid())
5655 Arg = ArgE.getAs<Expr>();
5658 if (RequireCompleteType(Arg->getLocStart(),
5660 diag::err_call_incomplete_argument, Arg))
5663 TheCall->setArg(i, Arg);
5667 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5668 if (!Method->isStatic())
5669 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5670 << Fn->getSourceRange());
5672 // Check for sentinels
5674 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5676 // Do special checking on direct calls to functions.
5678 if (CheckFunctionCall(FDecl, TheCall, Proto))
5682 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5684 if (CheckPointerCall(NDecl, TheCall, Proto))
5687 if (CheckOtherCall(TheCall, Proto))
5691 return MaybeBindToTemporary(TheCall);
5695 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5696 SourceLocation RParenLoc, Expr *InitExpr) {
5697 assert(Ty && "ActOnCompoundLiteral(): missing type");
5698 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5700 TypeSourceInfo *TInfo;
5701 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5703 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5705 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5709 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5710 SourceLocation RParenLoc, Expr *LiteralExpr) {
5711 QualType literalType = TInfo->getType();
5713 if (literalType->isArrayType()) {
5714 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5715 diag::err_illegal_decl_array_incomplete_type,
5716 SourceRange(LParenLoc,
5717 LiteralExpr->getSourceRange().getEnd())))
5719 if (literalType->isVariableArrayType())
5720 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5721 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5722 } else if (!literalType->isDependentType() &&
5723 RequireCompleteType(LParenLoc, literalType,
5724 diag::err_typecheck_decl_incomplete_type,
5725 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5728 InitializedEntity Entity
5729 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5730 InitializationKind Kind
5731 = InitializationKind::CreateCStyleCast(LParenLoc,
5732 SourceRange(LParenLoc, RParenLoc),
5734 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5735 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5737 if (Result.isInvalid())
5739 LiteralExpr = Result.get();
5741 bool isFileScope = !CurContext->isFunctionOrMethod();
5743 !LiteralExpr->isTypeDependent() &&
5744 !LiteralExpr->isValueDependent() &&
5745 !literalType->isDependentType()) { // 6.5.2.5p3
5746 if (CheckForConstantInitializer(LiteralExpr, literalType))
5750 // In C, compound literals are l-values for some reason.
5751 // For GCC compatibility, in C++, file-scope array compound literals with
5752 // constant initializers are also l-values, and compound literals are
5753 // otherwise prvalues.
5755 // (GCC also treats C++ list-initialized file-scope array prvalues with
5756 // constant initializers as l-values, but that's non-conforming, so we don't
5757 // follow it there.)
5759 // FIXME: It would be better to handle the lvalue cases as materializing and
5760 // lifetime-extending a temporary object, but our materialized temporaries
5761 // representation only supports lifetime extension from a variable, not "out
5763 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5764 // is bound to the result of applying array-to-pointer decay to the compound
5766 // FIXME: GCC supports compound literals of reference type, which should
5767 // obviously have a value kind derived from the kind of reference involved.
5769 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5773 return MaybeBindToTemporary(
5774 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5775 VK, LiteralExpr, isFileScope));
5779 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5780 SourceLocation RBraceLoc) {
5781 // Immediately handle non-overload placeholders. Overloads can be
5782 // resolved contextually, but everything else here can't.
5783 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5784 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5785 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5787 // Ignore failures; dropping the entire initializer list because
5788 // of one failure would be terrible for indexing/etc.
5789 if (result.isInvalid()) continue;
5791 InitArgList[I] = result.get();
5795 // Semantic analysis for initializers is done by ActOnDeclarator() and
5796 // CheckInitializer() - it requires knowledge of the object being initialized.
5798 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5800 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5804 /// Do an explicit extend of the given block pointer if we're in ARC.
5805 void Sema::maybeExtendBlockObject(ExprResult &E) {
5806 assert(E.get()->getType()->isBlockPointerType());
5807 assert(E.get()->isRValue());
5809 // Only do this in an r-value context.
5810 if (!getLangOpts().ObjCAutoRefCount) return;
5812 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5813 CK_ARCExtendBlockObject, E.get(),
5814 /*base path*/ nullptr, VK_RValue);
5815 Cleanup.setExprNeedsCleanups(true);
5818 /// Prepare a conversion of the given expression to an ObjC object
5820 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5821 QualType type = E.get()->getType();
5822 if (type->isObjCObjectPointerType()) {
5824 } else if (type->isBlockPointerType()) {
5825 maybeExtendBlockObject(E);
5826 return CK_BlockPointerToObjCPointerCast;
5828 assert(type->isPointerType());
5829 return CK_CPointerToObjCPointerCast;
5833 /// Prepares for a scalar cast, performing all the necessary stages
5834 /// except the final cast and returning the kind required.
5835 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5836 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5837 // Also, callers should have filtered out the invalid cases with
5838 // pointers. Everything else should be possible.
5840 QualType SrcTy = Src.get()->getType();
5841 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5844 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5845 case Type::STK_MemberPointer:
5846 llvm_unreachable("member pointer type in C");
5848 case Type::STK_CPointer:
5849 case Type::STK_BlockPointer:
5850 case Type::STK_ObjCObjectPointer:
5851 switch (DestTy->getScalarTypeKind()) {
5852 case Type::STK_CPointer: {
5853 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5854 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5855 if (SrcAS != DestAS)
5856 return CK_AddressSpaceConversion;
5859 case Type::STK_BlockPointer:
5860 return (SrcKind == Type::STK_BlockPointer
5861 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5862 case Type::STK_ObjCObjectPointer:
5863 if (SrcKind == Type::STK_ObjCObjectPointer)
5865 if (SrcKind == Type::STK_CPointer)
5866 return CK_CPointerToObjCPointerCast;
5867 maybeExtendBlockObject(Src);
5868 return CK_BlockPointerToObjCPointerCast;
5869 case Type::STK_Bool:
5870 return CK_PointerToBoolean;
5871 case Type::STK_Integral:
5872 return CK_PointerToIntegral;
5873 case Type::STK_Floating:
5874 case Type::STK_FloatingComplex:
5875 case Type::STK_IntegralComplex:
5876 case Type::STK_MemberPointer:
5877 llvm_unreachable("illegal cast from pointer");
5879 llvm_unreachable("Should have returned before this");
5881 case Type::STK_Bool: // casting from bool is like casting from an integer
5882 case Type::STK_Integral:
5883 switch (DestTy->getScalarTypeKind()) {
5884 case Type::STK_CPointer:
5885 case Type::STK_ObjCObjectPointer:
5886 case Type::STK_BlockPointer:
5887 if (Src.get()->isNullPointerConstant(Context,
5888 Expr::NPC_ValueDependentIsNull))
5889 return CK_NullToPointer;
5890 return CK_IntegralToPointer;
5891 case Type::STK_Bool:
5892 return CK_IntegralToBoolean;
5893 case Type::STK_Integral:
5894 return CK_IntegralCast;
5895 case Type::STK_Floating:
5896 return CK_IntegralToFloating;
5897 case Type::STK_IntegralComplex:
5898 Src = ImpCastExprToType(Src.get(),
5899 DestTy->castAs<ComplexType>()->getElementType(),
5901 return CK_IntegralRealToComplex;
5902 case Type::STK_FloatingComplex:
5903 Src = ImpCastExprToType(Src.get(),
5904 DestTy->castAs<ComplexType>()->getElementType(),
5905 CK_IntegralToFloating);
5906 return CK_FloatingRealToComplex;
5907 case Type::STK_MemberPointer:
5908 llvm_unreachable("member pointer type in C");
5910 llvm_unreachable("Should have returned before this");
5912 case Type::STK_Floating:
5913 switch (DestTy->getScalarTypeKind()) {
5914 case Type::STK_Floating:
5915 return CK_FloatingCast;
5916 case Type::STK_Bool:
5917 return CK_FloatingToBoolean;
5918 case Type::STK_Integral:
5919 return CK_FloatingToIntegral;
5920 case Type::STK_FloatingComplex:
5921 Src = ImpCastExprToType(Src.get(),
5922 DestTy->castAs<ComplexType>()->getElementType(),
5924 return CK_FloatingRealToComplex;
5925 case Type::STK_IntegralComplex:
5926 Src = ImpCastExprToType(Src.get(),
5927 DestTy->castAs<ComplexType>()->getElementType(),
5928 CK_FloatingToIntegral);
5929 return CK_IntegralRealToComplex;
5930 case Type::STK_CPointer:
5931 case Type::STK_ObjCObjectPointer:
5932 case Type::STK_BlockPointer:
5933 llvm_unreachable("valid float->pointer cast?");
5934 case Type::STK_MemberPointer:
5935 llvm_unreachable("member pointer type in C");
5937 llvm_unreachable("Should have returned before this");
5939 case Type::STK_FloatingComplex:
5940 switch (DestTy->getScalarTypeKind()) {
5941 case Type::STK_FloatingComplex:
5942 return CK_FloatingComplexCast;
5943 case Type::STK_IntegralComplex:
5944 return CK_FloatingComplexToIntegralComplex;
5945 case Type::STK_Floating: {
5946 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5947 if (Context.hasSameType(ET, DestTy))
5948 return CK_FloatingComplexToReal;
5949 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5950 return CK_FloatingCast;
5952 case Type::STK_Bool:
5953 return CK_FloatingComplexToBoolean;
5954 case Type::STK_Integral:
5955 Src = ImpCastExprToType(Src.get(),
5956 SrcTy->castAs<ComplexType>()->getElementType(),
5957 CK_FloatingComplexToReal);
5958 return CK_FloatingToIntegral;
5959 case Type::STK_CPointer:
5960 case Type::STK_ObjCObjectPointer:
5961 case Type::STK_BlockPointer:
5962 llvm_unreachable("valid complex float->pointer cast?");
5963 case Type::STK_MemberPointer:
5964 llvm_unreachable("member pointer type in C");
5966 llvm_unreachable("Should have returned before this");
5968 case Type::STK_IntegralComplex:
5969 switch (DestTy->getScalarTypeKind()) {
5970 case Type::STK_FloatingComplex:
5971 return CK_IntegralComplexToFloatingComplex;
5972 case Type::STK_IntegralComplex:
5973 return CK_IntegralComplexCast;
5974 case Type::STK_Integral: {
5975 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5976 if (Context.hasSameType(ET, DestTy))
5977 return CK_IntegralComplexToReal;
5978 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5979 return CK_IntegralCast;
5981 case Type::STK_Bool:
5982 return CK_IntegralComplexToBoolean;
5983 case Type::STK_Floating:
5984 Src = ImpCastExprToType(Src.get(),
5985 SrcTy->castAs<ComplexType>()->getElementType(),
5986 CK_IntegralComplexToReal);
5987 return CK_IntegralToFloating;
5988 case Type::STK_CPointer:
5989 case Type::STK_ObjCObjectPointer:
5990 case Type::STK_BlockPointer:
5991 llvm_unreachable("valid complex int->pointer cast?");
5992 case Type::STK_MemberPointer:
5993 llvm_unreachable("member pointer type in C");
5995 llvm_unreachable("Should have returned before this");
5998 llvm_unreachable("Unhandled scalar cast");
6001 static bool breakDownVectorType(QualType type, uint64_t &len,
6002 QualType &eltType) {
6003 // Vectors are simple.
6004 if (const VectorType *vecType = type->getAs<VectorType>()) {
6005 len = vecType->getNumElements();
6006 eltType = vecType->getElementType();
6007 assert(eltType->isScalarType());
6011 // We allow lax conversion to and from non-vector types, but only if
6012 // they're real types (i.e. non-complex, non-pointer scalar types).
6013 if (!type->isRealType()) return false;
6020 /// Are the two types lax-compatible vector types? That is, given
6021 /// that one of them is a vector, do they have equal storage sizes,
6022 /// where the storage size is the number of elements times the element
6025 /// This will also return false if either of the types is neither a
6026 /// vector nor a real type.
6027 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6028 assert(destTy->isVectorType() || srcTy->isVectorType());
6030 // Disallow lax conversions between scalars and ExtVectors (these
6031 // conversions are allowed for other vector types because common headers
6032 // depend on them). Most scalar OP ExtVector cases are handled by the
6033 // splat path anyway, which does what we want (convert, not bitcast).
6034 // What this rules out for ExtVectors is crazy things like char4*float.
6035 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6036 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6038 uint64_t srcLen, destLen;
6039 QualType srcEltTy, destEltTy;
6040 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6041 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6043 // ASTContext::getTypeSize will return the size rounded up to a
6044 // power of 2, so instead of using that, we need to use the raw
6045 // element size multiplied by the element count.
6046 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6047 uint64_t destEltSize = Context.getTypeSize(destEltTy);
6049 return (srcLen * srcEltSize == destLen * destEltSize);
6052 /// Is this a legal conversion between two types, one of which is
6053 /// known to be a vector type?
6054 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6055 assert(destTy->isVectorType() || srcTy->isVectorType());
6057 if (!Context.getLangOpts().LaxVectorConversions)
6059 return areLaxCompatibleVectorTypes(srcTy, destTy);
6062 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6064 assert(VectorTy->isVectorType() && "Not a vector type!");
6066 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6067 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6068 return Diag(R.getBegin(),
6069 Ty->isVectorType() ?
6070 diag::err_invalid_conversion_between_vectors :
6071 diag::err_invalid_conversion_between_vector_and_integer)
6072 << VectorTy << Ty << R;
6074 return Diag(R.getBegin(),
6075 diag::err_invalid_conversion_between_vector_and_scalar)
6076 << VectorTy << Ty << R;
6082 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6083 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6085 if (DestElemTy == SplattedExpr->getType())
6086 return SplattedExpr;
6088 assert(DestElemTy->isFloatingType() ||
6089 DestElemTy->isIntegralOrEnumerationType());
6092 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6093 // OpenCL requires that we convert `true` boolean expressions to -1, but
6094 // only when splatting vectors.
6095 if (DestElemTy->isFloatingType()) {
6096 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6097 // in two steps: boolean to signed integral, then to floating.
6098 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6099 CK_BooleanToSignedIntegral);
6100 SplattedExpr = CastExprRes.get();
6101 CK = CK_IntegralToFloating;
6103 CK = CK_BooleanToSignedIntegral;
6106 ExprResult CastExprRes = SplattedExpr;
6107 CK = PrepareScalarCast(CastExprRes, DestElemTy);
6108 if (CastExprRes.isInvalid())
6110 SplattedExpr = CastExprRes.get();
6112 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6115 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6116 Expr *CastExpr, CastKind &Kind) {
6117 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6119 QualType SrcTy = CastExpr->getType();
6121 // If SrcTy is a VectorType, the total size must match to explicitly cast to
6122 // an ExtVectorType.
6123 // In OpenCL, casts between vectors of different types are not allowed.
6124 // (See OpenCL 6.2).
6125 if (SrcTy->isVectorType()) {
6126 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6127 (getLangOpts().OpenCL &&
6128 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6129 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6130 << DestTy << SrcTy << R;
6137 // All non-pointer scalars can be cast to ExtVector type. The appropriate
6138 // conversion will take place first from scalar to elt type, and then
6139 // splat from elt type to vector.
6140 if (SrcTy->isPointerType())
6141 return Diag(R.getBegin(),
6142 diag::err_invalid_conversion_between_vector_and_scalar)
6143 << DestTy << SrcTy << R;
6145 Kind = CK_VectorSplat;
6146 return prepareVectorSplat(DestTy, CastExpr);
6150 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6151 Declarator &D, ParsedType &Ty,
6152 SourceLocation RParenLoc, Expr *CastExpr) {
6153 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6154 "ActOnCastExpr(): missing type or expr");
6156 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6157 if (D.isInvalidType())
6160 if (getLangOpts().CPlusPlus) {
6161 // Check that there are no default arguments (C++ only).
6162 CheckExtraCXXDefaultArguments(D);
6164 // Make sure any TypoExprs have been dealt with.
6165 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6166 if (!Res.isUsable())
6168 CastExpr = Res.get();
6171 checkUnusedDeclAttributes(D);
6173 QualType castType = castTInfo->getType();
6174 Ty = CreateParsedType(castType, castTInfo);
6176 bool isVectorLiteral = false;
6178 // Check for an altivec or OpenCL literal,
6179 // i.e. all the elements are integer constants.
6180 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6181 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6182 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6183 && castType->isVectorType() && (PE || PLE)) {
6184 if (PLE && PLE->getNumExprs() == 0) {
6185 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6188 if (PE || PLE->getNumExprs() == 1) {
6189 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6190 if (!E->getType()->isVectorType())
6191 isVectorLiteral = true;
6194 isVectorLiteral = true;
6197 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6198 // then handle it as such.
6199 if (isVectorLiteral)
6200 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6202 // If the Expr being casted is a ParenListExpr, handle it specially.
6203 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6204 // sequence of BinOp comma operators.
6205 if (isa<ParenListExpr>(CastExpr)) {
6206 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6207 if (Result.isInvalid()) return ExprError();
6208 CastExpr = Result.get();
6211 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6212 !getSourceManager().isInSystemMacro(LParenLoc))
6213 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6215 CheckTollFreeBridgeCast(castType, CastExpr);
6217 CheckObjCBridgeRelatedCast(castType, CastExpr);
6219 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6221 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6224 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6225 SourceLocation RParenLoc, Expr *E,
6226 TypeSourceInfo *TInfo) {
6227 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6228 "Expected paren or paren list expression");
6233 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6234 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6235 LiteralLParenLoc = PE->getLParenLoc();
6236 LiteralRParenLoc = PE->getRParenLoc();
6237 exprs = PE->getExprs();
6238 numExprs = PE->getNumExprs();
6239 } else { // isa<ParenExpr> by assertion at function entrance
6240 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6241 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6242 subExpr = cast<ParenExpr>(E)->getSubExpr();
6247 QualType Ty = TInfo->getType();
6248 assert(Ty->isVectorType() && "Expected vector type");
6250 SmallVector<Expr *, 8> initExprs;
6251 const VectorType *VTy = Ty->getAs<VectorType>();
6252 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6254 // '(...)' form of vector initialization in AltiVec: the number of
6255 // initializers must be one or must match the size of the vector.
6256 // If a single value is specified in the initializer then it will be
6257 // replicated to all the components of the vector
6258 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6259 // The number of initializers must be one or must match the size of the
6260 // vector. If a single value is specified in the initializer then it will
6261 // be replicated to all the components of the vector
6262 if (numExprs == 1) {
6263 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6264 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6265 if (Literal.isInvalid())
6267 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6268 PrepareScalarCast(Literal, ElemTy));
6269 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6271 else if (numExprs < numElems) {
6272 Diag(E->getExprLoc(),
6273 diag::err_incorrect_number_of_vector_initializers);
6277 initExprs.append(exprs, exprs + numExprs);
6280 // For OpenCL, when the number of initializers is a single value,
6281 // it will be replicated to all components of the vector.
6282 if (getLangOpts().OpenCL &&
6283 VTy->getVectorKind() == VectorType::GenericVector &&
6285 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6286 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6287 if (Literal.isInvalid())
6289 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6290 PrepareScalarCast(Literal, ElemTy));
6291 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6294 initExprs.append(exprs, exprs + numExprs);
6296 // FIXME: This means that pretty-printing the final AST will produce curly
6297 // braces instead of the original commas.
6298 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6299 initExprs, LiteralRParenLoc);
6301 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6304 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6305 /// the ParenListExpr into a sequence of comma binary operators.
6307 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6308 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6312 ExprResult Result(E->getExpr(0));
6314 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6315 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6318 if (Result.isInvalid()) return ExprError();
6320 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6323 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6326 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6330 /// Emit a specialized diagnostic when one expression is a null pointer
6331 /// constant and the other is not a pointer. Returns true if a diagnostic is
6333 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6334 SourceLocation QuestionLoc) {
6335 Expr *NullExpr = LHSExpr;
6336 Expr *NonPointerExpr = RHSExpr;
6337 Expr::NullPointerConstantKind NullKind =
6338 NullExpr->isNullPointerConstant(Context,
6339 Expr::NPC_ValueDependentIsNotNull);
6341 if (NullKind == Expr::NPCK_NotNull) {
6343 NonPointerExpr = LHSExpr;
6345 NullExpr->isNullPointerConstant(Context,
6346 Expr::NPC_ValueDependentIsNotNull);
6349 if (NullKind == Expr::NPCK_NotNull)
6352 if (NullKind == Expr::NPCK_ZeroExpression)
6355 if (NullKind == Expr::NPCK_ZeroLiteral) {
6356 // In this case, check to make sure that we got here from a "NULL"
6357 // string in the source code.
6358 NullExpr = NullExpr->IgnoreParenImpCasts();
6359 SourceLocation loc = NullExpr->getExprLoc();
6360 if (!findMacroSpelling(loc, "NULL"))
6364 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6365 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6366 << NonPointerExpr->getType() << DiagType
6367 << NonPointerExpr->getSourceRange();
6371 /// Return false if the condition expression is valid, true otherwise.
6372 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6373 QualType CondTy = Cond->getType();
6375 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6376 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6377 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6378 << CondTy << Cond->getSourceRange();
6383 if (CondTy->isScalarType()) return false;
6385 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6386 << CondTy << Cond->getSourceRange();
6390 /// Handle when one or both operands are void type.
6391 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6393 Expr *LHSExpr = LHS.get();
6394 Expr *RHSExpr = RHS.get();
6396 if (!LHSExpr->getType()->isVoidType())
6397 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6398 << RHSExpr->getSourceRange();
6399 if (!RHSExpr->getType()->isVoidType())
6400 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6401 << LHSExpr->getSourceRange();
6402 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6403 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6404 return S.Context.VoidTy;
6407 /// Return false if the NullExpr can be promoted to PointerTy,
6409 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6410 QualType PointerTy) {
6411 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6412 !NullExpr.get()->isNullPointerConstant(S.Context,
6413 Expr::NPC_ValueDependentIsNull))
6416 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6420 /// Checks compatibility between two pointers and return the resulting
6422 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6424 SourceLocation Loc) {
6425 QualType LHSTy = LHS.get()->getType();
6426 QualType RHSTy = RHS.get()->getType();
6428 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6429 // Two identical pointers types are always compatible.
6433 QualType lhptee, rhptee;
6435 // Get the pointee types.
6436 bool IsBlockPointer = false;
6437 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6438 lhptee = LHSBTy->getPointeeType();
6439 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6440 IsBlockPointer = true;
6442 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6443 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6446 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6447 // differently qualified versions of compatible types, the result type is
6448 // a pointer to an appropriately qualified version of the composite
6451 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6452 // clause doesn't make sense for our extensions. E.g. address space 2 should
6453 // be incompatible with address space 3: they may live on different devices or
6455 Qualifiers lhQual = lhptee.getQualifiers();
6456 Qualifiers rhQual = rhptee.getQualifiers();
6458 LangAS ResultAddrSpace = LangAS::Default;
6459 LangAS LAddrSpace = lhQual.getAddressSpace();
6460 LangAS RAddrSpace = rhQual.getAddressSpace();
6461 if (S.getLangOpts().OpenCL) {
6462 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6463 // spaces is disallowed.
6464 if (lhQual.isAddressSpaceSupersetOf(rhQual))
6465 ResultAddrSpace = LAddrSpace;
6466 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6467 ResultAddrSpace = RAddrSpace;
6470 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6471 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6472 << RHS.get()->getSourceRange();
6477 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6478 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6479 lhQual.removeCVRQualifiers();
6480 rhQual.removeCVRQualifiers();
6482 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6483 // (C99 6.7.3) for address spaces. We assume that the check should behave in
6484 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6485 // qual types are compatible iff
6486 // * corresponded types are compatible
6487 // * CVR qualifiers are equal
6488 // * address spaces are equal
6489 // Thus for conditional operator we merge CVR and address space unqualified
6490 // pointees and if there is a composite type we return a pointer to it with
6491 // merged qualifiers.
6492 if (S.getLangOpts().OpenCL) {
6493 LHSCastKind = LAddrSpace == ResultAddrSpace
6495 : CK_AddressSpaceConversion;
6496 RHSCastKind = RAddrSpace == ResultAddrSpace
6498 : CK_AddressSpaceConversion;
6499 lhQual.removeAddressSpace();
6500 rhQual.removeAddressSpace();
6503 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6504 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6506 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6508 if (CompositeTy.isNull()) {
6509 // In this situation, we assume void* type. No especially good
6510 // reason, but this is what gcc does, and we do have to pick
6511 // to get a consistent AST.
6512 QualType incompatTy;
6513 incompatTy = S.Context.getPointerType(
6514 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6515 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6516 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6517 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6518 // for casts between types with incompatible address space qualifiers.
6519 // For the following code the compiler produces casts between global and
6520 // local address spaces of the corresponded innermost pointees:
6521 // local int *global *a;
6522 // global int *global *b;
6523 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6524 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6525 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6526 << RHS.get()->getSourceRange();
6530 // The pointer types are compatible.
6531 // In case of OpenCL ResultTy should have the address space qualifier
6532 // which is a superset of address spaces of both the 2nd and the 3rd
6533 // operands of the conditional operator.
6534 QualType ResultTy = [&, ResultAddrSpace]() {
6535 if (S.getLangOpts().OpenCL) {
6536 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6537 CompositeQuals.setAddressSpace(ResultAddrSpace);
6539 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6540 .withCVRQualifiers(MergedCVRQual);
6542 return CompositeTy.withCVRQualifiers(MergedCVRQual);
6545 ResultTy = S.Context.getBlockPointerType(ResultTy);
6547 ResultTy = S.Context.getPointerType(ResultTy);
6549 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6550 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6554 /// Return the resulting type when the operands are both block pointers.
6555 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6558 SourceLocation Loc) {
6559 QualType LHSTy = LHS.get()->getType();
6560 QualType RHSTy = RHS.get()->getType();
6562 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6563 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6564 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6565 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6566 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6569 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6570 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6571 << RHS.get()->getSourceRange();
6575 // We have 2 block pointer types.
6576 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6579 /// Return the resulting type when the operands are both pointers.
6581 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6583 SourceLocation Loc) {
6584 // get the pointer types
6585 QualType LHSTy = LHS.get()->getType();
6586 QualType RHSTy = RHS.get()->getType();
6588 // get the "pointed to" types
6589 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6590 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6592 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6593 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6594 // Figure out necessary qualifiers (C99 6.5.15p6)
6595 QualType destPointee
6596 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6597 QualType destType = S.Context.getPointerType(destPointee);
6598 // Add qualifiers if necessary.
6599 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6600 // Promote to void*.
6601 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6604 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6605 QualType destPointee
6606 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6607 QualType destType = S.Context.getPointerType(destPointee);
6608 // Add qualifiers if necessary.
6609 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6610 // Promote to void*.
6611 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6615 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6618 /// Return false if the first expression is not an integer and the second
6619 /// expression is not a pointer, true otherwise.
6620 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6621 Expr* PointerExpr, SourceLocation Loc,
6622 bool IsIntFirstExpr) {
6623 if (!PointerExpr->getType()->isPointerType() ||
6624 !Int.get()->getType()->isIntegerType())
6627 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6628 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6630 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6631 << Expr1->getType() << Expr2->getType()
6632 << Expr1->getSourceRange() << Expr2->getSourceRange();
6633 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6634 CK_IntegralToPointer);
6638 /// Simple conversion between integer and floating point types.
6640 /// Used when handling the OpenCL conditional operator where the
6641 /// condition is a vector while the other operands are scalar.
6643 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6644 /// types are either integer or floating type. Between the two
6645 /// operands, the type with the higher rank is defined as the "result
6646 /// type". The other operand needs to be promoted to the same type. No
6647 /// other type promotion is allowed. We cannot use
6648 /// UsualArithmeticConversions() for this purpose, since it always
6649 /// promotes promotable types.
6650 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6652 SourceLocation QuestionLoc) {
6653 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6654 if (LHS.isInvalid())
6656 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6657 if (RHS.isInvalid())
6660 // For conversion purposes, we ignore any qualifiers.
6661 // For example, "const float" and "float" are equivalent.
6663 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6665 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6667 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6668 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6669 << LHSType << LHS.get()->getSourceRange();
6673 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6674 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6675 << RHSType << RHS.get()->getSourceRange();
6679 // If both types are identical, no conversion is needed.
6680 if (LHSType == RHSType)
6683 // Now handle "real" floating types (i.e. float, double, long double).
6684 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6685 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6686 /*IsCompAssign = */ false);
6688 // Finally, we have two differing integer types.
6689 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6690 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6693 /// Convert scalar operands to a vector that matches the
6694 /// condition in length.
6696 /// Used when handling the OpenCL conditional operator where the
6697 /// condition is a vector while the other operands are scalar.
6699 /// We first compute the "result type" for the scalar operands
6700 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6701 /// into a vector of that type where the length matches the condition
6702 /// vector type. s6.11.6 requires that the element types of the result
6703 /// and the condition must have the same number of bits.
6705 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6706 QualType CondTy, SourceLocation QuestionLoc) {
6707 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6708 if (ResTy.isNull()) return QualType();
6710 const VectorType *CV = CondTy->getAs<VectorType>();
6713 // Determine the vector result type
6714 unsigned NumElements = CV->getNumElements();
6715 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6717 // Ensure that all types have the same number of bits
6718 if (S.Context.getTypeSize(CV->getElementType())
6719 != S.Context.getTypeSize(ResTy)) {
6720 // Since VectorTy is created internally, it does not pretty print
6721 // with an OpenCL name. Instead, we just print a description.
6722 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6723 SmallString<64> Str;
6724 llvm::raw_svector_ostream OS(Str);
6725 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6726 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6727 << CondTy << OS.str();
6731 // Convert operands to the vector result type
6732 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6733 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6738 /// Return false if this is a valid OpenCL condition vector
6739 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6740 SourceLocation QuestionLoc) {
6741 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6743 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6745 QualType EleTy = CondTy->getElementType();
6746 if (EleTy->isIntegerType()) return false;
6748 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6749 << Cond->getType() << Cond->getSourceRange();
6753 /// Return false if the vector condition type and the vector
6754 /// result type are compatible.
6756 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6757 /// number of elements, and their element types have the same number
6759 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6760 SourceLocation QuestionLoc) {
6761 const VectorType *CV = CondTy->getAs<VectorType>();
6762 const VectorType *RV = VecResTy->getAs<VectorType>();
6765 if (CV->getNumElements() != RV->getNumElements()) {
6766 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6767 << CondTy << VecResTy;
6771 QualType CVE = CV->getElementType();
6772 QualType RVE = RV->getElementType();
6774 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6775 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6776 << CondTy << VecResTy;
6783 /// Return the resulting type for the conditional operator in
6784 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6785 /// s6.3.i) when the condition is a vector type.
6787 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6788 ExprResult &LHS, ExprResult &RHS,
6789 SourceLocation QuestionLoc) {
6790 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6791 if (Cond.isInvalid())
6793 QualType CondTy = Cond.get()->getType();
6795 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6798 // If either operand is a vector then find the vector type of the
6799 // result as specified in OpenCL v1.1 s6.3.i.
6800 if (LHS.get()->getType()->isVectorType() ||
6801 RHS.get()->getType()->isVectorType()) {
6802 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6803 /*isCompAssign*/false,
6804 /*AllowBothBool*/true,
6805 /*AllowBoolConversions*/false);
6806 if (VecResTy.isNull()) return QualType();
6807 // The result type must match the condition type as specified in
6808 // OpenCL v1.1 s6.11.6.
6809 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6814 // Both operands are scalar.
6815 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6818 /// Return true if the Expr is block type
6819 static bool checkBlockType(Sema &S, const Expr *E) {
6820 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6821 QualType Ty = CE->getCallee()->getType();
6822 if (Ty->isBlockPointerType()) {
6823 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6830 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6831 /// In that case, LHS = cond.
6833 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6834 ExprResult &RHS, ExprValueKind &VK,
6836 SourceLocation QuestionLoc) {
6838 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6839 if (!LHSResult.isUsable()) return QualType();
6842 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6843 if (!RHSResult.isUsable()) return QualType();
6846 // C++ is sufficiently different to merit its own checker.
6847 if (getLangOpts().CPlusPlus)
6848 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6853 // The OpenCL operator with a vector condition is sufficiently
6854 // different to merit its own checker.
6855 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6856 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6858 // First, check the condition.
6859 Cond = UsualUnaryConversions(Cond.get());
6860 if (Cond.isInvalid())
6862 if (checkCondition(*this, Cond.get(), QuestionLoc))
6865 // Now check the two expressions.
6866 if (LHS.get()->getType()->isVectorType() ||
6867 RHS.get()->getType()->isVectorType())
6868 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6869 /*AllowBothBool*/true,
6870 /*AllowBoolConversions*/false);
6872 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6873 if (LHS.isInvalid() || RHS.isInvalid())
6876 QualType LHSTy = LHS.get()->getType();
6877 QualType RHSTy = RHS.get()->getType();
6879 // Diagnose attempts to convert between __float128 and long double where
6880 // such conversions currently can't be handled.
6881 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6883 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6884 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6888 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6889 // selection operator (?:).
6890 if (getLangOpts().OpenCL &&
6891 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6895 // If both operands have arithmetic type, do the usual arithmetic conversions
6896 // to find a common type: C99 6.5.15p3,5.
6897 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6898 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6899 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6904 // If both operands are the same structure or union type, the result is that
6906 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6907 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6908 if (LHSRT->getDecl() == RHSRT->getDecl())
6909 // "If both the operands have structure or union type, the result has
6910 // that type." This implies that CV qualifiers are dropped.
6911 return LHSTy.getUnqualifiedType();
6912 // FIXME: Type of conditional expression must be complete in C mode.
6915 // C99 6.5.15p5: "If both operands have void type, the result has void type."
6916 // The following || allows only one side to be void (a GCC-ism).
6917 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6918 return checkConditionalVoidType(*this, LHS, RHS);
6921 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6922 // the type of the other operand."
6923 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6924 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6926 // All objective-c pointer type analysis is done here.
6927 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6929 if (LHS.isInvalid() || RHS.isInvalid())
6931 if (!compositeType.isNull())
6932 return compositeType;
6935 // Handle block pointer types.
6936 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6937 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6940 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6941 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6942 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6945 // GCC compatibility: soften pointer/integer mismatch. Note that
6946 // null pointers have been filtered out by this point.
6947 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6948 /*isIntFirstExpr=*/true))
6950 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6951 /*isIntFirstExpr=*/false))
6954 // Emit a better diagnostic if one of the expressions is a null pointer
6955 // constant and the other is not a pointer type. In this case, the user most
6956 // likely forgot to take the address of the other expression.
6957 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6960 // Otherwise, the operands are not compatible.
6961 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6962 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6963 << RHS.get()->getSourceRange();
6967 /// FindCompositeObjCPointerType - Helper method to find composite type of
6968 /// two objective-c pointer types of the two input expressions.
6969 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6970 SourceLocation QuestionLoc) {
6971 QualType LHSTy = LHS.get()->getType();
6972 QualType RHSTy = RHS.get()->getType();
6974 // Handle things like Class and struct objc_class*. Here we case the result
6975 // to the pseudo-builtin, because that will be implicitly cast back to the
6976 // redefinition type if an attempt is made to access its fields.
6977 if (LHSTy->isObjCClassType() &&
6978 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6979 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6982 if (RHSTy->isObjCClassType() &&
6983 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6984 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6987 // And the same for struct objc_object* / id
6988 if (LHSTy->isObjCIdType() &&
6989 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6990 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6993 if (RHSTy->isObjCIdType() &&
6994 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6995 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6998 // And the same for struct objc_selector* / SEL
6999 if (Context.isObjCSelType(LHSTy) &&
7000 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7001 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7004 if (Context.isObjCSelType(RHSTy) &&
7005 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7006 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7009 // Check constraints for Objective-C object pointers types.
7010 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7012 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7013 // Two identical object pointer types are always compatible.
7016 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7017 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7018 QualType compositeType = LHSTy;
7020 // If both operands are interfaces and either operand can be
7021 // assigned to the other, use that type as the composite
7022 // type. This allows
7023 // xxx ? (A*) a : (B*) b
7024 // where B is a subclass of A.
7026 // Additionally, as for assignment, if either type is 'id'
7027 // allow silent coercion. Finally, if the types are
7028 // incompatible then make sure to use 'id' as the composite
7029 // type so the result is acceptable for sending messages to.
7031 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7032 // It could return the composite type.
7033 if (!(compositeType =
7034 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7035 // Nothing more to do.
7036 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7037 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7038 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7039 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7040 } else if ((LHSTy->isObjCQualifiedIdType() ||
7041 RHSTy->isObjCQualifiedIdType()) &&
7042 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7043 // Need to handle "id<xx>" explicitly.
7044 // GCC allows qualified id and any Objective-C type to devolve to
7045 // id. Currently localizing to here until clear this should be
7046 // part of ObjCQualifiedIdTypesAreCompatible.
7047 compositeType = Context.getObjCIdType();
7048 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7049 compositeType = Context.getObjCIdType();
7051 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7053 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7054 QualType incompatTy = Context.getObjCIdType();
7055 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7056 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7059 // The object pointer types are compatible.
7060 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7061 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7062 return compositeType;
7064 // Check Objective-C object pointer types and 'void *'
7065 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7066 if (getLangOpts().ObjCAutoRefCount) {
7067 // ARC forbids the implicit conversion of object pointers to 'void *',
7068 // so these types are not compatible.
7069 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7070 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7074 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7075 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7076 QualType destPointee
7077 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7078 QualType destType = Context.getPointerType(destPointee);
7079 // Add qualifiers if necessary.
7080 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7081 // Promote to void*.
7082 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7085 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7086 if (getLangOpts().ObjCAutoRefCount) {
7087 // ARC forbids the implicit conversion of object pointers to 'void *',
7088 // so these types are not compatible.
7089 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7090 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7094 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7095 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7096 QualType destPointee
7097 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7098 QualType destType = Context.getPointerType(destPointee);
7099 // Add qualifiers if necessary.
7100 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7101 // Promote to void*.
7102 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7108 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7109 /// ParenRange in parentheses.
7110 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7111 const PartialDiagnostic &Note,
7112 SourceRange ParenRange) {
7113 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7114 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7116 Self.Diag(Loc, Note)
7117 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7118 << FixItHint::CreateInsertion(EndLoc, ")");
7120 // We can't display the parentheses, so just show the bare note.
7121 Self.Diag(Loc, Note) << ParenRange;
7125 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7126 return BinaryOperator::isAdditiveOp(Opc) ||
7127 BinaryOperator::isMultiplicativeOp(Opc) ||
7128 BinaryOperator::isShiftOp(Opc);
7131 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7132 /// expression, either using a built-in or overloaded operator,
7133 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7135 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7137 // Don't strip parenthesis: we should not warn if E is in parenthesis.
7138 E = E->IgnoreImpCasts();
7139 E = E->IgnoreConversionOperator();
7140 E = E->IgnoreImpCasts();
7141 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7142 E = MTE->GetTemporaryExpr();
7143 E = E->IgnoreImpCasts();
7146 // Built-in binary operator.
7147 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7148 if (IsArithmeticOp(OP->getOpcode())) {
7149 *Opcode = OP->getOpcode();
7150 *RHSExprs = OP->getRHS();
7155 // Overloaded operator.
7156 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7157 if (Call->getNumArgs() != 2)
7160 // Make sure this is really a binary operator that is safe to pass into
7161 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7162 OverloadedOperatorKind OO = Call->getOperator();
7163 if (OO < OO_Plus || OO > OO_Arrow ||
7164 OO == OO_PlusPlus || OO == OO_MinusMinus)
7167 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7168 if (IsArithmeticOp(OpKind)) {
7170 *RHSExprs = Call->getArg(1);
7178 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7179 /// or is a logical expression such as (x==y) which has int type, but is
7180 /// commonly interpreted as boolean.
7181 static bool ExprLooksBoolean(Expr *E) {
7182 E = E->IgnoreParenImpCasts();
7184 if (E->getType()->isBooleanType())
7186 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7187 return OP->isComparisonOp() || OP->isLogicalOp();
7188 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7189 return OP->getOpcode() == UO_LNot;
7190 if (E->getType()->isPointerType())
7192 // FIXME: What about overloaded operator calls returning "unspecified boolean
7193 // type"s (commonly pointer-to-members)?
7198 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7199 /// and binary operator are mixed in a way that suggests the programmer assumed
7200 /// the conditional operator has higher precedence, for example:
7201 /// "int x = a + someBinaryCondition ? 1 : 2".
7202 static void DiagnoseConditionalPrecedence(Sema &Self,
7203 SourceLocation OpLoc,
7207 BinaryOperatorKind CondOpcode;
7210 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7212 if (!ExprLooksBoolean(CondRHS))
7215 // The condition is an arithmetic binary expression, with a right-
7216 // hand side that looks boolean, so warn.
7218 Self.Diag(OpLoc, diag::warn_precedence_conditional)
7219 << Condition->getSourceRange()
7220 << BinaryOperator::getOpcodeStr(CondOpcode);
7222 SuggestParentheses(Self, OpLoc,
7223 Self.PDiag(diag::note_precedence_silence)
7224 << BinaryOperator::getOpcodeStr(CondOpcode),
7225 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7227 SuggestParentheses(Self, OpLoc,
7228 Self.PDiag(diag::note_precedence_conditional_first),
7229 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7232 /// Compute the nullability of a conditional expression.
7233 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7234 QualType LHSTy, QualType RHSTy,
7236 if (!ResTy->isAnyPointerType())
7239 auto GetNullability = [&Ctx](QualType Ty) {
7240 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7243 return NullabilityKind::Unspecified;
7246 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7247 NullabilityKind MergedKind;
7249 // Compute nullability of a binary conditional expression.
7251 if (LHSKind == NullabilityKind::NonNull)
7252 MergedKind = NullabilityKind::NonNull;
7254 MergedKind = RHSKind;
7255 // Compute nullability of a normal conditional expression.
7257 if (LHSKind == NullabilityKind::Nullable ||
7258 RHSKind == NullabilityKind::Nullable)
7259 MergedKind = NullabilityKind::Nullable;
7260 else if (LHSKind == NullabilityKind::NonNull)
7261 MergedKind = RHSKind;
7262 else if (RHSKind == NullabilityKind::NonNull)
7263 MergedKind = LHSKind;
7265 MergedKind = NullabilityKind::Unspecified;
7268 // Return if ResTy already has the correct nullability.
7269 if (GetNullability(ResTy) == MergedKind)
7272 // Strip all nullability from ResTy.
7273 while (ResTy->getNullability(Ctx))
7274 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7276 // Create a new AttributedType with the new nullability kind.
7277 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7278 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7281 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7282 /// in the case of a the GNU conditional expr extension.
7283 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7284 SourceLocation ColonLoc,
7285 Expr *CondExpr, Expr *LHSExpr,
7287 if (!getLangOpts().CPlusPlus) {
7288 // C cannot handle TypoExpr nodes in the condition because it
7289 // doesn't handle dependent types properly, so make sure any TypoExprs have
7290 // been dealt with before checking the operands.
7291 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7292 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7293 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7295 if (!CondResult.isUsable())
7299 if (!LHSResult.isUsable())
7303 if (!RHSResult.isUsable())
7306 CondExpr = CondResult.get();
7307 LHSExpr = LHSResult.get();
7308 RHSExpr = RHSResult.get();
7311 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7312 // was the condition.
7313 OpaqueValueExpr *opaqueValue = nullptr;
7314 Expr *commonExpr = nullptr;
7316 commonExpr = CondExpr;
7317 // Lower out placeholder types first. This is important so that we don't
7318 // try to capture a placeholder. This happens in few cases in C++; such
7319 // as Objective-C++'s dictionary subscripting syntax.
7320 if (commonExpr->hasPlaceholderType()) {
7321 ExprResult result = CheckPlaceholderExpr(commonExpr);
7322 if (!result.isUsable()) return ExprError();
7323 commonExpr = result.get();
7325 // We usually want to apply unary conversions *before* saving, except
7326 // in the special case of a C++ l-value conditional.
7327 if (!(getLangOpts().CPlusPlus
7328 && !commonExpr->isTypeDependent()
7329 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7330 && commonExpr->isGLValue()
7331 && commonExpr->isOrdinaryOrBitFieldObject()
7332 && RHSExpr->isOrdinaryOrBitFieldObject()
7333 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7334 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7335 if (commonRes.isInvalid())
7337 commonExpr = commonRes.get();
7340 // If the common expression is a class or array prvalue, materialize it
7341 // so that we can safely refer to it multiple times.
7342 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7343 commonExpr->getType()->isArrayType())) {
7344 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7345 if (MatExpr.isInvalid())
7347 commonExpr = MatExpr.get();
7350 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7351 commonExpr->getType(),
7352 commonExpr->getValueKind(),
7353 commonExpr->getObjectKind(),
7355 LHSExpr = CondExpr = opaqueValue;
7358 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7359 ExprValueKind VK = VK_RValue;
7360 ExprObjectKind OK = OK_Ordinary;
7361 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7362 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7363 VK, OK, QuestionLoc);
7364 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7368 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7371 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7373 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7377 return new (Context)
7378 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7379 RHS.get(), result, VK, OK);
7381 return new (Context) BinaryConditionalOperator(
7382 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7383 ColonLoc, result, VK, OK);
7386 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7387 // being closely modeled after the C99 spec:-). The odd characteristic of this
7388 // routine is it effectively iqnores the qualifiers on the top level pointee.
7389 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7390 // FIXME: add a couple examples in this comment.
7391 static Sema::AssignConvertType
7392 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7393 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7394 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7396 // get the "pointed to" type (ignoring qualifiers at the top level)
7397 const Type *lhptee, *rhptee;
7398 Qualifiers lhq, rhq;
7399 std::tie(lhptee, lhq) =
7400 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7401 std::tie(rhptee, rhq) =
7402 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7404 Sema::AssignConvertType ConvTy = Sema::Compatible;
7406 // C99 6.5.16.1p1: This following citation is common to constraints
7407 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7408 // qualifiers of the type *pointed to* by the right;
7410 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7411 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7412 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7413 // Ignore lifetime for further calculation.
7414 lhq.removeObjCLifetime();
7415 rhq.removeObjCLifetime();
7418 if (!lhq.compatiblyIncludes(rhq)) {
7419 // Treat address-space mismatches as fatal. TODO: address subspaces
7420 if (!lhq.isAddressSpaceSupersetOf(rhq))
7421 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7423 // It's okay to add or remove GC or lifetime qualifiers when converting to
7425 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7426 .compatiblyIncludes(
7427 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7428 && (lhptee->isVoidType() || rhptee->isVoidType()))
7431 // Treat lifetime mismatches as fatal.
7432 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7433 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7435 // For GCC/MS compatibility, other qualifier mismatches are treated
7436 // as still compatible in C.
7437 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7440 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7441 // incomplete type and the other is a pointer to a qualified or unqualified
7442 // version of void...
7443 if (lhptee->isVoidType()) {
7444 if (rhptee->isIncompleteOrObjectType())
7447 // As an extension, we allow cast to/from void* to function pointer.
7448 assert(rhptee->isFunctionType());
7449 return Sema::FunctionVoidPointer;
7452 if (rhptee->isVoidType()) {
7453 if (lhptee->isIncompleteOrObjectType())
7456 // As an extension, we allow cast to/from void* to function pointer.
7457 assert(lhptee->isFunctionType());
7458 return Sema::FunctionVoidPointer;
7461 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7462 // unqualified versions of compatible types, ...
7463 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7464 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7465 // Check if the pointee types are compatible ignoring the sign.
7466 // We explicitly check for char so that we catch "char" vs
7467 // "unsigned char" on systems where "char" is unsigned.
7468 if (lhptee->isCharType())
7469 ltrans = S.Context.UnsignedCharTy;
7470 else if (lhptee->hasSignedIntegerRepresentation())
7471 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7473 if (rhptee->isCharType())
7474 rtrans = S.Context.UnsignedCharTy;
7475 else if (rhptee->hasSignedIntegerRepresentation())
7476 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7478 if (ltrans == rtrans) {
7479 // Types are compatible ignoring the sign. Qualifier incompatibility
7480 // takes priority over sign incompatibility because the sign
7481 // warning can be disabled.
7482 if (ConvTy != Sema::Compatible)
7485 return Sema::IncompatiblePointerSign;
7488 // If we are a multi-level pointer, it's possible that our issue is simply
7489 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7490 // the eventual target type is the same and the pointers have the same
7491 // level of indirection, this must be the issue.
7492 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7494 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7495 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7496 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7498 if (lhptee == rhptee)
7499 return Sema::IncompatibleNestedPointerQualifiers;
7502 // General pointer incompatibility takes priority over qualifiers.
7503 return Sema::IncompatiblePointer;
7505 if (!S.getLangOpts().CPlusPlus &&
7506 S.IsFunctionConversion(ltrans, rtrans, ltrans))
7507 return Sema::IncompatiblePointer;
7511 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7512 /// block pointer types are compatible or whether a block and normal pointer
7513 /// are compatible. It is more restrict than comparing two function pointer
7515 static Sema::AssignConvertType
7516 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7518 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7519 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7521 QualType lhptee, rhptee;
7523 // get the "pointed to" type (ignoring qualifiers at the top level)
7524 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7525 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7527 // In C++, the types have to match exactly.
7528 if (S.getLangOpts().CPlusPlus)
7529 return Sema::IncompatibleBlockPointer;
7531 Sema::AssignConvertType ConvTy = Sema::Compatible;
7533 // For blocks we enforce that qualifiers are identical.
7534 Qualifiers LQuals = lhptee.getLocalQualifiers();
7535 Qualifiers RQuals = rhptee.getLocalQualifiers();
7536 if (S.getLangOpts().OpenCL) {
7537 LQuals.removeAddressSpace();
7538 RQuals.removeAddressSpace();
7540 if (LQuals != RQuals)
7541 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7543 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7545 // The current behavior is similar to C++ lambdas. A block might be
7546 // assigned to a variable iff its return type and parameters are compatible
7547 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7548 // an assignment. Presumably it should behave in way that a function pointer
7549 // assignment does in C, so for each parameter and return type:
7550 // * CVR and address space of LHS should be a superset of CVR and address
7552 // * unqualified types should be compatible.
7553 if (S.getLangOpts().OpenCL) {
7554 if (!S.Context.typesAreBlockPointerCompatible(
7555 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7556 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7557 return Sema::IncompatibleBlockPointer;
7558 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7559 return Sema::IncompatibleBlockPointer;
7564 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7565 /// for assignment compatibility.
7566 static Sema::AssignConvertType
7567 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7569 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7570 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7572 if (LHSType->isObjCBuiltinType()) {
7573 // Class is not compatible with ObjC object pointers.
7574 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7575 !RHSType->isObjCQualifiedClassType())
7576 return Sema::IncompatiblePointer;
7577 return Sema::Compatible;
7579 if (RHSType->isObjCBuiltinType()) {
7580 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7581 !LHSType->isObjCQualifiedClassType())
7582 return Sema::IncompatiblePointer;
7583 return Sema::Compatible;
7585 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7586 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7588 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7589 // make an exception for id<P>
7590 !LHSType->isObjCQualifiedIdType())
7591 return Sema::CompatiblePointerDiscardsQualifiers;
7593 if (S.Context.typesAreCompatible(LHSType, RHSType))
7594 return Sema::Compatible;
7595 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7596 return Sema::IncompatibleObjCQualifiedId;
7597 return Sema::IncompatiblePointer;
7600 Sema::AssignConvertType
7601 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7602 QualType LHSType, QualType RHSType) {
7603 // Fake up an opaque expression. We don't actually care about what
7604 // cast operations are required, so if CheckAssignmentConstraints
7605 // adds casts to this they'll be wasted, but fortunately that doesn't
7606 // usually happen on valid code.
7607 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7608 ExprResult RHSPtr = &RHSExpr;
7611 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7614 /// This helper function returns true if QT is a vector type that has element
7615 /// type ElementType.
7616 static bool isVector(QualType QT, QualType ElementType) {
7617 if (const VectorType *VT = QT->getAs<VectorType>())
7618 return VT->getElementType() == ElementType;
7622 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7623 /// has code to accommodate several GCC extensions when type checking
7624 /// pointers. Here are some objectionable examples that GCC considers warnings:
7628 /// struct foo *pfoo;
7630 /// pint = pshort; // warning: assignment from incompatible pointer type
7631 /// a = pint; // warning: assignment makes integer from pointer without a cast
7632 /// pint = a; // warning: assignment makes pointer from integer without a cast
7633 /// pint = pfoo; // warning: assignment from incompatible pointer type
7635 /// As a result, the code for dealing with pointers is more complex than the
7636 /// C99 spec dictates.
7638 /// Sets 'Kind' for any result kind except Incompatible.
7639 Sema::AssignConvertType
7640 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7641 CastKind &Kind, bool ConvertRHS) {
7642 QualType RHSType = RHS.get()->getType();
7643 QualType OrigLHSType = LHSType;
7645 // Get canonical types. We're not formatting these types, just comparing
7647 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7648 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7650 // Common case: no conversion required.
7651 if (LHSType == RHSType) {
7656 // If we have an atomic type, try a non-atomic assignment, then just add an
7657 // atomic qualification step.
7658 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7659 Sema::AssignConvertType result =
7660 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7661 if (result != Compatible)
7663 if (Kind != CK_NoOp && ConvertRHS)
7664 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7665 Kind = CK_NonAtomicToAtomic;
7669 // If the left-hand side is a reference type, then we are in a
7670 // (rare!) case where we've allowed the use of references in C,
7671 // e.g., as a parameter type in a built-in function. In this case,
7672 // just make sure that the type referenced is compatible with the
7673 // right-hand side type. The caller is responsible for adjusting
7674 // LHSType so that the resulting expression does not have reference
7676 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7677 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7678 Kind = CK_LValueBitCast;
7681 return Incompatible;
7684 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7685 // to the same ExtVector type.
7686 if (LHSType->isExtVectorType()) {
7687 if (RHSType->isExtVectorType())
7688 return Incompatible;
7689 if (RHSType->isArithmeticType()) {
7690 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7692 RHS = prepareVectorSplat(LHSType, RHS.get());
7693 Kind = CK_VectorSplat;
7698 // Conversions to or from vector type.
7699 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7700 if (LHSType->isVectorType() && RHSType->isVectorType()) {
7701 // Allow assignments of an AltiVec vector type to an equivalent GCC
7702 // vector type and vice versa
7703 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7708 // If we are allowing lax vector conversions, and LHS and RHS are both
7709 // vectors, the total size only needs to be the same. This is a bitcast;
7710 // no bits are changed but the result type is different.
7711 if (isLaxVectorConversion(RHSType, LHSType)) {
7713 return IncompatibleVectors;
7717 // When the RHS comes from another lax conversion (e.g. binops between
7718 // scalars and vectors) the result is canonicalized as a vector. When the
7719 // LHS is also a vector, the lax is allowed by the condition above. Handle
7720 // the case where LHS is a scalar.
7721 if (LHSType->isScalarType()) {
7722 const VectorType *VecType = RHSType->getAs<VectorType>();
7723 if (VecType && VecType->getNumElements() == 1 &&
7724 isLaxVectorConversion(RHSType, LHSType)) {
7725 ExprResult *VecExpr = &RHS;
7726 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7732 return Incompatible;
7735 // Diagnose attempts to convert between __float128 and long double where
7736 // such conversions currently can't be handled.
7737 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7738 return Incompatible;
7740 // Disallow assigning a _Complex to a real type in C++ mode since it simply
7741 // discards the imaginary part.
7742 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7743 !LHSType->getAs<ComplexType>())
7744 return Incompatible;
7746 // Arithmetic conversions.
7747 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7748 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7750 Kind = PrepareScalarCast(RHS, LHSType);
7754 // Conversions to normal pointers.
7755 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7757 if (isa<PointerType>(RHSType)) {
7758 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7759 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7760 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7761 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7765 if (RHSType->isIntegerType()) {
7766 Kind = CK_IntegralToPointer; // FIXME: null?
7767 return IntToPointer;
7770 // C pointers are not compatible with ObjC object pointers,
7771 // with two exceptions:
7772 if (isa<ObjCObjectPointerType>(RHSType)) {
7773 // - conversions to void*
7774 if (LHSPointer->getPointeeType()->isVoidType()) {
7779 // - conversions from 'Class' to the redefinition type
7780 if (RHSType->isObjCClassType() &&
7781 Context.hasSameType(LHSType,
7782 Context.getObjCClassRedefinitionType())) {
7788 return IncompatiblePointer;
7792 if (RHSType->getAs<BlockPointerType>()) {
7793 if (LHSPointer->getPointeeType()->isVoidType()) {
7794 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7795 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7799 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7804 return Incompatible;
7807 // Conversions to block pointers.
7808 if (isa<BlockPointerType>(LHSType)) {
7810 if (RHSType->isBlockPointerType()) {
7811 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7814 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7817 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7818 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7821 // int or null -> T^
7822 if (RHSType->isIntegerType()) {
7823 Kind = CK_IntegralToPointer; // FIXME: null
7824 return IntToBlockPointer;
7828 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7829 Kind = CK_AnyPointerToBlockPointerCast;
7834 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7835 if (RHSPT->getPointeeType()->isVoidType()) {
7836 Kind = CK_AnyPointerToBlockPointerCast;
7840 return Incompatible;
7843 // Conversions to Objective-C pointers.
7844 if (isa<ObjCObjectPointerType>(LHSType)) {
7846 if (RHSType->isObjCObjectPointerType()) {
7848 Sema::AssignConvertType result =
7849 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7850 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7851 result == Compatible &&
7852 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7853 result = IncompatibleObjCWeakRef;
7857 // int or null -> A*
7858 if (RHSType->isIntegerType()) {
7859 Kind = CK_IntegralToPointer; // FIXME: null
7860 return IntToPointer;
7863 // In general, C pointers are not compatible with ObjC object pointers,
7864 // with two exceptions:
7865 if (isa<PointerType>(RHSType)) {
7866 Kind = CK_CPointerToObjCPointerCast;
7868 // - conversions from 'void*'
7869 if (RHSType->isVoidPointerType()) {
7873 // - conversions to 'Class' from its redefinition type
7874 if (LHSType->isObjCClassType() &&
7875 Context.hasSameType(RHSType,
7876 Context.getObjCClassRedefinitionType())) {
7880 return IncompatiblePointer;
7883 // Only under strict condition T^ is compatible with an Objective-C pointer.
7884 if (RHSType->isBlockPointerType() &&
7885 LHSType->isBlockCompatibleObjCPointerType(Context)) {
7887 maybeExtendBlockObject(RHS);
7888 Kind = CK_BlockPointerToObjCPointerCast;
7892 return Incompatible;
7895 // Conversions from pointers that are not covered by the above.
7896 if (isa<PointerType>(RHSType)) {
7898 if (LHSType == Context.BoolTy) {
7899 Kind = CK_PointerToBoolean;
7904 if (LHSType->isIntegerType()) {
7905 Kind = CK_PointerToIntegral;
7906 return PointerToInt;
7909 return Incompatible;
7912 // Conversions from Objective-C pointers that are not covered by the above.
7913 if (isa<ObjCObjectPointerType>(RHSType)) {
7915 if (LHSType == Context.BoolTy) {
7916 Kind = CK_PointerToBoolean;
7921 if (LHSType->isIntegerType()) {
7922 Kind = CK_PointerToIntegral;
7923 return PointerToInt;
7926 return Incompatible;
7929 // struct A -> struct B
7930 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7931 if (Context.typesAreCompatible(LHSType, RHSType)) {
7937 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7938 Kind = CK_IntToOCLSampler;
7942 return Incompatible;
7945 /// Constructs a transparent union from an expression that is
7946 /// used to initialize the transparent union.
7947 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7948 ExprResult &EResult, QualType UnionType,
7950 // Build an initializer list that designates the appropriate member
7951 // of the transparent union.
7952 Expr *E = EResult.get();
7953 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7954 E, SourceLocation());
7955 Initializer->setType(UnionType);
7956 Initializer->setInitializedFieldInUnion(Field);
7958 // Build a compound literal constructing a value of the transparent
7959 // union type from this initializer list.
7960 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7961 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7962 VK_RValue, Initializer, false);
7965 Sema::AssignConvertType
7966 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7968 QualType RHSType = RHS.get()->getType();
7970 // If the ArgType is a Union type, we want to handle a potential
7971 // transparent_union GCC extension.
7972 const RecordType *UT = ArgType->getAsUnionType();
7973 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7974 return Incompatible;
7976 // The field to initialize within the transparent union.
7977 RecordDecl *UD = UT->getDecl();
7978 FieldDecl *InitField = nullptr;
7979 // It's compatible if the expression matches any of the fields.
7980 for (auto *it : UD->fields()) {
7981 if (it->getType()->isPointerType()) {
7982 // If the transparent union contains a pointer type, we allow:
7984 // 2) null pointer constant
7985 if (RHSType->isPointerType())
7986 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7987 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7992 if (RHS.get()->isNullPointerConstant(Context,
7993 Expr::NPC_ValueDependentIsNull)) {
7994 RHS = ImpCastExprToType(RHS.get(), it->getType(),
8002 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8004 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8011 return Incompatible;
8013 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8017 Sema::AssignConvertType
8018 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8020 bool DiagnoseCFAudited,
8022 // We need to be able to tell the caller whether we diagnosed a problem, if
8023 // they ask us to issue diagnostics.
8024 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8026 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8027 // we can't avoid *all* modifications at the moment, so we need some somewhere
8028 // to put the updated value.
8029 ExprResult LocalRHS = CallerRHS;
8030 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8032 if (getLangOpts().CPlusPlus) {
8033 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8034 // C++ 5.17p3: If the left operand is not of class type, the
8035 // expression is implicitly converted (C++ 4) to the
8036 // cv-unqualified type of the left operand.
8037 QualType RHSType = RHS.get()->getType();
8039 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8042 ImplicitConversionSequence ICS =
8043 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8044 /*SuppressUserConversions=*/false,
8045 /*AllowExplicit=*/false,
8046 /*InOverloadResolution=*/false,
8048 /*AllowObjCWritebackConversion=*/false);
8049 if (ICS.isFailure())
8050 return Incompatible;
8051 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8054 if (RHS.isInvalid())
8055 return Incompatible;
8056 Sema::AssignConvertType result = Compatible;
8057 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8058 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8059 result = IncompatibleObjCWeakRef;
8063 // FIXME: Currently, we fall through and treat C++ classes like C
8065 // FIXME: We also fall through for atomics; not sure what should
8066 // happen there, though.
8067 } else if (RHS.get()->getType() == Context.OverloadTy) {
8068 // As a set of extensions to C, we support overloading on functions. These
8069 // functions need to be resolved here.
8071 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8072 RHS.get(), LHSType, /*Complain=*/false, DAP))
8073 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8075 return Incompatible;
8078 // C99 6.5.16.1p1: the left operand is a pointer and the right is
8079 // a null pointer constant.
8080 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8081 LHSType->isBlockPointerType()) &&
8082 RHS.get()->isNullPointerConstant(Context,
8083 Expr::NPC_ValueDependentIsNull)) {
8084 if (Diagnose || ConvertRHS) {
8087 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8088 /*IgnoreBaseAccess=*/false, Diagnose);
8090 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8095 // This check seems unnatural, however it is necessary to ensure the proper
8096 // conversion of functions/arrays. If the conversion were done for all
8097 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8098 // expressions that suppress this implicit conversion (&, sizeof).
8100 // Suppress this for references: C++ 8.5.3p5.
8101 if (!LHSType->isReferenceType()) {
8102 // FIXME: We potentially allocate here even if ConvertRHS is false.
8103 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8104 if (RHS.isInvalid())
8105 return Incompatible;
8108 Expr *PRE = RHS.get()->IgnoreParenCasts();
8109 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8110 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8111 if (PDecl && !PDecl->hasDefinition()) {
8112 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8113 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8118 Sema::AssignConvertType result =
8119 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8121 // C99 6.5.16.1p2: The value of the right operand is converted to the
8122 // type of the assignment expression.
8123 // CheckAssignmentConstraints allows the left-hand side to be a reference,
8124 // so that we can use references in built-in functions even in C.
8125 // The getNonReferenceType() call makes sure that the resulting expression
8126 // does not have reference type.
8127 if (result != Incompatible && RHS.get()->getType() != LHSType) {
8128 QualType Ty = LHSType.getNonLValueExprType(Context);
8129 Expr *E = RHS.get();
8131 // Check for various Objective-C errors. If we are not reporting
8132 // diagnostics and just checking for errors, e.g., during overload
8133 // resolution, return Incompatible to indicate the failure.
8134 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8135 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8136 Diagnose, DiagnoseCFAudited) != ACR_okay) {
8138 return Incompatible;
8140 if (getLangOpts().ObjC1 &&
8141 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8142 E->getType(), E, Diagnose) ||
8143 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8145 return Incompatible;
8146 // Replace the expression with a corrected version and continue so we
8147 // can find further errors.
8153 RHS = ImpCastExprToType(E, Ty, Kind);
8159 /// The original operand to an operator, prior to the application of the usual
8160 /// arithmetic conversions and converting the arguments of a builtin operator
8162 struct OriginalOperand {
8163 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8164 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8165 Op = MTE->GetTemporaryExpr();
8166 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8167 Op = BTE->getSubExpr();
8168 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8169 Orig = ICE->getSubExprAsWritten();
8170 Conversion = ICE->getConversionFunction();
8174 QualType getType() const { return Orig->getType(); }
8177 NamedDecl *Conversion;
8181 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8183 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8185 Diag(Loc, diag::err_typecheck_invalid_operands)
8186 << OrigLHS.getType() << OrigRHS.getType()
8187 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8189 // If a user-defined conversion was applied to either of the operands prior
8190 // to applying the built-in operator rules, tell the user about it.
8191 if (OrigLHS.Conversion) {
8192 Diag(OrigLHS.Conversion->getLocation(),
8193 diag::note_typecheck_invalid_operands_converted)
8194 << 0 << LHS.get()->getType();
8196 if (OrigRHS.Conversion) {
8197 Diag(OrigRHS.Conversion->getLocation(),
8198 diag::note_typecheck_invalid_operands_converted)
8199 << 1 << RHS.get()->getType();
8205 // Diagnose cases where a scalar was implicitly converted to a vector and
8206 // diagnose the underlying types. Otherwise, diagnose the error
8207 // as invalid vector logical operands for non-C++ cases.
8208 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8210 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8211 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8213 bool LHSNatVec = LHSType->isVectorType();
8214 bool RHSNatVec = RHSType->isVectorType();
8216 if (!(LHSNatVec && RHSNatVec)) {
8217 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8218 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8219 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8220 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8221 << Vector->getSourceRange();
8225 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8226 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8227 << RHS.get()->getSourceRange();
8232 /// Try to convert a value of non-vector type to a vector type by converting
8233 /// the type to the element type of the vector and then performing a splat.
8234 /// If the language is OpenCL, we only use conversions that promote scalar
8235 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8238 /// OpenCL V2.0 6.2.6.p2:
8239 /// An error shall occur if any scalar operand type has greater rank
8240 /// than the type of the vector element.
8242 /// \param scalar - if non-null, actually perform the conversions
8243 /// \return true if the operation fails (but without diagnosing the failure)
8244 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8246 QualType vectorEltTy,
8249 // The conversion to apply to the scalar before splatting it,
8251 CastKind scalarCast = CK_NoOp;
8253 if (vectorEltTy->isIntegralType(S.Context)) {
8254 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8255 (scalarTy->isIntegerType() &&
8256 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8257 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8260 if (!scalarTy->isIntegralType(S.Context))
8262 scalarCast = CK_IntegralCast;
8263 } else if (vectorEltTy->isRealFloatingType()) {
8264 if (scalarTy->isRealFloatingType()) {
8265 if (S.getLangOpts().OpenCL &&
8266 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8267 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8270 scalarCast = CK_FloatingCast;
8272 else if (scalarTy->isIntegralType(S.Context))
8273 scalarCast = CK_IntegralToFloating;
8280 // Adjust scalar if desired.
8282 if (scalarCast != CK_NoOp)
8283 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8284 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8289 /// Convert vector E to a vector with the same number of elements but different
8291 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8292 const auto *VecTy = E->getType()->getAs<VectorType>();
8293 assert(VecTy && "Expression E must be a vector");
8294 QualType NewVecTy = S.Context.getVectorType(ElementType,
8295 VecTy->getNumElements(),
8296 VecTy->getVectorKind());
8298 // Look through the implicit cast. Return the subexpression if its type is
8300 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8301 if (ICE->getSubExpr()->getType() == NewVecTy)
8302 return ICE->getSubExpr();
8304 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8305 return S.ImpCastExprToType(E, NewVecTy, Cast);
8308 /// Test if a (constant) integer Int can be casted to another integer type
8309 /// IntTy without losing precision.
8310 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8311 QualType OtherIntTy) {
8312 QualType IntTy = Int->get()->getType().getUnqualifiedType();
8314 // Reject cases where the value of the Int is unknown as that would
8315 // possibly cause truncation, but accept cases where the scalar can be
8316 // demoted without loss of precision.
8317 llvm::APSInt Result;
8318 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8319 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8320 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8321 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8324 // If the scalar is constant and is of a higher order and has more active
8325 // bits that the vector element type, reject it.
8326 unsigned NumBits = IntSigned
8327 ? (Result.isNegative() ? Result.getMinSignedBits()
8328 : Result.getActiveBits())
8329 : Result.getActiveBits();
8330 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8333 // If the signedness of the scalar type and the vector element type
8334 // differs and the number of bits is greater than that of the vector
8335 // element reject it.
8336 return (IntSigned != OtherIntSigned &&
8337 NumBits > S.Context.getIntWidth(OtherIntTy));
8340 // Reject cases where the value of the scalar is not constant and it's
8341 // order is greater than that of the vector element type.
8345 /// Test if a (constant) integer Int can be casted to floating point type
8346 /// FloatTy without losing precision.
8347 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8349 QualType IntTy = Int->get()->getType().getUnqualifiedType();
8351 // Determine if the integer constant can be expressed as a floating point
8352 // number of the appropriate type.
8353 llvm::APSInt Result;
8354 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8357 // Reject constants that would be truncated if they were converted to
8358 // the floating point type. Test by simple to/from conversion.
8359 // FIXME: Ideally the conversion to an APFloat and from an APFloat
8360 // could be avoided if there was a convertFromAPInt method
8361 // which could signal back if implicit truncation occurred.
8362 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8363 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8364 llvm::APFloat::rmTowardZero);
8365 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8366 !IntTy->hasSignedIntegerRepresentation());
8367 bool Ignored = false;
8368 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8370 if (Result != ConvertBack)
8373 // Reject types that cannot be fully encoded into the mantissa of
8375 Bits = S.Context.getTypeSize(IntTy);
8376 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8377 S.Context.getFloatTypeSemantics(FloatTy));
8378 if (Bits > FloatPrec)
8385 /// Attempt to convert and splat Scalar into a vector whose types matches
8386 /// Vector following GCC conversion rules. The rule is that implicit
8387 /// conversion can occur when Scalar can be casted to match Vector's element
8388 /// type without causing truncation of Scalar.
8389 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8390 ExprResult *Vector) {
8391 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8392 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8393 const VectorType *VT = VectorTy->getAs<VectorType>();
8395 assert(!isa<ExtVectorType>(VT) &&
8396 "ExtVectorTypes should not be handled here!");
8398 QualType VectorEltTy = VT->getElementType();
8400 // Reject cases where the vector element type or the scalar element type are
8401 // not integral or floating point types.
8402 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8405 // The conversion to apply to the scalar before splatting it,
8407 CastKind ScalarCast = CK_NoOp;
8409 // Accept cases where the vector elements are integers and the scalar is
8411 // FIXME: Notionally if the scalar was a floating point value with a precise
8412 // integral representation, we could cast it to an appropriate integer
8413 // type and then perform the rest of the checks here. GCC will perform
8414 // this conversion in some cases as determined by the input language.
8415 // We should accept it on a language independent basis.
8416 if (VectorEltTy->isIntegralType(S.Context) &&
8417 ScalarTy->isIntegralType(S.Context) &&
8418 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8420 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8423 ScalarCast = CK_IntegralCast;
8424 } else if (VectorEltTy->isRealFloatingType()) {
8425 if (ScalarTy->isRealFloatingType()) {
8427 // Reject cases where the scalar type is not a constant and has a higher
8428 // Order than the vector element type.
8429 llvm::APFloat Result(0.0);
8430 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8431 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8432 if (!CstScalar && Order < 0)
8435 // If the scalar cannot be safely casted to the vector element type,
8438 bool Truncated = false;
8439 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8440 llvm::APFloat::rmNearestTiesToEven, &Truncated);
8445 ScalarCast = CK_FloatingCast;
8446 } else if (ScalarTy->isIntegralType(S.Context)) {
8447 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8450 ScalarCast = CK_IntegralToFloating;
8455 // Adjust scalar if desired.
8457 if (ScalarCast != CK_NoOp)
8458 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8459 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8464 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8465 SourceLocation Loc, bool IsCompAssign,
8467 bool AllowBoolConversions) {
8468 if (!IsCompAssign) {
8469 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8470 if (LHS.isInvalid())
8473 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8474 if (RHS.isInvalid())
8477 // For conversion purposes, we ignore any qualifiers.
8478 // For example, "const float" and "float" are equivalent.
8479 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8480 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8482 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8483 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8484 assert(LHSVecType || RHSVecType);
8486 // AltiVec-style "vector bool op vector bool" combinations are allowed
8487 // for some operators but not others.
8488 if (!AllowBothBool &&
8489 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8490 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8491 return InvalidOperands(Loc, LHS, RHS);
8493 // If the vector types are identical, return.
8494 if (Context.hasSameType(LHSType, RHSType))
8497 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8498 if (LHSVecType && RHSVecType &&
8499 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8500 if (isa<ExtVectorType>(LHSVecType)) {
8501 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8506 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8510 // AllowBoolConversions says that bool and non-bool AltiVec vectors
8511 // can be mixed, with the result being the non-bool type. The non-bool
8512 // operand must have integer element type.
8513 if (AllowBoolConversions && LHSVecType && RHSVecType &&
8514 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8515 (Context.getTypeSize(LHSVecType->getElementType()) ==
8516 Context.getTypeSize(RHSVecType->getElementType()))) {
8517 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8518 LHSVecType->getElementType()->isIntegerType() &&
8519 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8520 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8523 if (!IsCompAssign &&
8524 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8525 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8526 RHSVecType->getElementType()->isIntegerType()) {
8527 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8532 // If there's a vector type and a scalar, try to convert the scalar to
8533 // the vector element type and splat.
8534 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8536 if (isa<ExtVectorType>(LHSVecType)) {
8537 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8538 LHSVecType->getElementType(), LHSType,
8542 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8547 if (isa<ExtVectorType>(RHSVecType)) {
8548 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8549 LHSType, RHSVecType->getElementType(),
8553 if (LHS.get()->getValueKind() == VK_LValue ||
8554 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8559 // FIXME: The code below also handles conversion between vectors and
8560 // non-scalars, we should break this down into fine grained specific checks
8561 // and emit proper diagnostics.
8562 QualType VecType = LHSVecType ? LHSType : RHSType;
8563 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8564 QualType OtherType = LHSVecType ? RHSType : LHSType;
8565 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8566 if (isLaxVectorConversion(OtherType, VecType)) {
8567 // If we're allowing lax vector conversions, only the total (data) size
8568 // needs to be the same. For non compound assignment, if one of the types is
8569 // scalar, the result is always the vector type.
8570 if (!IsCompAssign) {
8571 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8573 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8574 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8575 // type. Note that this is already done by non-compound assignments in
8576 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8577 // <1 x T> -> T. The result is also a vector type.
8578 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8579 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8580 ExprResult *RHSExpr = &RHS;
8581 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8586 // Okay, the expression is invalid.
8588 // If there's a non-vector, non-real operand, diagnose that.
8589 if ((!RHSVecType && !RHSType->isRealType()) ||
8590 (!LHSVecType && !LHSType->isRealType())) {
8591 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8592 << LHSType << RHSType
8593 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8597 // OpenCL V1.1 6.2.6.p1:
8598 // If the operands are of more than one vector type, then an error shall
8599 // occur. Implicit conversions between vector types are not permitted, per
8601 if (getLangOpts().OpenCL &&
8602 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8603 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8604 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8610 // If there is a vector type that is not a ExtVector and a scalar, we reach
8611 // this point if scalar could not be converted to the vector's element type
8612 // without truncation.
8613 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8614 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8615 QualType Scalar = LHSVecType ? RHSType : LHSType;
8616 QualType Vector = LHSVecType ? LHSType : RHSType;
8617 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8619 diag::err_typecheck_vector_not_convertable_implict_truncation)
8620 << ScalarOrVector << Scalar << Vector;
8625 // Otherwise, use the generic diagnostic.
8627 << LHSType << RHSType
8628 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8632 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8633 // expression. These are mainly cases where the null pointer is used as an
8634 // integer instead of a pointer.
8635 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8636 SourceLocation Loc, bool IsCompare) {
8637 // The canonical way to check for a GNU null is with isNullPointerConstant,
8638 // but we use a bit of a hack here for speed; this is a relatively
8639 // hot path, and isNullPointerConstant is slow.
8640 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8641 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8643 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8645 // Avoid analyzing cases where the result will either be invalid (and
8646 // diagnosed as such) or entirely valid and not something to warn about.
8647 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8648 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8651 // Comparison operations would not make sense with a null pointer no matter
8652 // what the other expression is.
8654 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8655 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8656 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8660 // The rest of the operations only make sense with a null pointer
8661 // if the other expression is a pointer.
8662 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8663 NonNullType->canDecayToPointerType())
8666 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8667 << LHSNull /* LHS is NULL */ << NonNullType
8668 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8671 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8673 SourceLocation Loc, bool IsDiv) {
8674 // Check for division/remainder by zero.
8675 llvm::APSInt RHSValue;
8676 if (!RHS.get()->isValueDependent() &&
8677 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8678 S.DiagRuntimeBehavior(Loc, RHS.get(),
8679 S.PDiag(diag::warn_remainder_division_by_zero)
8680 << IsDiv << RHS.get()->getSourceRange());
8683 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8685 bool IsCompAssign, bool IsDiv) {
8686 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8688 if (LHS.get()->getType()->isVectorType() ||
8689 RHS.get()->getType()->isVectorType())
8690 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8691 /*AllowBothBool*/getLangOpts().AltiVec,
8692 /*AllowBoolConversions*/false);
8694 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8695 if (LHS.isInvalid() || RHS.isInvalid())
8699 if (compType.isNull() || !compType->isArithmeticType())
8700 return InvalidOperands(Loc, LHS, RHS);
8702 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8706 QualType Sema::CheckRemainderOperands(
8707 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8708 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8710 if (LHS.get()->getType()->isVectorType() ||
8711 RHS.get()->getType()->isVectorType()) {
8712 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8713 RHS.get()->getType()->hasIntegerRepresentation())
8714 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8715 /*AllowBothBool*/getLangOpts().AltiVec,
8716 /*AllowBoolConversions*/false);
8717 return InvalidOperands(Loc, LHS, RHS);
8720 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8721 if (LHS.isInvalid() || RHS.isInvalid())
8724 if (compType.isNull() || !compType->isIntegerType())
8725 return InvalidOperands(Loc, LHS, RHS);
8726 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8730 /// Diagnose invalid arithmetic on two void pointers.
8731 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8732 Expr *LHSExpr, Expr *RHSExpr) {
8733 S.Diag(Loc, S.getLangOpts().CPlusPlus
8734 ? diag::err_typecheck_pointer_arith_void_type
8735 : diag::ext_gnu_void_ptr)
8736 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8737 << RHSExpr->getSourceRange();
8740 /// Diagnose invalid arithmetic on a void pointer.
8741 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8743 S.Diag(Loc, S.getLangOpts().CPlusPlus
8744 ? diag::err_typecheck_pointer_arith_void_type
8745 : diag::ext_gnu_void_ptr)
8746 << 0 /* one pointer */ << Pointer->getSourceRange();
8749 /// Diagnose invalid arithmetic on a null pointer.
8751 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8752 /// idiom, which we recognize as a GNU extension.
8754 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8755 Expr *Pointer, bool IsGNUIdiom) {
8757 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8758 << Pointer->getSourceRange();
8760 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8761 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8764 /// Diagnose invalid arithmetic on two function pointers.
8765 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8766 Expr *LHS, Expr *RHS) {
8767 assert(LHS->getType()->isAnyPointerType());
8768 assert(RHS->getType()->isAnyPointerType());
8769 S.Diag(Loc, S.getLangOpts().CPlusPlus
8770 ? diag::err_typecheck_pointer_arith_function_type
8771 : diag::ext_gnu_ptr_func_arith)
8772 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8773 // We only show the second type if it differs from the first.
8774 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8776 << RHS->getType()->getPointeeType()
8777 << LHS->getSourceRange() << RHS->getSourceRange();
8780 /// Diagnose invalid arithmetic on a function pointer.
8781 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8783 assert(Pointer->getType()->isAnyPointerType());
8784 S.Diag(Loc, S.getLangOpts().CPlusPlus
8785 ? diag::err_typecheck_pointer_arith_function_type
8786 : diag::ext_gnu_ptr_func_arith)
8787 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8788 << 0 /* one pointer, so only one type */
8789 << Pointer->getSourceRange();
8792 /// Emit error if Operand is incomplete pointer type
8794 /// \returns True if pointer has incomplete type
8795 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8797 QualType ResType = Operand->getType();
8798 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8799 ResType = ResAtomicType->getValueType();
8801 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8802 QualType PointeeTy = ResType->getPointeeType();
8803 return S.RequireCompleteType(Loc, PointeeTy,
8804 diag::err_typecheck_arithmetic_incomplete_type,
8805 PointeeTy, Operand->getSourceRange());
8808 /// Check the validity of an arithmetic pointer operand.
8810 /// If the operand has pointer type, this code will check for pointer types
8811 /// which are invalid in arithmetic operations. These will be diagnosed
8812 /// appropriately, including whether or not the use is supported as an
8815 /// \returns True when the operand is valid to use (even if as an extension).
8816 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8818 QualType ResType = Operand->getType();
8819 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8820 ResType = ResAtomicType->getValueType();
8822 if (!ResType->isAnyPointerType()) return true;
8824 QualType PointeeTy = ResType->getPointeeType();
8825 if (PointeeTy->isVoidType()) {
8826 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8827 return !S.getLangOpts().CPlusPlus;
8829 if (PointeeTy->isFunctionType()) {
8830 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8831 return !S.getLangOpts().CPlusPlus;
8834 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8839 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8842 /// This routine will diagnose any invalid arithmetic on pointer operands much
8843 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8844 /// for emitting a single diagnostic even for operations where both LHS and RHS
8845 /// are (potentially problematic) pointers.
8847 /// \returns True when the operand is valid to use (even if as an extension).
8848 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8849 Expr *LHSExpr, Expr *RHSExpr) {
8850 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8851 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8852 if (!isLHSPointer && !isRHSPointer) return true;
8854 QualType LHSPointeeTy, RHSPointeeTy;
8855 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8856 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8858 // if both are pointers check if operation is valid wrt address spaces
8859 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8860 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8861 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8862 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8864 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8865 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8866 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8871 // Check for arithmetic on pointers to incomplete types.
8872 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8873 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8874 if (isLHSVoidPtr || isRHSVoidPtr) {
8875 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8876 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8877 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8879 return !S.getLangOpts().CPlusPlus;
8882 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8883 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8884 if (isLHSFuncPtr || isRHSFuncPtr) {
8885 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8886 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8888 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8890 return !S.getLangOpts().CPlusPlus;
8893 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8895 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8901 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8903 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8904 Expr *LHSExpr, Expr *RHSExpr) {
8905 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8906 Expr* IndexExpr = RHSExpr;
8908 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8909 IndexExpr = LHSExpr;
8912 bool IsStringPlusInt = StrExpr &&
8913 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8914 if (!IsStringPlusInt || IndexExpr->isValueDependent())
8918 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8919 unsigned StrLenWithNull = StrExpr->getLength() + 1;
8920 if (index.isNonNegative() &&
8921 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8922 index.isUnsigned()))
8926 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8927 Self.Diag(OpLoc, diag::warn_string_plus_int)
8928 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8930 // Only print a fixit for "str" + int, not for int + "str".
8931 if (IndexExpr == RHSExpr) {
8932 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8933 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8934 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8935 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8936 << FixItHint::CreateInsertion(EndLoc, "]");
8938 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8941 /// Emit a warning when adding a char literal to a string.
8942 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8943 Expr *LHSExpr, Expr *RHSExpr) {
8944 const Expr *StringRefExpr = LHSExpr;
8945 const CharacterLiteral *CharExpr =
8946 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8949 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8950 StringRefExpr = RHSExpr;
8953 if (!CharExpr || !StringRefExpr)
8956 const QualType StringType = StringRefExpr->getType();
8958 // Return if not a PointerType.
8959 if (!StringType->isAnyPointerType())
8962 // Return if not a CharacterType.
8963 if (!StringType->getPointeeType()->isAnyCharacterType())
8966 ASTContext &Ctx = Self.getASTContext();
8967 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8969 const QualType CharType = CharExpr->getType();
8970 if (!CharType->isAnyCharacterType() &&
8971 CharType->isIntegerType() &&
8972 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8973 Self.Diag(OpLoc, diag::warn_string_plus_char)
8974 << DiagRange << Ctx.CharTy;
8976 Self.Diag(OpLoc, diag::warn_string_plus_char)
8977 << DiagRange << CharExpr->getType();
8980 // Only print a fixit for str + char, not for char + str.
8981 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8982 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8983 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8984 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8985 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8986 << FixItHint::CreateInsertion(EndLoc, "]");
8988 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8992 /// Emit error when two pointers are incompatible.
8993 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8994 Expr *LHSExpr, Expr *RHSExpr) {
8995 assert(LHSExpr->getType()->isAnyPointerType());
8996 assert(RHSExpr->getType()->isAnyPointerType());
8997 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8998 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8999 << RHSExpr->getSourceRange();
9003 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9004 SourceLocation Loc, BinaryOperatorKind Opc,
9005 QualType* CompLHSTy) {
9006 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9008 if (LHS.get()->getType()->isVectorType() ||
9009 RHS.get()->getType()->isVectorType()) {
9010 QualType compType = CheckVectorOperands(
9011 LHS, RHS, Loc, CompLHSTy,
9012 /*AllowBothBool*/getLangOpts().AltiVec,
9013 /*AllowBoolConversions*/getLangOpts().ZVector);
9014 if (CompLHSTy) *CompLHSTy = compType;
9018 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9019 if (LHS.isInvalid() || RHS.isInvalid())
9022 // Diagnose "string literal" '+' int and string '+' "char literal".
9023 if (Opc == BO_Add) {
9024 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9025 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9028 // handle the common case first (both operands are arithmetic).
9029 if (!compType.isNull() && compType->isArithmeticType()) {
9030 if (CompLHSTy) *CompLHSTy = compType;
9034 // Type-checking. Ultimately the pointer's going to be in PExp;
9035 // note that we bias towards the LHS being the pointer.
9036 Expr *PExp = LHS.get(), *IExp = RHS.get();
9039 if (PExp->getType()->isPointerType()) {
9040 isObjCPointer = false;
9041 } else if (PExp->getType()->isObjCObjectPointerType()) {
9042 isObjCPointer = true;
9044 std::swap(PExp, IExp);
9045 if (PExp->getType()->isPointerType()) {
9046 isObjCPointer = false;
9047 } else if (PExp->getType()->isObjCObjectPointerType()) {
9048 isObjCPointer = true;
9050 return InvalidOperands(Loc, LHS, RHS);
9053 assert(PExp->getType()->isAnyPointerType());
9055 if (!IExp->getType()->isIntegerType())
9056 return InvalidOperands(Loc, LHS, RHS);
9058 // Adding to a null pointer results in undefined behavior.
9059 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9060 Context, Expr::NPC_ValueDependentIsNotNull)) {
9061 // In C++ adding zero to a null pointer is defined.
9062 llvm::APSInt KnownVal;
9063 if (!getLangOpts().CPlusPlus ||
9064 (!IExp->isValueDependent() &&
9065 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9066 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9067 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9068 Context, BO_Add, PExp, IExp);
9069 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9073 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9076 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9079 // Check array bounds for pointer arithemtic
9080 CheckArrayAccess(PExp, IExp);
9083 QualType LHSTy = Context.isPromotableBitField(LHS.get());
9084 if (LHSTy.isNull()) {
9085 LHSTy = LHS.get()->getType();
9086 if (LHSTy->isPromotableIntegerType())
9087 LHSTy = Context.getPromotedIntegerType(LHSTy);
9092 return PExp->getType();
9096 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9098 QualType* CompLHSTy) {
9099 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9101 if (LHS.get()->getType()->isVectorType() ||
9102 RHS.get()->getType()->isVectorType()) {
9103 QualType compType = CheckVectorOperands(
9104 LHS, RHS, Loc, CompLHSTy,
9105 /*AllowBothBool*/getLangOpts().AltiVec,
9106 /*AllowBoolConversions*/getLangOpts().ZVector);
9107 if (CompLHSTy) *CompLHSTy = compType;
9111 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9112 if (LHS.isInvalid() || RHS.isInvalid())
9115 // Enforce type constraints: C99 6.5.6p3.
9117 // Handle the common case first (both operands are arithmetic).
9118 if (!compType.isNull() && compType->isArithmeticType()) {
9119 if (CompLHSTy) *CompLHSTy = compType;
9123 // Either ptr - int or ptr - ptr.
9124 if (LHS.get()->getType()->isAnyPointerType()) {
9125 QualType lpointee = LHS.get()->getType()->getPointeeType();
9127 // Diagnose bad cases where we step over interface counts.
9128 if (LHS.get()->getType()->isObjCObjectPointerType() &&
9129 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9132 // The result type of a pointer-int computation is the pointer type.
9133 if (RHS.get()->getType()->isIntegerType()) {
9134 // Subtracting from a null pointer should produce a warning.
9135 // The last argument to the diagnose call says this doesn't match the
9136 // GNU int-to-pointer idiom.
9137 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9138 Expr::NPC_ValueDependentIsNotNull)) {
9139 // In C++ adding zero to a null pointer is defined.
9140 llvm::APSInt KnownVal;
9141 if (!getLangOpts().CPlusPlus ||
9142 (!RHS.get()->isValueDependent() &&
9143 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9144 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9148 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9151 // Check array bounds for pointer arithemtic
9152 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9153 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9155 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9156 return LHS.get()->getType();
9159 // Handle pointer-pointer subtractions.
9160 if (const PointerType *RHSPTy
9161 = RHS.get()->getType()->getAs<PointerType>()) {
9162 QualType rpointee = RHSPTy->getPointeeType();
9164 if (getLangOpts().CPlusPlus) {
9165 // Pointee types must be the same: C++ [expr.add]
9166 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9167 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9170 // Pointee types must be compatible C99 6.5.6p3
9171 if (!Context.typesAreCompatible(
9172 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9173 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9174 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9179 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9180 LHS.get(), RHS.get()))
9183 // FIXME: Add warnings for nullptr - ptr.
9185 // The pointee type may have zero size. As an extension, a structure or
9186 // union may have zero size or an array may have zero length. In this
9187 // case subtraction does not make sense.
9188 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9189 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9190 if (ElementSize.isZero()) {
9191 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9192 << rpointee.getUnqualifiedType()
9193 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9197 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9198 return Context.getPointerDiffType();
9202 return InvalidOperands(Loc, LHS, RHS);
9205 static bool isScopedEnumerationType(QualType T) {
9206 if (const EnumType *ET = T->getAs<EnumType>())
9207 return ET->getDecl()->isScoped();
9211 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9212 SourceLocation Loc, BinaryOperatorKind Opc,
9214 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9215 // so skip remaining warnings as we don't want to modify values within Sema.
9216 if (S.getLangOpts().OpenCL)
9220 // Check right/shifter operand
9221 if (RHS.get()->isValueDependent() ||
9222 !RHS.get()->EvaluateAsInt(Right, S.Context))
9225 if (Right.isNegative()) {
9226 S.DiagRuntimeBehavior(Loc, RHS.get(),
9227 S.PDiag(diag::warn_shift_negative)
9228 << RHS.get()->getSourceRange());
9231 llvm::APInt LeftBits(Right.getBitWidth(),
9232 S.Context.getTypeSize(LHS.get()->getType()));
9233 if (Right.uge(LeftBits)) {
9234 S.DiagRuntimeBehavior(Loc, RHS.get(),
9235 S.PDiag(diag::warn_shift_gt_typewidth)
9236 << RHS.get()->getSourceRange());
9242 // When left shifting an ICE which is signed, we can check for overflow which
9243 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9244 // integers have defined behavior modulo one more than the maximum value
9245 // representable in the result type, so never warn for those.
9247 if (LHS.get()->isValueDependent() ||
9248 LHSType->hasUnsignedIntegerRepresentation() ||
9249 !LHS.get()->EvaluateAsInt(Left, S.Context))
9252 // If LHS does not have a signed type and non-negative value
9253 // then, the behavior is undefined. Warn about it.
9254 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9255 S.DiagRuntimeBehavior(Loc, LHS.get(),
9256 S.PDiag(diag::warn_shift_lhs_negative)
9257 << LHS.get()->getSourceRange());
9261 llvm::APInt ResultBits =
9262 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9263 if (LeftBits.uge(ResultBits))
9265 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9266 Result = Result.shl(Right);
9268 // Print the bit representation of the signed integer as an unsigned
9269 // hexadecimal number.
9270 SmallString<40> HexResult;
9271 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9273 // If we are only missing a sign bit, this is less likely to result in actual
9274 // bugs -- if the result is cast back to an unsigned type, it will have the
9275 // expected value. Thus we place this behind a different warning that can be
9276 // turned off separately if needed.
9277 if (LeftBits == ResultBits - 1) {
9278 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9279 << HexResult << LHSType
9280 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9284 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9285 << HexResult.str() << Result.getMinSignedBits() << LHSType
9286 << Left.getBitWidth() << LHS.get()->getSourceRange()
9287 << RHS.get()->getSourceRange();
9290 /// Return the resulting type when a vector is shifted
9291 /// by a scalar or vector shift amount.
9292 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9293 SourceLocation Loc, bool IsCompAssign) {
9294 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9295 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9296 !LHS.get()->getType()->isVectorType()) {
9297 S.Diag(Loc, diag::err_shift_rhs_only_vector)
9298 << RHS.get()->getType() << LHS.get()->getType()
9299 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9303 if (!IsCompAssign) {
9304 LHS = S.UsualUnaryConversions(LHS.get());
9305 if (LHS.isInvalid()) return QualType();
9308 RHS = S.UsualUnaryConversions(RHS.get());
9309 if (RHS.isInvalid()) return QualType();
9311 QualType LHSType = LHS.get()->getType();
9312 // Note that LHS might be a scalar because the routine calls not only in
9314 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9315 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9317 // Note that RHS might not be a vector.
9318 QualType RHSType = RHS.get()->getType();
9319 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9320 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9322 // The operands need to be integers.
9323 if (!LHSEleType->isIntegerType()) {
9324 S.Diag(Loc, diag::err_typecheck_expect_int)
9325 << LHS.get()->getType() << LHS.get()->getSourceRange();
9329 if (!RHSEleType->isIntegerType()) {
9330 S.Diag(Loc, diag::err_typecheck_expect_int)
9331 << RHS.get()->getType() << RHS.get()->getSourceRange();
9339 if (LHSEleType != RHSEleType) {
9340 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9341 LHSEleType = RHSEleType;
9344 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9345 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9347 } else if (RHSVecTy) {
9348 // OpenCL v1.1 s6.3.j says that for vector types, the operators
9349 // are applied component-wise. So if RHS is a vector, then ensure
9350 // that the number of elements is the same as LHS...
9351 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9352 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9353 << LHS.get()->getType() << RHS.get()->getType()
9354 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9357 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9358 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9359 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9360 if (LHSBT != RHSBT &&
9361 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9362 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9363 << LHS.get()->getType() << RHS.get()->getType()
9364 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9368 // ...else expand RHS to match the number of elements in LHS.
9370 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9371 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9378 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9379 SourceLocation Loc, BinaryOperatorKind Opc,
9380 bool IsCompAssign) {
9381 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9383 // Vector shifts promote their scalar inputs to vector type.
9384 if (LHS.get()->getType()->isVectorType() ||
9385 RHS.get()->getType()->isVectorType()) {
9386 if (LangOpts.ZVector) {
9387 // The shift operators for the z vector extensions work basically
9388 // like general shifts, except that neither the LHS nor the RHS is
9389 // allowed to be a "vector bool".
9390 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9391 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9392 return InvalidOperands(Loc, LHS, RHS);
9393 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9394 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9395 return InvalidOperands(Loc, LHS, RHS);
9397 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9400 // Shifts don't perform usual arithmetic conversions, they just do integer
9401 // promotions on each operand. C99 6.5.7p3
9403 // For the LHS, do usual unary conversions, but then reset them away
9404 // if this is a compound assignment.
9405 ExprResult OldLHS = LHS;
9406 LHS = UsualUnaryConversions(LHS.get());
9407 if (LHS.isInvalid())
9409 QualType LHSType = LHS.get()->getType();
9410 if (IsCompAssign) LHS = OldLHS;
9412 // The RHS is simpler.
9413 RHS = UsualUnaryConversions(RHS.get());
9414 if (RHS.isInvalid())
9416 QualType RHSType = RHS.get()->getType();
9418 // C99 6.5.7p2: Each of the operands shall have integer type.
9419 if (!LHSType->hasIntegerRepresentation() ||
9420 !RHSType->hasIntegerRepresentation())
9421 return InvalidOperands(Loc, LHS, RHS);
9423 // C++0x: Don't allow scoped enums. FIXME: Use something better than
9424 // hasIntegerRepresentation() above instead of this.
9425 if (isScopedEnumerationType(LHSType) ||
9426 isScopedEnumerationType(RHSType)) {
9427 return InvalidOperands(Loc, LHS, RHS);
9429 // Sanity-check shift operands
9430 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9432 // "The type of the result is that of the promoted left operand."
9436 /// If two different enums are compared, raise a warning.
9437 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9439 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9440 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9442 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9445 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9449 // Ignore anonymous enums.
9450 if (!LHSEnumType->getDecl()->getIdentifier() &&
9451 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9453 if (!RHSEnumType->getDecl()->getIdentifier() &&
9454 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9457 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9460 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9461 << LHSStrippedType << RHSStrippedType
9462 << LHS->getSourceRange() << RHS->getSourceRange();
9465 /// Diagnose bad pointer comparisons.
9466 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9467 ExprResult &LHS, ExprResult &RHS,
9469 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9470 : diag::ext_typecheck_comparison_of_distinct_pointers)
9471 << LHS.get()->getType() << RHS.get()->getType()
9472 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9475 /// Returns false if the pointers are converted to a composite type,
9477 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9478 ExprResult &LHS, ExprResult &RHS) {
9479 // C++ [expr.rel]p2:
9480 // [...] Pointer conversions (4.10) and qualification
9481 // conversions (4.4) are performed on pointer operands (or on
9482 // a pointer operand and a null pointer constant) to bring
9483 // them to their composite pointer type. [...]
9485 // C++ [expr.eq]p1 uses the same notion for (in)equality
9486 // comparisons of pointers.
9488 QualType LHSType = LHS.get()->getType();
9489 QualType RHSType = RHS.get()->getType();
9490 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9491 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9493 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9495 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9496 (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9497 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9499 S.InvalidOperands(Loc, LHS, RHS);
9503 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9504 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9508 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9512 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9513 : diag::ext_typecheck_comparison_of_fptr_to_void)
9514 << LHS.get()->getType() << RHS.get()->getType()
9515 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9518 static bool isObjCObjectLiteral(ExprResult &E) {
9519 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9520 case Stmt::ObjCArrayLiteralClass:
9521 case Stmt::ObjCDictionaryLiteralClass:
9522 case Stmt::ObjCStringLiteralClass:
9523 case Stmt::ObjCBoxedExprClass:
9526 // Note that ObjCBoolLiteral is NOT an object literal!
9531 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9532 const ObjCObjectPointerType *Type =
9533 LHS->getType()->getAs<ObjCObjectPointerType>();
9535 // If this is not actually an Objective-C object, bail out.
9539 // Get the LHS object's interface type.
9540 QualType InterfaceType = Type->getPointeeType();
9542 // If the RHS isn't an Objective-C object, bail out.
9543 if (!RHS->getType()->isObjCObjectPointerType())
9546 // Try to find the -isEqual: method.
9547 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9548 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9552 if (Type->isObjCIdType()) {
9553 // For 'id', just check the global pool.
9554 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9555 /*receiverId=*/true);
9558 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9566 QualType T = Method->parameters()[0]->getType();
9567 if (!T->isObjCObjectPointerType())
9570 QualType R = Method->getReturnType();
9571 if (!R->isScalarType())
9577 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9578 FromE = FromE->IgnoreParenImpCasts();
9579 switch (FromE->getStmtClass()) {
9582 case Stmt::ObjCStringLiteralClass:
9585 case Stmt::ObjCArrayLiteralClass:
9588 case Stmt::ObjCDictionaryLiteralClass:
9589 // "dictionary literal"
9590 return LK_Dictionary;
9591 case Stmt::BlockExprClass:
9593 case Stmt::ObjCBoxedExprClass: {
9594 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9595 switch (Inner->getStmtClass()) {
9596 case Stmt::IntegerLiteralClass:
9597 case Stmt::FloatingLiteralClass:
9598 case Stmt::CharacterLiteralClass:
9599 case Stmt::ObjCBoolLiteralExprClass:
9600 case Stmt::CXXBoolLiteralExprClass:
9601 // "numeric literal"
9603 case Stmt::ImplicitCastExprClass: {
9604 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9605 // Boolean literals can be represented by implicit casts.
9606 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9619 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9620 ExprResult &LHS, ExprResult &RHS,
9621 BinaryOperator::Opcode Opc){
9624 if (isObjCObjectLiteral(LHS)) {
9625 Literal = LHS.get();
9628 Literal = RHS.get();
9632 // Don't warn on comparisons against nil.
9633 Other = Other->IgnoreParenCasts();
9634 if (Other->isNullPointerConstant(S.getASTContext(),
9635 Expr::NPC_ValueDependentIsNotNull))
9638 // This should be kept in sync with warn_objc_literal_comparison.
9639 // LK_String should always be after the other literals, since it has its own
9641 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9642 assert(LiteralKind != Sema::LK_Block);
9643 if (LiteralKind == Sema::LK_None) {
9644 llvm_unreachable("Unknown Objective-C object literal kind");
9647 if (LiteralKind == Sema::LK_String)
9648 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9649 << Literal->getSourceRange();
9651 S.Diag(Loc, diag::warn_objc_literal_comparison)
9652 << LiteralKind << Literal->getSourceRange();
9654 if (BinaryOperator::isEqualityOp(Opc) &&
9655 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9656 SourceLocation Start = LHS.get()->getLocStart();
9657 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9658 CharSourceRange OpRange =
9659 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9661 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9662 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9663 << FixItHint::CreateReplacement(OpRange, " isEqual:")
9664 << FixItHint::CreateInsertion(End, "]");
9668 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9669 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9670 ExprResult &RHS, SourceLocation Loc,
9671 BinaryOperatorKind Opc) {
9672 // Check that left hand side is !something.
9673 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9674 if (!UO || UO->getOpcode() != UO_LNot) return;
9676 // Only check if the right hand side is non-bool arithmetic type.
9677 if (RHS.get()->isKnownToHaveBooleanValue()) return;
9679 // Make sure that the something in !something is not bool.
9680 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9681 if (SubExpr->isKnownToHaveBooleanValue()) return;
9684 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9685 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9686 << Loc << IsBitwiseOp;
9688 // First note suggest !(x < y)
9689 SourceLocation FirstOpen = SubExpr->getLocStart();
9690 SourceLocation FirstClose = RHS.get()->getLocEnd();
9691 FirstClose = S.getLocForEndOfToken(FirstClose);
9692 if (FirstClose.isInvalid())
9693 FirstOpen = SourceLocation();
9694 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9696 << FixItHint::CreateInsertion(FirstOpen, "(")
9697 << FixItHint::CreateInsertion(FirstClose, ")");
9699 // Second note suggests (!x) < y
9700 SourceLocation SecondOpen = LHS.get()->getLocStart();
9701 SourceLocation SecondClose = LHS.get()->getLocEnd();
9702 SecondClose = S.getLocForEndOfToken(SecondClose);
9703 if (SecondClose.isInvalid())
9704 SecondOpen = SourceLocation();
9705 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9706 << FixItHint::CreateInsertion(SecondOpen, "(")
9707 << FixItHint::CreateInsertion(SecondClose, ")");
9710 // Get the decl for a simple expression: a reference to a variable,
9711 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9712 static ValueDecl *getCompareDecl(Expr *E) {
9713 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9714 return DR->getDecl();
9715 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9716 if (Ivar->isFreeIvar())
9717 return Ivar->getDecl();
9719 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9720 if (Mem->isImplicitAccess())
9721 return Mem->getMemberDecl();
9726 /// Diagnose some forms of syntactically-obvious tautological comparison.
9727 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9728 Expr *LHS, Expr *RHS,
9729 BinaryOperatorKind Opc) {
9730 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9731 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9733 QualType LHSType = LHS->getType();
9734 QualType RHSType = RHS->getType();
9735 if (LHSType->hasFloatingRepresentation() ||
9736 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9737 LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9738 S.inTemplateInstantiation())
9741 // Comparisons between two array types are ill-formed for operator<=>, so
9742 // we shouldn't emit any additional warnings about it.
9743 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9746 // For non-floating point types, check for self-comparisons of the form
9747 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9748 // often indicate logic errors in the program.
9750 // NOTE: Don't warn about comparison expressions resulting from macro
9751 // expansion. Also don't warn about comparisons which are only self
9752 // comparisons within a template instantiation. The warnings should catch
9753 // obvious cases in the definition of the template anyways. The idea is to
9754 // warn when the typed comparison operator will always evaluate to the same
9756 ValueDecl *DL = getCompareDecl(LHSStripped);
9757 ValueDecl *DR = getCompareDecl(RHSStripped);
9758 if (DL && DR && declaresSameEntity(DL, DR)) {
9761 case BO_EQ: case BO_LE: case BO_GE:
9764 case BO_NE: case BO_LT: case BO_GT:
9768 Result = "'std::strong_ordering::equal'";
9773 S.DiagRuntimeBehavior(Loc, nullptr,
9774 S.PDiag(diag::warn_comparison_always)
9775 << 0 /*self-comparison*/ << !Result.empty()
9777 } else if (DL && DR &&
9778 DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9779 !DL->isWeak() && !DR->isWeak()) {
9780 // What is it always going to evaluate to?
9783 case BO_EQ: // e.g. array1 == array2
9786 case BO_NE: // e.g. array1 != array2
9789 default: // e.g. array1 <= array2
9790 // The best we can say is 'a constant'
9793 S.DiagRuntimeBehavior(Loc, nullptr,
9794 S.PDiag(diag::warn_comparison_always)
9795 << 1 /*array comparison*/
9796 << !Result.empty() << Result);
9799 if (isa<CastExpr>(LHSStripped))
9800 LHSStripped = LHSStripped->IgnoreParenCasts();
9801 if (isa<CastExpr>(RHSStripped))
9802 RHSStripped = RHSStripped->IgnoreParenCasts();
9804 // Warn about comparisons against a string constant (unless the other
9805 // operand is null); the user probably wants strcmp.
9806 Expr *LiteralString = nullptr;
9807 Expr *LiteralStringStripped = nullptr;
9808 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9809 !RHSStripped->isNullPointerConstant(S.Context,
9810 Expr::NPC_ValueDependentIsNull)) {
9811 LiteralString = LHS;
9812 LiteralStringStripped = LHSStripped;
9813 } else if ((isa<StringLiteral>(RHSStripped) ||
9814 isa<ObjCEncodeExpr>(RHSStripped)) &&
9815 !LHSStripped->isNullPointerConstant(S.Context,
9816 Expr::NPC_ValueDependentIsNull)) {
9817 LiteralString = RHS;
9818 LiteralStringStripped = RHSStripped;
9821 if (LiteralString) {
9822 S.DiagRuntimeBehavior(Loc, nullptr,
9823 S.PDiag(diag::warn_stringcompare)
9824 << isa<ObjCEncodeExpr>(LiteralStringStripped)
9825 << LiteralString->getSourceRange());
9829 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
9833 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9836 llvm_unreachable("unhandled cast kind");
9838 case CK_UserDefinedConversion:
9839 return ICK_Identity;
9840 case CK_LValueToRValue:
9841 return ICK_Lvalue_To_Rvalue;
9842 case CK_ArrayToPointerDecay:
9843 return ICK_Array_To_Pointer;
9844 case CK_FunctionToPointerDecay:
9845 return ICK_Function_To_Pointer;
9846 case CK_IntegralCast:
9847 return ICK_Integral_Conversion;
9848 case CK_FloatingCast:
9849 return ICK_Floating_Conversion;
9850 case CK_IntegralToFloating:
9851 case CK_FloatingToIntegral:
9852 return ICK_Floating_Integral;
9853 case CK_IntegralComplexCast:
9854 case CK_FloatingComplexCast:
9855 case CK_FloatingComplexToIntegralComplex:
9856 case CK_IntegralComplexToFloatingComplex:
9857 return ICK_Complex_Conversion;
9858 case CK_FloatingComplexToReal:
9859 case CK_FloatingRealToComplex:
9860 case CK_IntegralComplexToReal:
9861 case CK_IntegralRealToComplex:
9862 return ICK_Complex_Real;
9866 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
9868 SourceLocation Loc) {
9869 // Check for a narrowing implicit conversion.
9870 StandardConversionSequence SCS;
9871 SCS.setAsIdentityConversion();
9872 SCS.setToType(0, FromType);
9873 SCS.setToType(1, ToType);
9874 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9875 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9877 APValue PreNarrowingValue;
9878 QualType PreNarrowingType;
9879 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9881 /*IgnoreFloatToIntegralConversion*/ true)) {
9882 case NK_Dependent_Narrowing:
9883 // Implicit conversion to a narrower type, but the expression is
9884 // value-dependent so we can't tell whether it's actually narrowing.
9885 case NK_Not_Narrowing:
9888 case NK_Constant_Narrowing:
9889 // Implicit conversion to a narrower type, and the value is not a constant
9891 S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9893 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
9896 case NK_Variable_Narrowing:
9897 // Implicit conversion to a narrower type, and the value is not a constant
9899 case NK_Type_Narrowing:
9900 S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9901 << /*Constant*/ 0 << FromType << ToType;
9902 // TODO: It's not a constant expression, but what if the user intended it
9903 // to be? Can we produce notes to help them figure out why it isn't?
9906 llvm_unreachable("unhandled case in switch");
9909 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
9912 SourceLocation Loc) {
9913 using CCT = ComparisonCategoryType;
9915 QualType LHSType = LHS.get()->getType();
9916 QualType RHSType = RHS.get()->getType();
9917 // Dig out the original argument type and expression before implicit casts
9918 // were applied. These are the types/expressions we need to check the
9919 // [expr.spaceship] requirements against.
9920 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
9921 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
9922 QualType LHSStrippedType = LHSStripped.get()->getType();
9923 QualType RHSStrippedType = RHSStripped.get()->getType();
9925 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
9926 // other is not, the program is ill-formed.
9927 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
9928 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9932 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
9933 RHSStrippedType->isEnumeralType();
9934 if (NumEnumArgs == 1) {
9935 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
9936 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
9937 if (OtherTy->hasFloatingRepresentation()) {
9938 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9942 if (NumEnumArgs == 2) {
9943 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
9944 // type E, the operator yields the result of converting the operands
9945 // to the underlying type of E and applying <=> to the converted operands.
9946 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
9947 S.InvalidOperands(Loc, LHS, RHS);
9951 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
9952 assert(IntType->isArithmeticType());
9954 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
9955 // promote the boolean type, and all other promotable integer types, to
9957 if (IntType->isPromotableIntegerType())
9958 IntType = S.Context.getPromotedIntegerType(IntType);
9960 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
9961 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
9962 LHSType = RHSType = IntType;
9965 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
9966 // usual arithmetic conversions are applied to the operands.
9967 QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9968 if (LHS.isInvalid() || RHS.isInvalid())
9971 return S.InvalidOperands(Loc, LHS, RHS);
9972 assert(Type->isArithmeticType() || Type->isEnumeralType());
9974 bool HasNarrowing = checkThreeWayNarrowingConversion(
9975 S, Type, LHS.get(), LHSType, LHS.get()->getLocStart());
9976 HasNarrowing |= checkThreeWayNarrowingConversion(
9977 S, Type, RHS.get(), RHSType, RHS.get()->getLocStart());
9981 assert(!Type.isNull() && "composite type for <=> has not been set");
9983 auto TypeKind = [&]() {
9984 if (const ComplexType *CT = Type->getAs<ComplexType>()) {
9985 if (CT->getElementType()->hasFloatingRepresentation())
9986 return CCT::WeakEquality;
9987 return CCT::StrongEquality;
9989 if (Type->isIntegralOrEnumerationType())
9990 return CCT::StrongOrdering;
9991 if (Type->hasFloatingRepresentation())
9992 return CCT::PartialOrdering;
9993 llvm_unreachable("other types are unimplemented");
9996 return S.CheckComparisonCategoryType(TypeKind, Loc);
9999 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10001 SourceLocation Loc,
10002 BinaryOperatorKind Opc) {
10004 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10006 // C99 6.5.8p3 / C99 6.5.9p4
10007 QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10008 if (LHS.isInvalid() || RHS.isInvalid())
10011 return S.InvalidOperands(Loc, LHS, RHS);
10012 assert(Type->isArithmeticType() || Type->isEnumeralType());
10014 checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10016 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10017 return S.InvalidOperands(Loc, LHS, RHS);
10019 // Check for comparisons of floating point operands using != and ==.
10020 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10021 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10023 // The result of comparisons is 'bool' in C++, 'int' in C.
10024 return S.Context.getLogicalOperationType();
10027 // C99 6.5.8, C++ [expr.rel]
10028 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10029 SourceLocation Loc,
10030 BinaryOperatorKind Opc) {
10031 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10032 bool IsThreeWay = Opc == BO_Cmp;
10033 auto IsAnyPointerType = [](ExprResult E) {
10034 QualType Ty = E.get()->getType();
10035 return Ty->isPointerType() || Ty->isMemberPointerType();
10038 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10039 // type, array-to-pointer, ..., conversions are performed on both operands to
10040 // bring them to their composite type.
10041 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10042 // any type-related checks.
10043 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10044 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10045 if (LHS.isInvalid())
10047 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10048 if (RHS.isInvalid())
10051 LHS = DefaultLvalueConversion(LHS.get());
10052 if (LHS.isInvalid())
10054 RHS = DefaultLvalueConversion(RHS.get());
10055 if (RHS.isInvalid())
10059 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10061 // Handle vector comparisons separately.
10062 if (LHS.get()->getType()->isVectorType() ||
10063 RHS.get()->getType()->isVectorType())
10064 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10066 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10067 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10069 QualType LHSType = LHS.get()->getType();
10070 QualType RHSType = RHS.get()->getType();
10071 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10072 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10073 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10075 const Expr::NullPointerConstantKind LHSNullKind =
10076 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10077 const Expr::NullPointerConstantKind RHSNullKind =
10078 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10079 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10080 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10082 auto computeResultTy = [&]() {
10084 return Context.getLogicalOperationType();
10085 assert(getLangOpts().CPlusPlus);
10086 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10088 QualType CompositeTy = LHS.get()->getType();
10089 assert(!CompositeTy->isReferenceType());
10091 auto buildResultTy = [&](ComparisonCategoryType Kind) {
10092 return CheckComparisonCategoryType(Kind, Loc);
10095 // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10096 // pointer type, a pointer-to-member type, or std::nullptr_t, the
10097 // result is of type std::strong_equality
10098 if (CompositeTy->isFunctionPointerType() ||
10099 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10100 // FIXME: consider making the function pointer case produce
10101 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10102 // and direction polls
10103 return buildResultTy(ComparisonCategoryType::StrongEquality);
10105 // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10106 // pointer type, p <=> q is of type std::strong_ordering.
10107 if (CompositeTy->isPointerType()) {
10108 // P0946R0: Comparisons between a null pointer constant and an object
10109 // pointer result in std::strong_equality
10110 if (LHSIsNull != RHSIsNull)
10111 return buildResultTy(ComparisonCategoryType::StrongEquality);
10112 return buildResultTy(ComparisonCategoryType::StrongOrdering);
10114 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10115 // TODO: Extend support for operator<=> to ObjC types.
10116 return InvalidOperands(Loc, LHS, RHS);
10120 if (!IsRelational && LHSIsNull != RHSIsNull) {
10121 bool IsEquality = Opc == BO_EQ;
10123 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10124 RHS.get()->getSourceRange());
10126 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10127 LHS.get()->getSourceRange());
10130 if ((LHSType->isIntegerType() && !LHSIsNull) ||
10131 (RHSType->isIntegerType() && !RHSIsNull)) {
10132 // Skip normal pointer conversion checks in this case; we have better
10133 // diagnostics for this below.
10134 } else if (getLangOpts().CPlusPlus) {
10135 // Equality comparison of a function pointer to a void pointer is invalid,
10136 // but we allow it as an extension.
10137 // FIXME: If we really want to allow this, should it be part of composite
10138 // pointer type computation so it works in conditionals too?
10139 if (!IsRelational &&
10140 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10141 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10142 // This is a gcc extension compatibility comparison.
10143 // In a SFINAE context, we treat this as a hard error to maintain
10144 // conformance with the C++ standard.
10145 diagnoseFunctionPointerToVoidComparison(
10146 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10148 if (isSFINAEContext())
10151 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10152 return computeResultTy();
10155 // C++ [expr.eq]p2:
10156 // If at least one operand is a pointer [...] bring them to their
10157 // composite pointer type.
10158 // C++ [expr.spaceship]p6
10159 // If at least one of the operands is of pointer type, [...] bring them
10160 // to their composite pointer type.
10161 // C++ [expr.rel]p2:
10162 // If both operands are pointers, [...] bring them to their composite
10164 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10165 (IsRelational ? 2 : 1) &&
10166 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10167 RHSType->isObjCObjectPointerType()))) {
10168 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10170 return computeResultTy();
10172 } else if (LHSType->isPointerType() &&
10173 RHSType->isPointerType()) { // C99 6.5.8p2
10174 // All of the following pointer-related warnings are GCC extensions, except
10175 // when handling null pointer constants.
10176 QualType LCanPointeeTy =
10177 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10178 QualType RCanPointeeTy =
10179 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10181 // C99 6.5.9p2 and C99 6.5.8p2
10182 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10183 RCanPointeeTy.getUnqualifiedType())) {
10184 // Valid unless a relational comparison of function pointers
10185 if (IsRelational && LCanPointeeTy->isFunctionType()) {
10186 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10187 << LHSType << RHSType << LHS.get()->getSourceRange()
10188 << RHS.get()->getSourceRange();
10190 } else if (!IsRelational &&
10191 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10192 // Valid unless comparison between non-null pointer and function pointer
10193 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10194 && !LHSIsNull && !RHSIsNull)
10195 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10199 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10201 if (LCanPointeeTy != RCanPointeeTy) {
10202 // Treat NULL constant as a special case in OpenCL.
10203 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10204 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10205 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10207 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10208 << LHSType << RHSType << 0 /* comparison */
10209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10212 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10213 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10214 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10216 if (LHSIsNull && !RHSIsNull)
10217 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10219 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10221 return computeResultTy();
10224 if (getLangOpts().CPlusPlus) {
10225 // C++ [expr.eq]p4:
10226 // Two operands of type std::nullptr_t or one operand of type
10227 // std::nullptr_t and the other a null pointer constant compare equal.
10228 if (!IsRelational && LHSIsNull && RHSIsNull) {
10229 if (LHSType->isNullPtrType()) {
10230 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10231 return computeResultTy();
10233 if (RHSType->isNullPtrType()) {
10234 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10235 return computeResultTy();
10239 // Comparison of Objective-C pointers and block pointers against nullptr_t.
10240 // These aren't covered by the composite pointer type rules.
10241 if (!IsRelational && RHSType->isNullPtrType() &&
10242 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10243 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10244 return computeResultTy();
10246 if (!IsRelational && LHSType->isNullPtrType() &&
10247 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10248 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10249 return computeResultTy();
10252 if (IsRelational &&
10253 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10254 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10255 // HACK: Relational comparison of nullptr_t against a pointer type is
10256 // invalid per DR583, but we allow it within std::less<> and friends,
10257 // since otherwise common uses of it break.
10258 // FIXME: Consider removing this hack once LWG fixes std::less<> and
10259 // friends to have std::nullptr_t overload candidates.
10260 DeclContext *DC = CurContext;
10261 if (isa<FunctionDecl>(DC))
10262 DC = DC->getParent();
10263 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10264 if (CTSD->isInStdNamespace() &&
10265 llvm::StringSwitch<bool>(CTSD->getName())
10266 .Cases("less", "less_equal", "greater", "greater_equal", true)
10268 if (RHSType->isNullPtrType())
10269 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10271 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10272 return computeResultTy();
10277 // C++ [expr.eq]p2:
10278 // If at least one operand is a pointer to member, [...] bring them to
10279 // their composite pointer type.
10280 if (!IsRelational &&
10281 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10282 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10285 return computeResultTy();
10289 // Handle block pointer types.
10290 if (!IsRelational && LHSType->isBlockPointerType() &&
10291 RHSType->isBlockPointerType()) {
10292 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10293 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10295 if (!LHSIsNull && !RHSIsNull &&
10296 !Context.typesAreCompatible(lpointee, rpointee)) {
10297 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10298 << LHSType << RHSType << LHS.get()->getSourceRange()
10299 << RHS.get()->getSourceRange();
10301 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10302 return computeResultTy();
10305 // Allow block pointers to be compared with null pointer constants.
10307 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10308 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10309 if (!LHSIsNull && !RHSIsNull) {
10310 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10311 ->getPointeeType()->isVoidType())
10312 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10313 ->getPointeeType()->isVoidType())))
10314 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10315 << LHSType << RHSType << LHS.get()->getSourceRange()
10316 << RHS.get()->getSourceRange();
10318 if (LHSIsNull && !RHSIsNull)
10319 LHS = ImpCastExprToType(LHS.get(), RHSType,
10320 RHSType->isPointerType() ? CK_BitCast
10321 : CK_AnyPointerToBlockPointerCast);
10323 RHS = ImpCastExprToType(RHS.get(), LHSType,
10324 LHSType->isPointerType() ? CK_BitCast
10325 : CK_AnyPointerToBlockPointerCast);
10326 return computeResultTy();
10329 if (LHSType->isObjCObjectPointerType() ||
10330 RHSType->isObjCObjectPointerType()) {
10331 const PointerType *LPT = LHSType->getAs<PointerType>();
10332 const PointerType *RPT = RHSType->getAs<PointerType>();
10334 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10335 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10337 if (!LPtrToVoid && !RPtrToVoid &&
10338 !Context.typesAreCompatible(LHSType, RHSType)) {
10339 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10342 if (LHSIsNull && !RHSIsNull) {
10343 Expr *E = LHS.get();
10344 if (getLangOpts().ObjCAutoRefCount)
10345 CheckObjCConversion(SourceRange(), RHSType, E,
10346 CCK_ImplicitConversion);
10347 LHS = ImpCastExprToType(E, RHSType,
10348 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10351 Expr *E = RHS.get();
10352 if (getLangOpts().ObjCAutoRefCount)
10353 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10355 /*DiagnoseCFAudited=*/false, Opc);
10356 RHS = ImpCastExprToType(E, LHSType,
10357 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10359 return computeResultTy();
10361 if (LHSType->isObjCObjectPointerType() &&
10362 RHSType->isObjCObjectPointerType()) {
10363 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10364 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10366 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10367 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10369 if (LHSIsNull && !RHSIsNull)
10370 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10372 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10373 return computeResultTy();
10376 if (!IsRelational && LHSType->isBlockPointerType() &&
10377 RHSType->isBlockCompatibleObjCPointerType(Context)) {
10378 LHS = ImpCastExprToType(LHS.get(), RHSType,
10379 CK_BlockPointerToObjCPointerCast);
10380 return computeResultTy();
10381 } else if (!IsRelational &&
10382 LHSType->isBlockCompatibleObjCPointerType(Context) &&
10383 RHSType->isBlockPointerType()) {
10384 RHS = ImpCastExprToType(RHS.get(), LHSType,
10385 CK_BlockPointerToObjCPointerCast);
10386 return computeResultTy();
10389 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10390 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10391 unsigned DiagID = 0;
10392 bool isError = false;
10393 if (LangOpts.DebuggerSupport) {
10394 // Under a debugger, allow the comparison of pointers to integers,
10395 // since users tend to want to compare addresses.
10396 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10397 (RHSIsNull && RHSType->isIntegerType())) {
10398 if (IsRelational) {
10399 isError = getLangOpts().CPlusPlus;
10401 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10402 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10404 } else if (getLangOpts().CPlusPlus) {
10405 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10407 } else if (IsRelational)
10408 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10410 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10414 << LHSType << RHSType << LHS.get()->getSourceRange()
10415 << RHS.get()->getSourceRange();
10420 if (LHSType->isIntegerType())
10421 LHS = ImpCastExprToType(LHS.get(), RHSType,
10422 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10424 RHS = ImpCastExprToType(RHS.get(), LHSType,
10425 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10426 return computeResultTy();
10429 // Handle block pointers.
10430 if (!IsRelational && RHSIsNull
10431 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10432 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10433 return computeResultTy();
10435 if (!IsRelational && LHSIsNull
10436 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10437 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10438 return computeResultTy();
10441 if (getLangOpts().OpenCLVersion >= 200) {
10442 if (LHSIsNull && RHSType->isQueueT()) {
10443 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10444 return computeResultTy();
10447 if (LHSType->isQueueT() && RHSIsNull) {
10448 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10449 return computeResultTy();
10453 return InvalidOperands(Loc, LHS, RHS);
10456 // Return a signed ext_vector_type that is of identical size and number of
10457 // elements. For floating point vectors, return an integer type of identical
10458 // size and number of elements. In the non ext_vector_type case, search from
10459 // the largest type to the smallest type to avoid cases where long long == long,
10460 // where long gets picked over long long.
10461 QualType Sema::GetSignedVectorType(QualType V) {
10462 const VectorType *VTy = V->getAs<VectorType>();
10463 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10465 if (isa<ExtVectorType>(VTy)) {
10466 if (TypeSize == Context.getTypeSize(Context.CharTy))
10467 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10468 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10469 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10470 else if (TypeSize == Context.getTypeSize(Context.IntTy))
10471 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10472 else if (TypeSize == Context.getTypeSize(Context.LongTy))
10473 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10474 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10475 "Unhandled vector element size in vector compare");
10476 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10479 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10480 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10481 VectorType::GenericVector);
10482 else if (TypeSize == Context.getTypeSize(Context.LongTy))
10483 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10484 VectorType::GenericVector);
10485 else if (TypeSize == Context.getTypeSize(Context.IntTy))
10486 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10487 VectorType::GenericVector);
10488 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10489 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10490 VectorType::GenericVector);
10491 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10492 "Unhandled vector element size in vector compare");
10493 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10494 VectorType::GenericVector);
10497 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10498 /// operates on extended vector types. Instead of producing an IntTy result,
10499 /// like a scalar comparison, a vector comparison produces a vector of integer
10501 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10502 SourceLocation Loc,
10503 BinaryOperatorKind Opc) {
10504 // Check to make sure we're operating on vectors of the same type and width,
10505 // Allowing one side to be a scalar of element type.
10506 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10507 /*AllowBothBool*/true,
10508 /*AllowBoolConversions*/getLangOpts().ZVector);
10509 if (vType.isNull())
10512 QualType LHSType = LHS.get()->getType();
10514 // If AltiVec, the comparison results in a numeric type, i.e.
10515 // bool for C++, int for C
10516 if (getLangOpts().AltiVec &&
10517 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10518 return Context.getLogicalOperationType();
10520 // For non-floating point types, check for self-comparisons of the form
10521 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
10522 // often indicate logic errors in the program.
10523 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10525 // Check for comparisons of floating point operands using != and ==.
10526 if (BinaryOperator::isEqualityOp(Opc) &&
10527 LHSType->hasFloatingRepresentation()) {
10528 assert(RHS.get()->getType()->hasFloatingRepresentation());
10529 CheckFloatComparison(Loc, LHS.get(), RHS.get());
10532 // Return a signed type for the vector.
10533 return GetSignedVectorType(vType);
10536 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10537 SourceLocation Loc) {
10538 // Ensure that either both operands are of the same vector type, or
10539 // one operand is of a vector type and the other is of its element type.
10540 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10541 /*AllowBothBool*/true,
10542 /*AllowBoolConversions*/false);
10543 if (vType.isNull())
10544 return InvalidOperands(Loc, LHS, RHS);
10545 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10546 vType->hasFloatingRepresentation())
10547 return InvalidOperands(Loc, LHS, RHS);
10548 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10549 // usage of the logical operators && and || with vectors in C. This
10550 // check could be notionally dropped.
10551 if (!getLangOpts().CPlusPlus &&
10552 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10553 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10555 return GetSignedVectorType(LHS.get()->getType());
10558 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10559 SourceLocation Loc,
10560 BinaryOperatorKind Opc) {
10561 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10563 bool IsCompAssign =
10564 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10566 if (LHS.get()->getType()->isVectorType() ||
10567 RHS.get()->getType()->isVectorType()) {
10568 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10569 RHS.get()->getType()->hasIntegerRepresentation())
10570 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10571 /*AllowBothBool*/true,
10572 /*AllowBoolConversions*/getLangOpts().ZVector);
10573 return InvalidOperands(Loc, LHS, RHS);
10577 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10579 ExprResult LHSResult = LHS, RHSResult = RHS;
10580 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10582 if (LHSResult.isInvalid() || RHSResult.isInvalid())
10584 LHS = LHSResult.get();
10585 RHS = RHSResult.get();
10587 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10589 return InvalidOperands(Loc, LHS, RHS);
10593 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10594 SourceLocation Loc,
10595 BinaryOperatorKind Opc) {
10596 // Check vector operands differently.
10597 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10598 return CheckVectorLogicalOperands(LHS, RHS, Loc);
10600 // Diagnose cases where the user write a logical and/or but probably meant a
10601 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
10603 if (LHS.get()->getType()->isIntegerType() &&
10604 !LHS.get()->getType()->isBooleanType() &&
10605 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10606 // Don't warn in macros or template instantiations.
10607 !Loc.isMacroID() && !inTemplateInstantiation()) {
10608 // If the RHS can be constant folded, and if it constant folds to something
10609 // that isn't 0 or 1 (which indicate a potential logical operation that
10610 // happened to fold to true/false) then warn.
10611 // Parens on the RHS are ignored.
10612 llvm::APSInt Result;
10613 if (RHS.get()->EvaluateAsInt(Result, Context))
10614 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10615 !RHS.get()->getExprLoc().isMacroID()) ||
10616 (Result != 0 && Result != 1)) {
10617 Diag(Loc, diag::warn_logical_instead_of_bitwise)
10618 << RHS.get()->getSourceRange()
10619 << (Opc == BO_LAnd ? "&&" : "||");
10620 // Suggest replacing the logical operator with the bitwise version
10621 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10622 << (Opc == BO_LAnd ? "&" : "|")
10623 << FixItHint::CreateReplacement(SourceRange(
10624 Loc, getLocForEndOfToken(Loc)),
10625 Opc == BO_LAnd ? "&" : "|");
10626 if (Opc == BO_LAnd)
10627 // Suggest replacing "Foo() && kNonZero" with "Foo()"
10628 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10629 << FixItHint::CreateRemoval(
10630 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10631 RHS.get()->getLocEnd()));
10635 if (!Context.getLangOpts().CPlusPlus) {
10636 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10637 // not operate on the built-in scalar and vector float types.
10638 if (Context.getLangOpts().OpenCL &&
10639 Context.getLangOpts().OpenCLVersion < 120) {
10640 if (LHS.get()->getType()->isFloatingType() ||
10641 RHS.get()->getType()->isFloatingType())
10642 return InvalidOperands(Loc, LHS, RHS);
10645 LHS = UsualUnaryConversions(LHS.get());
10646 if (LHS.isInvalid())
10649 RHS = UsualUnaryConversions(RHS.get());
10650 if (RHS.isInvalid())
10653 if (!LHS.get()->getType()->isScalarType() ||
10654 !RHS.get()->getType()->isScalarType())
10655 return InvalidOperands(Loc, LHS, RHS);
10657 return Context.IntTy;
10660 // The following is safe because we only use this method for
10661 // non-overloadable operands.
10663 // C++ [expr.log.and]p1
10664 // C++ [expr.log.or]p1
10665 // The operands are both contextually converted to type bool.
10666 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10667 if (LHSRes.isInvalid())
10668 return InvalidOperands(Loc, LHS, RHS);
10671 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10672 if (RHSRes.isInvalid())
10673 return InvalidOperands(Loc, LHS, RHS);
10676 // C++ [expr.log.and]p2
10677 // C++ [expr.log.or]p2
10678 // The result is a bool.
10679 return Context.BoolTy;
10682 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10683 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10684 if (!ME) return false;
10685 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10686 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10687 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10688 if (!Base) return false;
10689 return Base->getMethodDecl() != nullptr;
10692 /// Is the given expression (which must be 'const') a reference to a
10693 /// variable which was originally non-const, but which has become
10694 /// 'const' due to being captured within a block?
10695 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10696 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10697 assert(E->isLValue() && E->getType().isConstQualified());
10698 E = E->IgnoreParens();
10700 // Must be a reference to a declaration from an enclosing scope.
10701 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10702 if (!DRE) return NCCK_None;
10703 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10705 // The declaration must be a variable which is not declared 'const'.
10706 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10707 if (!var) return NCCK_None;
10708 if (var->getType().isConstQualified()) return NCCK_None;
10709 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10711 // Decide whether the first capture was for a block or a lambda.
10712 DeclContext *DC = S.CurContext, *Prev = nullptr;
10713 // Decide whether the first capture was for a block or a lambda.
10715 // For init-capture, it is possible that the variable belongs to the
10716 // template pattern of the current context.
10717 if (auto *FD = dyn_cast<FunctionDecl>(DC))
10718 if (var->isInitCapture() &&
10719 FD->getTemplateInstantiationPattern() == var->getDeclContext())
10721 if (DC == var->getDeclContext())
10724 DC = DC->getParent();
10726 // Unless we have an init-capture, we've gone one step too far.
10727 if (!var->isInitCapture())
10729 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10732 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10733 Ty = Ty.getNonReferenceType();
10734 if (IsDereference && Ty->isPointerType())
10735 Ty = Ty->getPointeeType();
10736 return !Ty.isConstQualified();
10739 // Update err_typecheck_assign_const and note_typecheck_assign_const
10740 // when this enum is changed.
10747 ConstUnknown, // Keep as last element
10750 /// Emit the "read-only variable not assignable" error and print notes to give
10751 /// more information about why the variable is not assignable, such as pointing
10752 /// to the declaration of a const variable, showing that a method is const, or
10753 /// that the function is returning a const reference.
10754 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10755 SourceLocation Loc) {
10756 SourceRange ExprRange = E->getSourceRange();
10758 // Only emit one error on the first const found. All other consts will emit
10759 // a note to the error.
10760 bool DiagnosticEmitted = false;
10762 // Track if the current expression is the result of a dereference, and if the
10763 // next checked expression is the result of a dereference.
10764 bool IsDereference = false;
10765 bool NextIsDereference = false;
10767 // Loop to process MemberExpr chains.
10769 IsDereference = NextIsDereference;
10771 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10772 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10773 NextIsDereference = ME->isArrow();
10774 const ValueDecl *VD = ME->getMemberDecl();
10775 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10776 // Mutable fields can be modified even if the class is const.
10777 if (Field->isMutable()) {
10778 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10782 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10783 if (!DiagnosticEmitted) {
10784 S.Diag(Loc, diag::err_typecheck_assign_const)
10785 << ExprRange << ConstMember << false /*static*/ << Field
10786 << Field->getType();
10787 DiagnosticEmitted = true;
10789 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10790 << ConstMember << false /*static*/ << Field << Field->getType()
10791 << Field->getSourceRange();
10795 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10796 if (VDecl->getType().isConstQualified()) {
10797 if (!DiagnosticEmitted) {
10798 S.Diag(Loc, diag::err_typecheck_assign_const)
10799 << ExprRange << ConstMember << true /*static*/ << VDecl
10800 << VDecl->getType();
10801 DiagnosticEmitted = true;
10803 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10804 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10805 << VDecl->getSourceRange();
10807 // Static fields do not inherit constness from parents.
10810 break; // End MemberExpr
10811 } else if (const ArraySubscriptExpr *ASE =
10812 dyn_cast<ArraySubscriptExpr>(E)) {
10813 E = ASE->getBase()->IgnoreParenImpCasts();
10815 } else if (const ExtVectorElementExpr *EVE =
10816 dyn_cast<ExtVectorElementExpr>(E)) {
10817 E = EVE->getBase()->IgnoreParenImpCasts();
10823 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10825 const FunctionDecl *FD = CE->getDirectCallee();
10826 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10827 if (!DiagnosticEmitted) {
10828 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10829 << ConstFunction << FD;
10830 DiagnosticEmitted = true;
10832 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10833 diag::note_typecheck_assign_const)
10834 << ConstFunction << FD << FD->getReturnType()
10835 << FD->getReturnTypeSourceRange();
10837 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10838 // Point to variable declaration.
10839 if (const ValueDecl *VD = DRE->getDecl()) {
10840 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10841 if (!DiagnosticEmitted) {
10842 S.Diag(Loc, diag::err_typecheck_assign_const)
10843 << ExprRange << ConstVariable << VD << VD->getType();
10844 DiagnosticEmitted = true;
10846 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10847 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10850 } else if (isa<CXXThisExpr>(E)) {
10851 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10852 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10853 if (MD->isConst()) {
10854 if (!DiagnosticEmitted) {
10855 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10856 << ConstMethod << MD;
10857 DiagnosticEmitted = true;
10859 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10860 << ConstMethod << MD << MD->getSourceRange();
10866 if (DiagnosticEmitted)
10869 // Can't determine a more specific message, so display the generic error.
10870 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10873 enum OriginalExprKind {
10879 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10880 const RecordType *Ty,
10881 SourceLocation Loc, SourceRange Range,
10882 OriginalExprKind OEK,
10883 bool &DiagnosticEmitted,
10884 bool IsNested = false) {
10885 // We walk the record hierarchy breadth-first to ensure that we print
10886 // diagnostics in field nesting order.
10887 // First, check every field for constness.
10888 for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10889 if (Field->getType().isConstQualified()) {
10890 if (!DiagnosticEmitted) {
10891 S.Diag(Loc, diag::err_typecheck_assign_const)
10892 << Range << NestedConstMember << OEK << VD
10893 << IsNested << Field;
10894 DiagnosticEmitted = true;
10896 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10897 << NestedConstMember << IsNested << Field
10898 << Field->getType() << Field->getSourceRange();
10902 for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10903 QualType FTy = Field->getType();
10904 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10905 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10906 OEK, DiagnosticEmitted, true);
10910 /// Emit an error for the case where a record we are trying to assign to has a
10911 /// const-qualified field somewhere in its hierarchy.
10912 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10913 SourceLocation Loc) {
10914 QualType Ty = E->getType();
10915 assert(Ty->isRecordType() && "lvalue was not record?");
10916 SourceRange Range = E->getSourceRange();
10917 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10918 bool DiagEmitted = false;
10920 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10921 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10922 Range, OEK_Member, DiagEmitted);
10923 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10924 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10925 Range, OEK_Variable, DiagEmitted);
10927 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10928 Range, OEK_LValue, DiagEmitted);
10930 DiagnoseConstAssignment(S, E, Loc);
10933 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
10934 /// emit an error and return true. If so, return false.
10935 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10936 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10938 S.CheckShadowingDeclModification(E, Loc);
10940 SourceLocation OrigLoc = Loc;
10941 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10943 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10944 IsLV = Expr::MLV_InvalidMessageExpression;
10945 if (IsLV == Expr::MLV_Valid)
10948 unsigned DiagID = 0;
10949 bool NeedType = false;
10950 switch (IsLV) { // C99 6.5.16p2
10951 case Expr::MLV_ConstQualified:
10952 // Use a specialized diagnostic when we're assigning to an object
10953 // from an enclosing function or block.
10954 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10955 if (NCCK == NCCK_Block)
10956 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10958 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10962 // In ARC, use some specialized diagnostics for occasions where we
10963 // infer 'const'. These are always pseudo-strong variables.
10964 if (S.getLangOpts().ObjCAutoRefCount) {
10965 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10966 if (declRef && isa<VarDecl>(declRef->getDecl())) {
10967 VarDecl *var = cast<VarDecl>(declRef->getDecl());
10969 // Use the normal diagnostic if it's pseudo-__strong but the
10970 // user actually wrote 'const'.
10971 if (var->isARCPseudoStrong() &&
10972 (!var->getTypeSourceInfo() ||
10973 !var->getTypeSourceInfo()->getType().isConstQualified())) {
10974 // There are two pseudo-strong cases:
10976 ObjCMethodDecl *method = S.getCurMethodDecl();
10977 if (method && var == method->getSelfDecl())
10978 DiagID = method->isClassMethod()
10979 ? diag::err_typecheck_arc_assign_self_class_method
10980 : diag::err_typecheck_arc_assign_self;
10982 // - fast enumeration variables
10984 DiagID = diag::err_typecheck_arr_assign_enumeration;
10986 SourceRange Assign;
10987 if (Loc != OrigLoc)
10988 Assign = SourceRange(OrigLoc, OrigLoc);
10989 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10990 // We need to preserve the AST regardless, so migration tool
10997 // If none of the special cases above are triggered, then this is a
10998 // simple const assignment.
11000 DiagnoseConstAssignment(S, E, Loc);
11005 case Expr::MLV_ConstAddrSpace:
11006 DiagnoseConstAssignment(S, E, Loc);
11008 case Expr::MLV_ConstQualifiedField:
11009 DiagnoseRecursiveConstFields(S, E, Loc);
11011 case Expr::MLV_ArrayType:
11012 case Expr::MLV_ArrayTemporary:
11013 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11016 case Expr::MLV_NotObjectType:
11017 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11020 case Expr::MLV_LValueCast:
11021 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11023 case Expr::MLV_Valid:
11024 llvm_unreachable("did not take early return for MLV_Valid");
11025 case Expr::MLV_InvalidExpression:
11026 case Expr::MLV_MemberFunction:
11027 case Expr::MLV_ClassTemporary:
11028 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11030 case Expr::MLV_IncompleteType:
11031 case Expr::MLV_IncompleteVoidType:
11032 return S.RequireCompleteType(Loc, E->getType(),
11033 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11034 case Expr::MLV_DuplicateVectorComponents:
11035 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11037 case Expr::MLV_NoSetterProperty:
11038 llvm_unreachable("readonly properties should be processed differently");
11039 case Expr::MLV_InvalidMessageExpression:
11040 DiagID = diag::err_readonly_message_assignment;
11042 case Expr::MLV_SubObjCPropertySetting:
11043 DiagID = diag::err_no_subobject_property_setting;
11047 SourceRange Assign;
11048 if (Loc != OrigLoc)
11049 Assign = SourceRange(OrigLoc, OrigLoc);
11051 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11053 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11057 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11058 SourceLocation Loc,
11060 if (Sema.inTemplateInstantiation())
11062 if (Sema.isUnevaluatedContext())
11064 if (Loc.isInvalid() || Loc.isMacroID())
11066 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11070 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11071 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11073 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11075 const ValueDecl *LHSDecl =
11076 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11077 const ValueDecl *RHSDecl =
11078 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11079 if (LHSDecl != RHSDecl)
11081 if (LHSDecl->getType().isVolatileQualified())
11083 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11084 if (RefTy->getPointeeType().isVolatileQualified())
11087 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11090 // Objective-C instance variables
11091 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11092 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11093 if (OL && OR && OL->getDecl() == OR->getDecl()) {
11094 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11095 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11096 if (RL && RR && RL->getDecl() == RR->getDecl())
11097 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11102 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11103 SourceLocation Loc,
11104 QualType CompoundType) {
11105 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11107 // Verify that LHS is a modifiable lvalue, and emit error if not.
11108 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11111 QualType LHSType = LHSExpr->getType();
11112 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11114 // OpenCL v1.2 s6.1.1.1 p2:
11115 // The half data type can only be used to declare a pointer to a buffer that
11116 // contains half values
11117 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11118 LHSType->isHalfType()) {
11119 Diag(Loc, diag::err_opencl_half_load_store) << 1
11120 << LHSType.getUnqualifiedType();
11124 AssignConvertType ConvTy;
11125 if (CompoundType.isNull()) {
11126 Expr *RHSCheck = RHS.get();
11128 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11130 QualType LHSTy(LHSType);
11131 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11132 if (RHS.isInvalid())
11134 // Special case of NSObject attributes on c-style pointer types.
11135 if (ConvTy == IncompatiblePointer &&
11136 ((Context.isObjCNSObjectType(LHSType) &&
11137 RHSType->isObjCObjectPointerType()) ||
11138 (Context.isObjCNSObjectType(RHSType) &&
11139 LHSType->isObjCObjectPointerType())))
11140 ConvTy = Compatible;
11142 if (ConvTy == Compatible &&
11143 LHSType->isObjCObjectType())
11144 Diag(Loc, diag::err_objc_object_assignment)
11147 // If the RHS is a unary plus or minus, check to see if they = and + are
11148 // right next to each other. If so, the user may have typo'd "x =+ 4"
11149 // instead of "x += 4".
11150 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11151 RHSCheck = ICE->getSubExpr();
11152 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11153 if ((UO->getOpcode() == UO_Plus ||
11154 UO->getOpcode() == UO_Minus) &&
11155 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11156 // Only if the two operators are exactly adjacent.
11157 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11158 // And there is a space or other character before the subexpr of the
11159 // unary +/-. We don't want to warn on "x=-1".
11160 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
11161 UO->getSubExpr()->getLocStart().isFileID()) {
11162 Diag(Loc, diag::warn_not_compound_assign)
11163 << (UO->getOpcode() == UO_Plus ? "+" : "-")
11164 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11168 if (ConvTy == Compatible) {
11169 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11170 // Warn about retain cycles where a block captures the LHS, but
11171 // not if the LHS is a simple variable into which the block is
11172 // being stored...unless that variable can be captured by reference!
11173 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11174 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11175 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11176 checkRetainCycles(LHSExpr, RHS.get());
11179 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11180 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11181 // It is safe to assign a weak reference into a strong variable.
11182 // Although this code can still have problems:
11183 // id x = self.weakProp;
11184 // id y = self.weakProp;
11185 // we do not warn to warn spuriously when 'x' and 'y' are on separate
11186 // paths through the function. This should be revisited if
11187 // -Wrepeated-use-of-weak is made flow-sensitive.
11188 // For ObjCWeak only, we do not warn if the assign is to a non-weak
11189 // variable, which will be valid for the current autorelease scope.
11190 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11191 RHS.get()->getLocStart()))
11192 getCurFunction()->markSafeWeakUse(RHS.get());
11194 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11195 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11199 // Compound assignment "x += y"
11200 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11203 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11204 RHS.get(), AA_Assigning))
11207 CheckForNullPointerDereference(*this, LHSExpr);
11209 // C99 6.5.16p3: The type of an assignment expression is the type of the
11210 // left operand unless the left operand has qualified type, in which case
11211 // it is the unqualified version of the type of the left operand.
11212 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11213 // is converted to the type of the assignment expression (above).
11214 // C++ 5.17p1: the type of the assignment expression is that of its left
11216 return (getLangOpts().CPlusPlus
11217 ? LHSType : LHSType.getUnqualifiedType());
11220 // Only ignore explicit casts to void.
11221 static bool IgnoreCommaOperand(const Expr *E) {
11222 E = E->IgnoreParens();
11224 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11225 if (CE->getCastKind() == CK_ToVoid) {
11233 // Look for instances where it is likely the comma operator is confused with
11234 // another operator. There is a whitelist of acceptable expressions for the
11235 // left hand side of the comma operator, otherwise emit a warning.
11236 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11237 // No warnings in macros
11238 if (Loc.isMacroID())
11241 // Don't warn in template instantiations.
11242 if (inTemplateInstantiation())
11245 // Scope isn't fine-grained enough to whitelist the specific cases, so
11246 // instead, skip more than needed, then call back into here with the
11247 // CommaVisitor in SemaStmt.cpp.
11248 // The whitelisted locations are the initialization and increment portions
11249 // of a for loop. The additional checks are on the condition of
11250 // if statements, do/while loops, and for loops.
11251 const unsigned ForIncrementFlags =
11252 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
11253 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11254 const unsigned ScopeFlags = getCurScope()->getFlags();
11255 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11256 (ScopeFlags & ForInitFlags) == ForInitFlags)
11259 // If there are multiple comma operators used together, get the RHS of the
11260 // of the comma operator as the LHS.
11261 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11262 if (BO->getOpcode() != BO_Comma)
11264 LHS = BO->getRHS();
11267 // Only allow some expressions on LHS to not warn.
11268 if (IgnoreCommaOperand(LHS))
11271 Diag(Loc, diag::warn_comma_operator);
11272 Diag(LHS->getLocStart(), diag::note_cast_to_void)
11273 << LHS->getSourceRange()
11274 << FixItHint::CreateInsertion(LHS->getLocStart(),
11275 LangOpts.CPlusPlus ? "static_cast<void>("
11277 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
11282 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11283 SourceLocation Loc) {
11284 LHS = S.CheckPlaceholderExpr(LHS.get());
11285 RHS = S.CheckPlaceholderExpr(RHS.get());
11286 if (LHS.isInvalid() || RHS.isInvalid())
11289 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11290 // operands, but not unary promotions.
11291 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11293 // So we treat the LHS as a ignored value, and in C++ we allow the
11294 // containing site to determine what should be done with the RHS.
11295 LHS = S.IgnoredValueConversions(LHS.get());
11296 if (LHS.isInvalid())
11299 S.DiagnoseUnusedExprResult(LHS.get());
11301 if (!S.getLangOpts().CPlusPlus) {
11302 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11303 if (RHS.isInvalid())
11305 if (!RHS.get()->getType()->isVoidType())
11306 S.RequireCompleteType(Loc, RHS.get()->getType(),
11307 diag::err_incomplete_type);
11310 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11311 S.DiagnoseCommaOperator(LHS.get(), Loc);
11313 return RHS.get()->getType();
11316 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11317 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11318 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11320 ExprObjectKind &OK,
11321 SourceLocation OpLoc,
11322 bool IsInc, bool IsPrefix) {
11323 if (Op->isTypeDependent())
11324 return S.Context.DependentTy;
11326 QualType ResType = Op->getType();
11327 // Atomic types can be used for increment / decrement where the non-atomic
11328 // versions can, so ignore the _Atomic() specifier for the purpose of
11330 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11331 ResType = ResAtomicType->getValueType();
11333 assert(!ResType.isNull() && "no type for increment/decrement expression");
11335 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11336 // Decrement of bool is not allowed.
11338 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11341 // Increment of bool sets it to true, but is deprecated.
11342 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11343 : diag::warn_increment_bool)
11344 << Op->getSourceRange();
11345 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11346 // Error on enum increments and decrements in C++ mode
11347 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11349 } else if (ResType->isRealType()) {
11351 } else if (ResType->isPointerType()) {
11352 // C99 6.5.2.4p2, 6.5.6p2
11353 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11355 } else if (ResType->isObjCObjectPointerType()) {
11356 // On modern runtimes, ObjC pointer arithmetic is forbidden.
11357 // Otherwise, we just need a complete type.
11358 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11359 checkArithmeticOnObjCPointer(S, OpLoc, Op))
11361 } else if (ResType->isAnyComplexType()) {
11362 // C99 does not support ++/-- on complex types, we allow as an extension.
11363 S.Diag(OpLoc, diag::ext_integer_increment_complex)
11364 << ResType << Op->getSourceRange();
11365 } else if (ResType->isPlaceholderType()) {
11366 ExprResult PR = S.CheckPlaceholderExpr(Op);
11367 if (PR.isInvalid()) return QualType();
11368 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11370 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11371 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11372 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11373 (ResType->getAs<VectorType>()->getVectorKind() !=
11374 VectorType::AltiVecBool)) {
11375 // The z vector extensions allow ++ and -- for non-bool vectors.
11376 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11377 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11378 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11380 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11381 << ResType << int(IsInc) << Op->getSourceRange();
11384 // At this point, we know we have a real, complex or pointer type.
11385 // Now make sure the operand is a modifiable lvalue.
11386 if (CheckForModifiableLvalue(Op, OpLoc, S))
11388 // In C++, a prefix increment is the same type as the operand. Otherwise
11389 // (in C or with postfix), the increment is the unqualified type of the
11391 if (IsPrefix && S.getLangOpts().CPlusPlus) {
11393 OK = Op->getObjectKind();
11397 return ResType.getUnqualifiedType();
11402 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11403 /// This routine allows us to typecheck complex/recursive expressions
11404 /// where the declaration is needed for type checking. We only need to
11405 /// handle cases when the expression references a function designator
11406 /// or is an lvalue. Here are some examples:
11408 /// - &*****f => f for f a function designator.
11410 /// - &s.zz[1].yy -> s, if zz is an array
11411 /// - *(x + 1) -> x, if x is an array
11412 /// - &"123"[2] -> 0
11413 /// - & __real__ x -> x
11414 static ValueDecl *getPrimaryDecl(Expr *E) {
11415 switch (E->getStmtClass()) {
11416 case Stmt::DeclRefExprClass:
11417 return cast<DeclRefExpr>(E)->getDecl();
11418 case Stmt::MemberExprClass:
11419 // If this is an arrow operator, the address is an offset from
11420 // the base's value, so the object the base refers to is
11422 if (cast<MemberExpr>(E)->isArrow())
11424 // Otherwise, the expression refers to a part of the base
11425 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11426 case Stmt::ArraySubscriptExprClass: {
11427 // FIXME: This code shouldn't be necessary! We should catch the implicit
11428 // promotion of register arrays earlier.
11429 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11430 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11431 if (ICE->getSubExpr()->getType()->isArrayType())
11432 return getPrimaryDecl(ICE->getSubExpr());
11436 case Stmt::UnaryOperatorClass: {
11437 UnaryOperator *UO = cast<UnaryOperator>(E);
11439 switch(UO->getOpcode()) {
11443 return getPrimaryDecl(UO->getSubExpr());
11448 case Stmt::ParenExprClass:
11449 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11450 case Stmt::ImplicitCastExprClass:
11451 // If the result of an implicit cast is an l-value, we care about
11452 // the sub-expression; otherwise, the result here doesn't matter.
11453 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11462 AO_Vector_Element = 1,
11463 AO_Property_Expansion = 2,
11464 AO_Register_Variable = 3,
11468 /// Diagnose invalid operand for address of operations.
11470 /// \param Type The type of operand which cannot have its address taken.
11471 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11472 Expr *E, unsigned Type) {
11473 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11476 /// CheckAddressOfOperand - The operand of & must be either a function
11477 /// designator or an lvalue designating an object. If it is an lvalue, the
11478 /// object cannot be declared with storage class register or be a bit field.
11479 /// Note: The usual conversions are *not* applied to the operand of the &
11480 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11481 /// In C++, the operand might be an overloaded function name, in which case
11482 /// we allow the '&' but retain the overloaded-function type.
11483 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11484 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11485 if (PTy->getKind() == BuiltinType::Overload) {
11486 Expr *E = OrigOp.get()->IgnoreParens();
11487 if (!isa<OverloadExpr>(E)) {
11488 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11489 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11490 << OrigOp.get()->getSourceRange();
11494 OverloadExpr *Ovl = cast<OverloadExpr>(E);
11495 if (isa<UnresolvedMemberExpr>(Ovl))
11496 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11497 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11498 << OrigOp.get()->getSourceRange();
11502 return Context.OverloadTy;
11505 if (PTy->getKind() == BuiltinType::UnknownAny)
11506 return Context.UnknownAnyTy;
11508 if (PTy->getKind() == BuiltinType::BoundMember) {
11509 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11510 << OrigOp.get()->getSourceRange();
11514 OrigOp = CheckPlaceholderExpr(OrigOp.get());
11515 if (OrigOp.isInvalid()) return QualType();
11518 if (OrigOp.get()->isTypeDependent())
11519 return Context.DependentTy;
11521 assert(!OrigOp.get()->getType()->isPlaceholderType());
11523 // Make sure to ignore parentheses in subsequent checks
11524 Expr *op = OrigOp.get()->IgnoreParens();
11526 // In OpenCL captures for blocks called as lambda functions
11527 // are located in the private address space. Blocks used in
11528 // enqueue_kernel can be located in a different address space
11529 // depending on a vendor implementation. Thus preventing
11530 // taking an address of the capture to avoid invalid AS casts.
11531 if (LangOpts.OpenCL) {
11532 auto* VarRef = dyn_cast<DeclRefExpr>(op);
11533 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11534 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11539 if (getLangOpts().C99) {
11540 // Implement C99-only parts of addressof rules.
11541 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11542 if (uOp->getOpcode() == UO_Deref)
11543 // Per C99 6.5.3.2, the address of a deref always returns a valid result
11544 // (assuming the deref expression is valid).
11545 return uOp->getSubExpr()->getType();
11547 // Technically, there should be a check for array subscript
11548 // expressions here, but the result of one is always an lvalue anyway.
11550 ValueDecl *dcl = getPrimaryDecl(op);
11552 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11553 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11554 op->getLocStart()))
11557 Expr::LValueClassification lval = op->ClassifyLValue(Context);
11558 unsigned AddressOfError = AO_No_Error;
11560 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11561 bool sfinae = (bool)isSFINAEContext();
11562 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11563 : diag::ext_typecheck_addrof_temporary)
11564 << op->getType() << op->getSourceRange();
11567 // Materialize the temporary as an lvalue so that we can take its address.
11569 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11570 } else if (isa<ObjCSelectorExpr>(op)) {
11571 return Context.getPointerType(op->getType());
11572 } else if (lval == Expr::LV_MemberFunction) {
11573 // If it's an instance method, make a member pointer.
11574 // The expression must have exactly the form &A::foo.
11576 // If the underlying expression isn't a decl ref, give up.
11577 if (!isa<DeclRefExpr>(op)) {
11578 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11579 << OrigOp.get()->getSourceRange();
11582 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11583 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11585 // The id-expression was parenthesized.
11586 if (OrigOp.get() != DRE) {
11587 Diag(OpLoc, diag::err_parens_pointer_member_function)
11588 << OrigOp.get()->getSourceRange();
11590 // The method was named without a qualifier.
11591 } else if (!DRE->getQualifier()) {
11592 if (MD->getParent()->getName().empty())
11593 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11594 << op->getSourceRange();
11596 SmallString<32> Str;
11597 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11598 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11599 << op->getSourceRange()
11600 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11604 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11605 if (isa<CXXDestructorDecl>(MD))
11606 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11608 QualType MPTy = Context.getMemberPointerType(
11609 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11610 // Under the MS ABI, lock down the inheritance model now.
11611 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11612 (void)isCompleteType(OpLoc, MPTy);
11614 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11616 // The operand must be either an l-value or a function designator
11617 if (!op->getType()->isFunctionType()) {
11618 // Use a special diagnostic for loads from property references.
11619 if (isa<PseudoObjectExpr>(op)) {
11620 AddressOfError = AO_Property_Expansion;
11622 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11623 << op->getType() << op->getSourceRange();
11627 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11628 // The operand cannot be a bit-field
11629 AddressOfError = AO_Bit_Field;
11630 } else if (op->getObjectKind() == OK_VectorComponent) {
11631 // The operand cannot be an element of a vector
11632 AddressOfError = AO_Vector_Element;
11633 } else if (dcl) { // C99 6.5.3.2p1
11634 // We have an lvalue with a decl. Make sure the decl is not declared
11635 // with the register storage-class specifier.
11636 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11637 // in C++ it is not error to take address of a register
11638 // variable (c++03 7.1.1P3)
11639 if (vd->getStorageClass() == SC_Register &&
11640 !getLangOpts().CPlusPlus) {
11641 AddressOfError = AO_Register_Variable;
11643 } else if (isa<MSPropertyDecl>(dcl)) {
11644 AddressOfError = AO_Property_Expansion;
11645 } else if (isa<FunctionTemplateDecl>(dcl)) {
11646 return Context.OverloadTy;
11647 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11648 // Okay: we can take the address of a field.
11649 // Could be a pointer to member, though, if there is an explicit
11650 // scope qualifier for the class.
11651 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11652 DeclContext *Ctx = dcl->getDeclContext();
11653 if (Ctx && Ctx->isRecord()) {
11654 if (dcl->getType()->isReferenceType()) {
11656 diag::err_cannot_form_pointer_to_member_of_reference_type)
11657 << dcl->getDeclName() << dcl->getType();
11661 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11662 Ctx = Ctx->getParent();
11664 QualType MPTy = Context.getMemberPointerType(
11666 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11667 // Under the MS ABI, lock down the inheritance model now.
11668 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11669 (void)isCompleteType(OpLoc, MPTy);
11673 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11674 !isa<BindingDecl>(dcl))
11675 llvm_unreachable("Unknown/unexpected decl type");
11678 if (AddressOfError != AO_No_Error) {
11679 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11683 if (lval == Expr::LV_IncompleteVoidType) {
11684 // Taking the address of a void variable is technically illegal, but we
11685 // allow it in cases which are otherwise valid.
11686 // Example: "extern void x; void* y = &x;".
11687 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11690 // If the operand has type "type", the result has type "pointer to type".
11691 if (op->getType()->isObjCObjectType())
11692 return Context.getObjCObjectPointerType(op->getType());
11694 CheckAddressOfPackedMember(op);
11696 return Context.getPointerType(op->getType());
11699 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11700 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11703 const Decl *D = DRE->getDecl();
11706 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11709 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11710 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11712 if (FunctionScopeInfo *FD = S.getCurFunction())
11713 if (!FD->ModifiedNonNullParams.count(Param))
11714 FD->ModifiedNonNullParams.insert(Param);
11717 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11718 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11719 SourceLocation OpLoc) {
11720 if (Op->isTypeDependent())
11721 return S.Context.DependentTy;
11723 ExprResult ConvResult = S.UsualUnaryConversions(Op);
11724 if (ConvResult.isInvalid())
11726 Op = ConvResult.get();
11727 QualType OpTy = Op->getType();
11730 if (isa<CXXReinterpretCastExpr>(Op)) {
11731 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11732 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11733 Op->getSourceRange());
11736 if (const PointerType *PT = OpTy->getAs<PointerType>())
11738 Result = PT->getPointeeType();
11740 else if (const ObjCObjectPointerType *OPT =
11741 OpTy->getAs<ObjCObjectPointerType>())
11742 Result = OPT->getPointeeType();
11744 ExprResult PR = S.CheckPlaceholderExpr(Op);
11745 if (PR.isInvalid()) return QualType();
11746 if (PR.get() != Op)
11747 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11750 if (Result.isNull()) {
11751 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11752 << OpTy << Op->getSourceRange();
11756 // Note that per both C89 and C99, indirection is always legal, even if Result
11757 // is an incomplete type or void. It would be possible to warn about
11758 // dereferencing a void pointer, but it's completely well-defined, and such a
11759 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11760 // for pointers to 'void' but is fine for any other pointer type:
11762 // C++ [expr.unary.op]p1:
11763 // [...] the expression to which [the unary * operator] is applied shall
11764 // be a pointer to an object type, or a pointer to a function type
11765 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11766 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11767 << OpTy << Op->getSourceRange();
11769 // Dereferences are usually l-values...
11772 // ...except that certain expressions are never l-values in C.
11773 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11779 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11780 BinaryOperatorKind Opc;
11782 default: llvm_unreachable("Unknown binop!");
11783 case tok::periodstar: Opc = BO_PtrMemD; break;
11784 case tok::arrowstar: Opc = BO_PtrMemI; break;
11785 case tok::star: Opc = BO_Mul; break;
11786 case tok::slash: Opc = BO_Div; break;
11787 case tok::percent: Opc = BO_Rem; break;
11788 case tok::plus: Opc = BO_Add; break;
11789 case tok::minus: Opc = BO_Sub; break;
11790 case tok::lessless: Opc = BO_Shl; break;
11791 case tok::greatergreater: Opc = BO_Shr; break;
11792 case tok::lessequal: Opc = BO_LE; break;
11793 case tok::less: Opc = BO_LT; break;
11794 case tok::greaterequal: Opc = BO_GE; break;
11795 case tok::greater: Opc = BO_GT; break;
11796 case tok::exclaimequal: Opc = BO_NE; break;
11797 case tok::equalequal: Opc = BO_EQ; break;
11798 case tok::spaceship: Opc = BO_Cmp; break;
11799 case tok::amp: Opc = BO_And; break;
11800 case tok::caret: Opc = BO_Xor; break;
11801 case tok::pipe: Opc = BO_Or; break;
11802 case tok::ampamp: Opc = BO_LAnd; break;
11803 case tok::pipepipe: Opc = BO_LOr; break;
11804 case tok::equal: Opc = BO_Assign; break;
11805 case tok::starequal: Opc = BO_MulAssign; break;
11806 case tok::slashequal: Opc = BO_DivAssign; break;
11807 case tok::percentequal: Opc = BO_RemAssign; break;
11808 case tok::plusequal: Opc = BO_AddAssign; break;
11809 case tok::minusequal: Opc = BO_SubAssign; break;
11810 case tok::lesslessequal: Opc = BO_ShlAssign; break;
11811 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
11812 case tok::ampequal: Opc = BO_AndAssign; break;
11813 case tok::caretequal: Opc = BO_XorAssign; break;
11814 case tok::pipeequal: Opc = BO_OrAssign; break;
11815 case tok::comma: Opc = BO_Comma; break;
11820 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11821 tok::TokenKind Kind) {
11822 UnaryOperatorKind Opc;
11824 default: llvm_unreachable("Unknown unary op!");
11825 case tok::plusplus: Opc = UO_PreInc; break;
11826 case tok::minusminus: Opc = UO_PreDec; break;
11827 case tok::amp: Opc = UO_AddrOf; break;
11828 case tok::star: Opc = UO_Deref; break;
11829 case tok::plus: Opc = UO_Plus; break;
11830 case tok::minus: Opc = UO_Minus; break;
11831 case tok::tilde: Opc = UO_Not; break;
11832 case tok::exclaim: Opc = UO_LNot; break;
11833 case tok::kw___real: Opc = UO_Real; break;
11834 case tok::kw___imag: Opc = UO_Imag; break;
11835 case tok::kw___extension__: Opc = UO_Extension; break;
11840 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11841 /// This warning suppressed in the event of macro expansions.
11842 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11843 SourceLocation OpLoc, bool IsBuiltin) {
11844 if (S.inTemplateInstantiation())
11846 if (S.isUnevaluatedContext())
11848 if (OpLoc.isInvalid() || OpLoc.isMacroID())
11850 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11851 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11852 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11853 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11854 if (!LHSDeclRef || !RHSDeclRef ||
11855 LHSDeclRef->getLocation().isMacroID() ||
11856 RHSDeclRef->getLocation().isMacroID())
11858 const ValueDecl *LHSDecl =
11859 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11860 const ValueDecl *RHSDecl =
11861 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11862 if (LHSDecl != RHSDecl)
11864 if (LHSDecl->getType().isVolatileQualified())
11866 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11867 if (RefTy->getPointeeType().isVolatileQualified())
11870 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11871 : diag::warn_self_assignment_overloaded)
11872 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11873 << RHSExpr->getSourceRange();
11876 /// Check if a bitwise-& is performed on an Objective-C pointer. This
11877 /// is usually indicative of introspection within the Objective-C pointer.
11878 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11879 SourceLocation OpLoc) {
11880 if (!S.getLangOpts().ObjC1)
11883 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11884 const Expr *LHS = L.get();
11885 const Expr *RHS = R.get();
11887 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11888 ObjCPointerExpr = LHS;
11891 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11892 ObjCPointerExpr = RHS;
11896 // This warning is deliberately made very specific to reduce false
11897 // positives with logic that uses '&' for hashing. This logic mainly
11898 // looks for code trying to introspect into tagged pointers, which
11899 // code should generally never do.
11900 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11901 unsigned Diag = diag::warn_objc_pointer_masking;
11902 // Determine if we are introspecting the result of performSelectorXXX.
11903 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11904 // Special case messages to -performSelector and friends, which
11905 // can return non-pointer values boxed in a pointer value.
11906 // Some clients may wish to silence warnings in this subcase.
11907 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11908 Selector S = ME->getSelector();
11909 StringRef SelArg0 = S.getNameForSlot(0);
11910 if (SelArg0.startswith("performSelector"))
11911 Diag = diag::warn_objc_pointer_masking_performSelector;
11914 S.Diag(OpLoc, Diag)
11915 << ObjCPointerExpr->getSourceRange();
11919 static NamedDecl *getDeclFromExpr(Expr *E) {
11922 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11923 return DRE->getDecl();
11924 if (auto *ME = dyn_cast<MemberExpr>(E))
11925 return ME->getMemberDecl();
11926 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11927 return IRE->getDecl();
11931 // This helper function promotes a binary operator's operands (which are of a
11932 // half vector type) to a vector of floats and then truncates the result to
11933 // a vector of either half or short.
11934 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11935 BinaryOperatorKind Opc, QualType ResultTy,
11936 ExprValueKind VK, ExprObjectKind OK,
11937 bool IsCompAssign, SourceLocation OpLoc,
11938 FPOptions FPFeatures) {
11939 auto &Context = S.getASTContext();
11940 assert((isVector(ResultTy, Context.HalfTy) ||
11941 isVector(ResultTy, Context.ShortTy)) &&
11942 "Result must be a vector of half or short");
11943 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11944 isVector(RHS.get()->getType(), Context.HalfTy) &&
11945 "both operands expected to be a half vector");
11947 RHS = convertVector(RHS.get(), Context.FloatTy, S);
11948 QualType BinOpResTy = RHS.get()->getType();
11950 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11951 // change BinOpResTy to a vector of ints.
11952 if (isVector(ResultTy, Context.ShortTy))
11953 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11956 return new (Context) CompoundAssignOperator(
11957 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11958 OpLoc, FPFeatures);
11960 LHS = convertVector(LHS.get(), Context.FloatTy, S);
11961 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11962 VK, OK, OpLoc, FPFeatures);
11963 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11966 static std::pair<ExprResult, ExprResult>
11967 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11969 ExprResult LHS = LHSExpr, RHS = RHSExpr;
11970 if (!S.getLangOpts().CPlusPlus) {
11971 // C cannot handle TypoExpr nodes on either side of a binop because it
11972 // doesn't handle dependent types properly, so make sure any TypoExprs have
11973 // been dealt with before checking the operands.
11974 LHS = S.CorrectDelayedTyposInExpr(LHS);
11975 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11976 if (Opc != BO_Assign)
11977 return ExprResult(E);
11978 // Avoid correcting the RHS to the same Expr as the LHS.
11979 Decl *D = getDeclFromExpr(E);
11980 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11983 return std::make_pair(LHS, RHS);
11986 /// Returns true if conversion between vectors of halfs and vectors of floats
11988 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11989 QualType SrcType) {
11990 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11991 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11992 isVector(SrcType, Ctx.HalfTy);
11995 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11996 /// operator @p Opc at location @c TokLoc. This routine only supports
11997 /// built-in operations; ActOnBinOp handles overloaded operators.
11998 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11999 BinaryOperatorKind Opc,
12000 Expr *LHSExpr, Expr *RHSExpr) {
12001 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12002 // The syntax only allows initializer lists on the RHS of assignment,
12003 // so we don't need to worry about accepting invalid code for
12004 // non-assignment operators.
12006 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12007 // of x = {} is x = T().
12008 InitializationKind Kind = InitializationKind::CreateDirectList(
12009 RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
12010 InitializedEntity Entity =
12011 InitializedEntity::InitializeTemporary(LHSExpr->getType());
12012 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12013 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12014 if (Init.isInvalid())
12016 RHSExpr = Init.get();
12019 ExprResult LHS = LHSExpr, RHS = RHSExpr;
12020 QualType ResultTy; // Result type of the binary operator.
12021 // The following two variables are used for compound assignment operators
12022 QualType CompLHSTy; // Type of LHS after promotions for computation
12023 QualType CompResultTy; // Type of computation result
12024 ExprValueKind VK = VK_RValue;
12025 ExprObjectKind OK = OK_Ordinary;
12026 bool ConvertHalfVec = false;
12028 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12029 if (!LHS.isUsable() || !RHS.isUsable())
12030 return ExprError();
12032 if (getLangOpts().OpenCL) {
12033 QualType LHSTy = LHSExpr->getType();
12034 QualType RHSTy = RHSExpr->getType();
12035 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12036 // the ATOMIC_VAR_INIT macro.
12037 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12038 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
12039 if (BO_Assign == Opc)
12040 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12042 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12043 return ExprError();
12046 // OpenCL special types - image, sampler, pipe, and blocks are to be used
12047 // only with a builtin functions and therefore should be disallowed here.
12048 if (LHSTy->isImageType() || RHSTy->isImageType() ||
12049 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12050 LHSTy->isPipeType() || RHSTy->isPipeType() ||
12051 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12052 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12053 return ExprError();
12059 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12060 if (getLangOpts().CPlusPlus &&
12061 LHS.get()->getObjectKind() != OK_ObjCProperty) {
12062 VK = LHS.get()->getValueKind();
12063 OK = LHS.get()->getObjectKind();
12065 if (!ResultTy.isNull()) {
12066 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12067 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12069 RecordModifiableNonNullParam(*this, LHS.get());
12073 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12074 Opc == BO_PtrMemI);
12078 ConvertHalfVec = true;
12079 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12083 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12086 ConvertHalfVec = true;
12087 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12090 ConvertHalfVec = true;
12091 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12095 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12101 ConvertHalfVec = true;
12102 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12106 ConvertHalfVec = true;
12107 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12110 ConvertHalfVec = true;
12111 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12112 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12115 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12119 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12123 ConvertHalfVec = true;
12124 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12128 ConvertHalfVec = true;
12129 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12130 Opc == BO_DivAssign);
12131 CompLHSTy = CompResultTy;
12132 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12133 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12136 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12137 CompLHSTy = CompResultTy;
12138 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12139 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12142 ConvertHalfVec = true;
12143 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12144 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12145 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12148 ConvertHalfVec = true;
12149 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12150 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12151 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12155 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12156 CompLHSTy = CompResultTy;
12157 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12158 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12161 case BO_OrAssign: // fallthrough
12162 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12165 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12166 CompLHSTy = CompResultTy;
12167 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12168 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12171 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12172 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12173 VK = RHS.get()->getValueKind();
12174 OK = RHS.get()->getObjectKind();
12178 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12179 return ExprError();
12181 // Some of the binary operations require promoting operands of half vector to
12182 // float vectors and truncating the result back to half vector. For now, we do
12183 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12185 assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12186 isVector(LHS.get()->getType(), Context.HalfTy) &&
12187 "both sides are half vectors or neither sides are");
12188 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12189 LHS.get()->getType());
12191 // Check for array bounds violations for both sides of the BinaryOperator
12192 CheckArrayAccess(LHS.get());
12193 CheckArrayAccess(RHS.get());
12195 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12196 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12197 &Context.Idents.get("object_setClass"),
12198 SourceLocation(), LookupOrdinaryName);
12199 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12200 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
12201 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
12202 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
12203 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
12204 FixItHint::CreateInsertion(RHSLocEnd, ")");
12207 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12209 else if (const ObjCIvarRefExpr *OIRE =
12210 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12211 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12213 // Opc is not a compound assignment if CompResultTy is null.
12214 if (CompResultTy.isNull()) {
12215 if (ConvertHalfVec)
12216 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12217 OpLoc, FPFeatures);
12218 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12219 OK, OpLoc, FPFeatures);
12222 // Handle compound assignments.
12223 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12226 OK = LHS.get()->getObjectKind();
12229 if (ConvertHalfVec)
12230 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12231 OpLoc, FPFeatures);
12233 return new (Context) CompoundAssignOperator(
12234 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12235 OpLoc, FPFeatures);
12238 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12239 /// operators are mixed in a way that suggests that the programmer forgot that
12240 /// comparison operators have higher precedence. The most typical example of
12241 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12242 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12243 SourceLocation OpLoc, Expr *LHSExpr,
12245 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12246 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12248 // Check that one of the sides is a comparison operator and the other isn't.
12249 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12250 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12251 if (isLeftComp == isRightComp)
12254 // Bitwise operations are sometimes used as eager logical ops.
12255 // Don't diagnose this.
12256 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12257 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12258 if (isLeftBitwise || isRightBitwise)
12261 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
12263 : SourceRange(OpLoc, RHSExpr->getLocEnd());
12264 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12265 SourceRange ParensRange = isLeftComp ?
12266 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
12267 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
12269 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12270 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12271 SuggestParentheses(Self, OpLoc,
12272 Self.PDiag(diag::note_precedence_silence) << OpStr,
12273 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12274 SuggestParentheses(Self, OpLoc,
12275 Self.PDiag(diag::note_precedence_bitwise_first)
12276 << BinaryOperator::getOpcodeStr(Opc),
12280 /// It accepts a '&&' expr that is inside a '||' one.
12281 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12282 /// in parentheses.
12284 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12285 BinaryOperator *Bop) {
12286 assert(Bop->getOpcode() == BO_LAnd);
12287 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12288 << Bop->getSourceRange() << OpLoc;
12289 SuggestParentheses(Self, Bop->getOperatorLoc(),
12290 Self.PDiag(diag::note_precedence_silence)
12291 << Bop->getOpcodeStr(),
12292 Bop->getSourceRange());
12295 /// Returns true if the given expression can be evaluated as a constant
12297 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12299 return !E->isValueDependent() &&
12300 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12303 /// Returns true if the given expression can be evaluated as a constant
12305 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12307 return !E->isValueDependent() &&
12308 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12311 /// Look for '&&' in the left hand of a '||' expr.
12312 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12313 Expr *LHSExpr, Expr *RHSExpr) {
12314 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12315 if (Bop->getOpcode() == BO_LAnd) {
12316 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12317 if (EvaluatesAsFalse(S, RHSExpr))
12319 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12320 if (!EvaluatesAsTrue(S, Bop->getLHS()))
12321 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12322 } else if (Bop->getOpcode() == BO_LOr) {
12323 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12324 // If it's "a || b && 1 || c" we didn't warn earlier for
12325 // "a || b && 1", but warn now.
12326 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12327 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12333 /// Look for '&&' in the right hand of a '||' expr.
12334 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12335 Expr *LHSExpr, Expr *RHSExpr) {
12336 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12337 if (Bop->getOpcode() == BO_LAnd) {
12338 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12339 if (EvaluatesAsFalse(S, LHSExpr))
12341 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12342 if (!EvaluatesAsTrue(S, Bop->getRHS()))
12343 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12348 /// Look for bitwise op in the left or right hand of a bitwise op with
12349 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12350 /// the '&' expression in parentheses.
12351 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12352 SourceLocation OpLoc, Expr *SubExpr) {
12353 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12354 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12355 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12356 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12357 << Bop->getSourceRange() << OpLoc;
12358 SuggestParentheses(S, Bop->getOperatorLoc(),
12359 S.PDiag(diag::note_precedence_silence)
12360 << Bop->getOpcodeStr(),
12361 Bop->getSourceRange());
12366 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12367 Expr *SubExpr, StringRef Shift) {
12368 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12369 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12370 StringRef Op = Bop->getOpcodeStr();
12371 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12372 << Bop->getSourceRange() << OpLoc << Shift << Op;
12373 SuggestParentheses(S, Bop->getOperatorLoc(),
12374 S.PDiag(diag::note_precedence_silence) << Op,
12375 Bop->getSourceRange());
12380 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12381 Expr *LHSExpr, Expr *RHSExpr) {
12382 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12386 FunctionDecl *FD = OCE->getDirectCallee();
12387 if (!FD || !FD->isOverloadedOperator())
12390 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12391 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12394 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12395 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12396 << (Kind == OO_LessLess);
12397 SuggestParentheses(S, OCE->getOperatorLoc(),
12398 S.PDiag(diag::note_precedence_silence)
12399 << (Kind == OO_LessLess ? "<<" : ">>"),
12400 OCE->getSourceRange());
12401 SuggestParentheses(S, OpLoc,
12402 S.PDiag(diag::note_evaluate_comparison_first),
12403 SourceRange(OCE->getArg(1)->getLocStart(),
12404 RHSExpr->getLocEnd()));
12407 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12409 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12410 SourceLocation OpLoc, Expr *LHSExpr,
12412 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12413 if (BinaryOperator::isBitwiseOp(Opc))
12414 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12416 // Diagnose "arg1 & arg2 | arg3"
12417 if ((Opc == BO_Or || Opc == BO_Xor) &&
12418 !OpLoc.isMacroID()/* Don't warn in macros. */) {
12419 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12420 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12423 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12424 // We don't warn for 'assert(a || b && "bad")' since this is safe.
12425 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12426 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12427 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12430 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12431 || Opc == BO_Shr) {
12432 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12433 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12434 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12437 // Warn on overloaded shift operators and comparisons, such as:
12439 if (BinaryOperator::isComparisonOp(Opc))
12440 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12443 // Binary Operators. 'Tok' is the token for the operator.
12444 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12445 tok::TokenKind Kind,
12446 Expr *LHSExpr, Expr *RHSExpr) {
12447 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12448 assert(LHSExpr && "ActOnBinOp(): missing left expression");
12449 assert(RHSExpr && "ActOnBinOp(): missing right expression");
12451 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12452 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12454 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12457 /// Build an overloaded binary operator expression in the given scope.
12458 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12459 BinaryOperatorKind Opc,
12460 Expr *LHS, Expr *RHS) {
12469 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12470 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12476 // Find all of the overloaded operators visible from this
12477 // point. We perform both an operator-name lookup from the local
12478 // scope and an argument-dependent lookup based on the types of
12480 UnresolvedSet<16> Functions;
12481 OverloadedOperatorKind OverOp
12482 = BinaryOperator::getOverloadedOperator(Opc);
12483 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12484 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12485 RHS->getType(), Functions);
12487 // Build the (potentially-overloaded, potentially-dependent)
12488 // binary operation.
12489 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12492 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12493 BinaryOperatorKind Opc,
12494 Expr *LHSExpr, Expr *RHSExpr) {
12495 ExprResult LHS, RHS;
12496 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12497 if (!LHS.isUsable() || !RHS.isUsable())
12498 return ExprError();
12499 LHSExpr = LHS.get();
12500 RHSExpr = RHS.get();
12502 // We want to end up calling one of checkPseudoObjectAssignment
12503 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12504 // both expressions are overloadable or either is type-dependent),
12505 // or CreateBuiltinBinOp (in any other case). We also want to get
12506 // any placeholder types out of the way.
12508 // Handle pseudo-objects in the LHS.
12509 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12510 // Assignments with a pseudo-object l-value need special analysis.
12511 if (pty->getKind() == BuiltinType::PseudoObject &&
12512 BinaryOperator::isAssignmentOp(Opc))
12513 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12515 // Don't resolve overloads if the other type is overloadable.
12516 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12517 // We can't actually test that if we still have a placeholder,
12518 // though. Fortunately, none of the exceptions we see in that
12519 // code below are valid when the LHS is an overload set. Note
12520 // that an overload set can be dependently-typed, but it never
12521 // instantiates to having an overloadable type.
12522 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12523 if (resolvedRHS.isInvalid()) return ExprError();
12524 RHSExpr = resolvedRHS.get();
12526 if (RHSExpr->isTypeDependent() ||
12527 RHSExpr->getType()->isOverloadableType())
12528 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12531 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12532 // template, diagnose the missing 'template' keyword instead of diagnosing
12533 // an invalid use of a bound member function.
12535 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12536 // to C++1z [over.over]/1.4, but we already checked for that case above.
12537 if (Opc == BO_LT && inTemplateInstantiation() &&
12538 (pty->getKind() == BuiltinType::BoundMember ||
12539 pty->getKind() == BuiltinType::Overload)) {
12540 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12541 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12542 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12543 return isa<FunctionTemplateDecl>(ND);
12545 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12546 : OE->getNameLoc(),
12547 diag::err_template_kw_missing)
12548 << OE->getName().getAsString() << "";
12549 return ExprError();
12553 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12554 if (LHS.isInvalid()) return ExprError();
12555 LHSExpr = LHS.get();
12558 // Handle pseudo-objects in the RHS.
12559 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12560 // An overload in the RHS can potentially be resolved by the type
12561 // being assigned to.
12562 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12563 if (getLangOpts().CPlusPlus &&
12564 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12565 LHSExpr->getType()->isOverloadableType()))
12566 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12568 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12571 // Don't resolve overloads if the other type is overloadable.
12572 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12573 LHSExpr->getType()->isOverloadableType())
12574 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12576 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12577 if (!resolvedRHS.isUsable()) return ExprError();
12578 RHSExpr = resolvedRHS.get();
12581 if (getLangOpts().CPlusPlus) {
12582 // If either expression is type-dependent, always build an
12584 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12585 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12587 // Otherwise, build an overloaded op if either expression has an
12588 // overloadable type.
12589 if (LHSExpr->getType()->isOverloadableType() ||
12590 RHSExpr->getType()->isOverloadableType())
12591 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12594 // Build a built-in binary operation.
12595 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12598 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12599 if (T.isNull() || T->isDependentType())
12602 if (!T->isPromotableIntegerType())
12605 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12608 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12609 UnaryOperatorKind Opc,
12611 ExprResult Input = InputExpr;
12612 ExprValueKind VK = VK_RValue;
12613 ExprObjectKind OK = OK_Ordinary;
12614 QualType resultType;
12615 bool CanOverflow = false;
12617 bool ConvertHalfVec = false;
12618 if (getLangOpts().OpenCL) {
12619 QualType Ty = InputExpr->getType();
12620 // The only legal unary operation for atomics is '&'.
12621 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12622 // OpenCL special types - image, sampler, pipe, and blocks are to be used
12623 // only with a builtin functions and therefore should be disallowed here.
12624 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12625 || Ty->isBlockPointerType())) {
12626 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12627 << InputExpr->getType()
12628 << Input.get()->getSourceRange());
12636 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12638 Opc == UO_PreInc ||
12640 Opc == UO_PreInc ||
12642 CanOverflow = isOverflowingIntegerType(Context, resultType);
12645 resultType = CheckAddressOfOperand(Input, OpLoc);
12646 RecordModifiableNonNullParam(*this, InputExpr);
12649 Input = DefaultFunctionArrayLvalueConversion(Input.get());
12650 if (Input.isInvalid()) return ExprError();
12651 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12656 CanOverflow = Opc == UO_Minus &&
12657 isOverflowingIntegerType(Context, Input.get()->getType());
12658 Input = UsualUnaryConversions(Input.get());
12659 if (Input.isInvalid()) return ExprError();
12660 // Unary plus and minus require promoting an operand of half vector to a
12661 // float vector and truncating the result back to a half vector. For now, we
12662 // do this only when HalfArgsAndReturns is set (that is, when the target is
12665 needsConversionOfHalfVec(true, Context, Input.get()->getType());
12667 // If the operand is a half vector, promote it to a float vector.
12668 if (ConvertHalfVec)
12669 Input = convertVector(Input.get(), Context.FloatTy, *this);
12670 resultType = Input.get()->getType();
12671 if (resultType->isDependentType())
12673 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12675 else if (resultType->isVectorType() &&
12676 // The z vector extensions don't allow + or - with bool vectors.
12677 (!Context.getLangOpts().ZVector ||
12678 resultType->getAs<VectorType>()->getVectorKind() !=
12679 VectorType::AltiVecBool))
12681 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12683 resultType->isPointerType())
12686 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12687 << resultType << Input.get()->getSourceRange());
12689 case UO_Not: // bitwise complement
12690 Input = UsualUnaryConversions(Input.get());
12691 if (Input.isInvalid())
12692 return ExprError();
12693 resultType = Input.get()->getType();
12695 if (resultType->isDependentType())
12697 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12698 if (resultType->isComplexType() || resultType->isComplexIntegerType())
12699 // C99 does not support '~' for complex conjugation.
12700 Diag(OpLoc, diag::ext_integer_complement_complex)
12701 << resultType << Input.get()->getSourceRange();
12702 else if (resultType->hasIntegerRepresentation())
12704 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12705 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12706 // on vector float types.
12707 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12708 if (!T->isIntegerType())
12709 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12710 << resultType << Input.get()->getSourceRange());
12712 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12713 << resultType << Input.get()->getSourceRange());
12717 case UO_LNot: // logical negation
12718 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12719 Input = DefaultFunctionArrayLvalueConversion(Input.get());
12720 if (Input.isInvalid()) return ExprError();
12721 resultType = Input.get()->getType();
12723 // Though we still have to promote half FP to float...
12724 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12725 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12726 resultType = Context.FloatTy;
12729 if (resultType->isDependentType())
12731 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12732 // C99 6.5.3.3p1: ok, fallthrough;
12733 if (Context.getLangOpts().CPlusPlus) {
12734 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12735 // operand contextually converted to bool.
12736 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12737 ScalarTypeToBooleanCastKind(resultType));
12738 } else if (Context.getLangOpts().OpenCL &&
12739 Context.getLangOpts().OpenCLVersion < 120) {
12740 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12741 // operate on scalar float types.
12742 if (!resultType->isIntegerType() && !resultType->isPointerType())
12743 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12744 << resultType << Input.get()->getSourceRange());
12746 } else if (resultType->isExtVectorType()) {
12747 if (Context.getLangOpts().OpenCL &&
12748 Context.getLangOpts().OpenCLVersion < 120) {
12749 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12750 // operate on vector float types.
12751 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12752 if (!T->isIntegerType())
12753 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12754 << resultType << Input.get()->getSourceRange());
12756 // Vector logical not returns the signed variant of the operand type.
12757 resultType = GetSignedVectorType(resultType);
12760 // FIXME: GCC's vector extension permits the usage of '!' with a vector
12761 // type in C++. We should allow that here too.
12762 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12763 << resultType << Input.get()->getSourceRange());
12766 // LNot always has type int. C99 6.5.3.3p5.
12767 // In C++, it's bool. C++ 5.3.1p8
12768 resultType = Context.getLogicalOperationType();
12772 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12773 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12774 // complex l-values to ordinary l-values and all other values to r-values.
12775 if (Input.isInvalid()) return ExprError();
12776 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12777 if (Input.get()->getValueKind() != VK_RValue &&
12778 Input.get()->getObjectKind() == OK_Ordinary)
12779 VK = Input.get()->getValueKind();
12780 } else if (!getLangOpts().CPlusPlus) {
12781 // In C, a volatile scalar is read by __imag. In C++, it is not.
12782 Input = DefaultLvalueConversion(Input.get());
12786 resultType = Input.get()->getType();
12787 VK = Input.get()->getValueKind();
12788 OK = Input.get()->getObjectKind();
12791 // It's unnecessary to represent the pass-through operator co_await in the
12792 // AST; just return the input expression instead.
12793 assert(!Input.get()->getType()->isDependentType() &&
12794 "the co_await expression must be non-dependant before "
12795 "building operator co_await");
12798 if (resultType.isNull() || Input.isInvalid())
12799 return ExprError();
12801 // Check for array bounds violations in the operand of the UnaryOperator,
12802 // except for the '*' and '&' operators that have to be handled specially
12803 // by CheckArrayAccess (as there are special cases like &array[arraysize]
12804 // that are explicitly defined as valid by the standard).
12805 if (Opc != UO_AddrOf && Opc != UO_Deref)
12806 CheckArrayAccess(Input.get());
12808 auto *UO = new (Context)
12809 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12810 // Convert the result back to a half vector.
12811 if (ConvertHalfVec)
12812 return convertVector(UO, Context.HalfTy, *this);
12816 /// Determine whether the given expression is a qualified member
12817 /// access expression, of a form that could be turned into a pointer to member
12818 /// with the address-of operator.
12819 bool Sema::isQualifiedMemberAccess(Expr *E) {
12820 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12821 if (!DRE->getQualifier())
12824 ValueDecl *VD = DRE->getDecl();
12825 if (!VD->isCXXClassMember())
12828 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12830 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12831 return Method->isInstance();
12836 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12837 if (!ULE->getQualifier())
12840 for (NamedDecl *D : ULE->decls()) {
12841 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12842 if (Method->isInstance())
12845 // Overload set does not contain methods.
12856 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12857 UnaryOperatorKind Opc, Expr *Input) {
12858 // First things first: handle placeholders so that the
12859 // overloaded-operator check considers the right type.
12860 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12861 // Increment and decrement of pseudo-object references.
12862 if (pty->getKind() == BuiltinType::PseudoObject &&
12863 UnaryOperator::isIncrementDecrementOp(Opc))
12864 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12866 // extension is always a builtin operator.
12867 if (Opc == UO_Extension)
12868 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12870 // & gets special logic for several kinds of placeholder.
12871 // The builtin code knows what to do.
12872 if (Opc == UO_AddrOf &&
12873 (pty->getKind() == BuiltinType::Overload ||
12874 pty->getKind() == BuiltinType::UnknownAny ||
12875 pty->getKind() == BuiltinType::BoundMember))
12876 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12878 // Anything else needs to be handled now.
12879 ExprResult Result = CheckPlaceholderExpr(Input);
12880 if (Result.isInvalid()) return ExprError();
12881 Input = Result.get();
12884 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12885 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12886 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12887 // Find all of the overloaded operators visible from this
12888 // point. We perform both an operator-name lookup from the local
12889 // scope and an argument-dependent lookup based on the types of
12891 UnresolvedSet<16> Functions;
12892 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12893 if (S && OverOp != OO_None)
12894 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12897 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12900 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12903 // Unary Operators. 'Tok' is the token for the operator.
12904 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12905 tok::TokenKind Op, Expr *Input) {
12906 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12909 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12910 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12911 LabelDecl *TheDecl) {
12912 TheDecl->markUsed(Context);
12913 // Create the AST node. The address of a label always has type 'void*'.
12914 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12915 Context.getPointerType(Context.VoidTy));
12918 /// Given the last statement in a statement-expression, check whether
12919 /// the result is a producing expression (like a call to an
12920 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12921 /// release out of the full-expression. Otherwise, return null.
12923 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12924 // Should always be wrapped with one of these.
12925 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12926 if (!cleanups) return nullptr;
12928 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12929 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12932 // Splice out the cast. This shouldn't modify any interesting
12933 // features of the statement.
12934 Expr *producer = cast->getSubExpr();
12935 assert(producer->getType() == cast->getType());
12936 assert(producer->getValueKind() == cast->getValueKind());
12937 cleanups->setSubExpr(producer);
12941 void Sema::ActOnStartStmtExpr() {
12942 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12945 void Sema::ActOnStmtExprError() {
12946 // Note that function is also called by TreeTransform when leaving a
12947 // StmtExpr scope without rebuilding anything.
12949 DiscardCleanupsInEvaluationContext();
12950 PopExpressionEvaluationContext();
12954 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12955 SourceLocation RPLoc) { // "({..})"
12956 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12957 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12959 if (hasAnyUnrecoverableErrorsInThisFunction())
12960 DiscardCleanupsInEvaluationContext();
12961 assert(!Cleanup.exprNeedsCleanups() &&
12962 "cleanups within StmtExpr not correctly bound!");
12963 PopExpressionEvaluationContext();
12965 // FIXME: there are a variety of strange constraints to enforce here, for
12966 // example, it is not possible to goto into a stmt expression apparently.
12967 // More semantic analysis is needed.
12969 // If there are sub-stmts in the compound stmt, take the type of the last one
12970 // as the type of the stmtexpr.
12971 QualType Ty = Context.VoidTy;
12972 bool StmtExprMayBindToTemp = false;
12973 if (!Compound->body_empty()) {
12974 Stmt *LastStmt = Compound->body_back();
12975 LabelStmt *LastLabelStmt = nullptr;
12976 // If LastStmt is a label, skip down through into the body.
12977 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12978 LastLabelStmt = Label;
12979 LastStmt = Label->getSubStmt();
12982 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12983 // Do function/array conversion on the last expression, but not
12984 // lvalue-to-rvalue. However, initialize an unqualified type.
12985 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12986 if (LastExpr.isInvalid())
12987 return ExprError();
12988 Ty = LastExpr.get()->getType().getUnqualifiedType();
12990 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12991 // In ARC, if the final expression ends in a consume, splice
12992 // the consume out and bind it later. In the alternate case
12993 // (when dealing with a retainable type), the result
12994 // initialization will create a produce. In both cases the
12995 // result will be +1, and we'll need to balance that out with
12997 if (Expr *rebuiltLastStmt
12998 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12999 LastExpr = rebuiltLastStmt;
13001 LastExpr = PerformCopyInitialization(
13002 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
13003 SourceLocation(), LastExpr);
13006 if (LastExpr.isInvalid())
13007 return ExprError();
13008 if (LastExpr.get() != nullptr) {
13009 if (!LastLabelStmt)
13010 Compound->setLastStmt(LastExpr.get());
13012 LastLabelStmt->setSubStmt(LastExpr.get());
13013 StmtExprMayBindToTemp = true;
13019 // FIXME: Check that expression type is complete/non-abstract; statement
13020 // expressions are not lvalues.
13021 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13022 if (StmtExprMayBindToTemp)
13023 return MaybeBindToTemporary(ResStmtExpr);
13024 return ResStmtExpr;
13027 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13028 TypeSourceInfo *TInfo,
13029 ArrayRef<OffsetOfComponent> Components,
13030 SourceLocation RParenLoc) {
13031 QualType ArgTy = TInfo->getType();
13032 bool Dependent = ArgTy->isDependentType();
13033 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13035 // We must have at least one component that refers to the type, and the first
13036 // one is known to be a field designator. Verify that the ArgTy represents
13037 // a struct/union/class.
13038 if (!Dependent && !ArgTy->isRecordType())
13039 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13040 << ArgTy << TypeRange);
13042 // Type must be complete per C99 7.17p3 because a declaring a variable
13043 // with an incomplete type would be ill-formed.
13045 && RequireCompleteType(BuiltinLoc, ArgTy,
13046 diag::err_offsetof_incomplete_type, TypeRange))
13047 return ExprError();
13049 bool DidWarnAboutNonPOD = false;
13050 QualType CurrentType = ArgTy;
13051 SmallVector<OffsetOfNode, 4> Comps;
13052 SmallVector<Expr*, 4> Exprs;
13053 for (const OffsetOfComponent &OC : Components) {
13054 if (OC.isBrackets) {
13055 // Offset of an array sub-field. TODO: Should we allow vector elements?
13056 if (!CurrentType->isDependentType()) {
13057 const ArrayType *AT = Context.getAsArrayType(CurrentType);
13059 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13061 CurrentType = AT->getElementType();
13063 CurrentType = Context.DependentTy;
13065 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13066 if (IdxRval.isInvalid())
13067 return ExprError();
13068 Expr *Idx = IdxRval.get();
13070 // The expression must be an integral expression.
13071 // FIXME: An integral constant expression?
13072 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13073 !Idx->getType()->isIntegerType())
13074 return ExprError(Diag(Idx->getLocStart(),
13075 diag::err_typecheck_subscript_not_integer)
13076 << Idx->getSourceRange());
13078 // Record this array index.
13079 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13080 Exprs.push_back(Idx);
13084 // Offset of a field.
13085 if (CurrentType->isDependentType()) {
13086 // We have the offset of a field, but we can't look into the dependent
13087 // type. Just record the identifier of the field.
13088 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13089 CurrentType = Context.DependentTy;
13093 // We need to have a complete type to look into.
13094 if (RequireCompleteType(OC.LocStart, CurrentType,
13095 diag::err_offsetof_incomplete_type))
13096 return ExprError();
13098 // Look for the designated field.
13099 const RecordType *RC = CurrentType->getAs<RecordType>();
13101 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13103 RecordDecl *RD = RC->getDecl();
13105 // C++ [lib.support.types]p5:
13106 // The macro offsetof accepts a restricted set of type arguments in this
13107 // International Standard. type shall be a POD structure or a POD union
13109 // C++11 [support.types]p4:
13110 // If type is not a standard-layout class (Clause 9), the results are
13112 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13113 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13115 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13116 : diag::ext_offsetof_non_pod_type;
13118 if (!IsSafe && !DidWarnAboutNonPOD &&
13119 DiagRuntimeBehavior(BuiltinLoc, nullptr,
13121 << SourceRange(Components[0].LocStart, OC.LocEnd)
13123 DidWarnAboutNonPOD = true;
13126 // Look for the field.
13127 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13128 LookupQualifiedName(R, RD);
13129 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13130 IndirectFieldDecl *IndirectMemberDecl = nullptr;
13132 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13133 MemberDecl = IndirectMemberDecl->getAnonField();
13137 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13138 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13142 // (If the specified member is a bit-field, the behavior is undefined.)
13144 // We diagnose this as an error.
13145 if (MemberDecl->isBitField()) {
13146 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13147 << MemberDecl->getDeclName()
13148 << SourceRange(BuiltinLoc, RParenLoc);
13149 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13150 return ExprError();
13153 RecordDecl *Parent = MemberDecl->getParent();
13154 if (IndirectMemberDecl)
13155 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13157 // If the member was found in a base class, introduce OffsetOfNodes for
13158 // the base class indirections.
13159 CXXBasePaths Paths;
13160 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13162 if (Paths.getDetectedVirtual()) {
13163 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13164 << MemberDecl->getDeclName()
13165 << SourceRange(BuiltinLoc, RParenLoc);
13166 return ExprError();
13169 CXXBasePath &Path = Paths.front();
13170 for (const CXXBasePathElement &B : Path)
13171 Comps.push_back(OffsetOfNode(B.Base));
13174 if (IndirectMemberDecl) {
13175 for (auto *FI : IndirectMemberDecl->chain()) {
13176 assert(isa<FieldDecl>(FI));
13177 Comps.push_back(OffsetOfNode(OC.LocStart,
13178 cast<FieldDecl>(FI), OC.LocEnd));
13181 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13183 CurrentType = MemberDecl->getType().getNonReferenceType();
13186 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13187 Comps, Exprs, RParenLoc);
13190 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13191 SourceLocation BuiltinLoc,
13192 SourceLocation TypeLoc,
13193 ParsedType ParsedArgTy,
13194 ArrayRef<OffsetOfComponent> Components,
13195 SourceLocation RParenLoc) {
13197 TypeSourceInfo *ArgTInfo;
13198 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13199 if (ArgTy.isNull())
13200 return ExprError();
13203 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13205 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13209 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13211 Expr *LHSExpr, Expr *RHSExpr,
13212 SourceLocation RPLoc) {
13213 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13215 ExprValueKind VK = VK_RValue;
13216 ExprObjectKind OK = OK_Ordinary;
13218 bool ValueDependent = false;
13219 bool CondIsTrue = false;
13220 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13221 resType = Context.DependentTy;
13222 ValueDependent = true;
13224 // The conditional expression is required to be a constant expression.
13225 llvm::APSInt condEval(32);
13227 = VerifyIntegerConstantExpression(CondExpr, &condEval,
13228 diag::err_typecheck_choose_expr_requires_constant, false);
13229 if (CondICE.isInvalid())
13230 return ExprError();
13231 CondExpr = CondICE.get();
13232 CondIsTrue = condEval.getZExtValue();
13234 // If the condition is > zero, then the AST type is the same as the LHSExpr.
13235 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13237 resType = ActiveExpr->getType();
13238 ValueDependent = ActiveExpr->isValueDependent();
13239 VK = ActiveExpr->getValueKind();
13240 OK = ActiveExpr->getObjectKind();
13243 return new (Context)
13244 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13245 CondIsTrue, resType->isDependentType(), ValueDependent);
13248 //===----------------------------------------------------------------------===//
13249 // Clang Extensions.
13250 //===----------------------------------------------------------------------===//
13252 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13253 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13254 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13256 if (LangOpts.CPlusPlus) {
13257 Decl *ManglingContextDecl;
13258 if (MangleNumberingContext *MCtx =
13259 getCurrentMangleNumberContext(Block->getDeclContext(),
13260 ManglingContextDecl)) {
13261 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13262 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13266 PushBlockScope(CurScope, Block);
13267 CurContext->addDecl(Block);
13269 PushDeclContext(CurScope, Block);
13271 CurContext = Block;
13273 getCurBlock()->HasImplicitReturnType = true;
13275 // Enter a new evaluation context to insulate the block from any
13276 // cleanups from the enclosing full-expression.
13277 PushExpressionEvaluationContext(
13278 ExpressionEvaluationContext::PotentiallyEvaluated);
13281 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13283 assert(ParamInfo.getIdentifier() == nullptr &&
13284 "block-id should have no identifier!");
13285 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13286 BlockScopeInfo *CurBlock = getCurBlock();
13288 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13289 QualType T = Sig->getType();
13291 // FIXME: We should allow unexpanded parameter packs here, but that would,
13292 // in turn, make the block expression contain unexpanded parameter packs.
13293 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13294 // Drop the parameters.
13295 FunctionProtoType::ExtProtoInfo EPI;
13296 EPI.HasTrailingReturn = false;
13297 EPI.TypeQuals |= DeclSpec::TQ_const;
13298 T = Context.getFunctionType(Context.DependentTy, None, EPI);
13299 Sig = Context.getTrivialTypeSourceInfo(T);
13302 // GetTypeForDeclarator always produces a function type for a block
13303 // literal signature. Furthermore, it is always a FunctionProtoType
13304 // unless the function was written with a typedef.
13305 assert(T->isFunctionType() &&
13306 "GetTypeForDeclarator made a non-function block signature");
13308 // Look for an explicit signature in that function type.
13309 FunctionProtoTypeLoc ExplicitSignature;
13311 if ((ExplicitSignature =
13312 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13314 // Check whether that explicit signature was synthesized by
13315 // GetTypeForDeclarator. If so, don't save that as part of the
13316 // written signature.
13317 if (ExplicitSignature.getLocalRangeBegin() ==
13318 ExplicitSignature.getLocalRangeEnd()) {
13319 // This would be much cheaper if we stored TypeLocs instead of
13320 // TypeSourceInfos.
13321 TypeLoc Result = ExplicitSignature.getReturnLoc();
13322 unsigned Size = Result.getFullDataSize();
13323 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13324 Sig->getTypeLoc().initializeFullCopy(Result, Size);
13326 ExplicitSignature = FunctionProtoTypeLoc();
13330 CurBlock->TheDecl->setSignatureAsWritten(Sig);
13331 CurBlock->FunctionType = T;
13333 const FunctionType *Fn = T->getAs<FunctionType>();
13334 QualType RetTy = Fn->getReturnType();
13336 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13338 CurBlock->TheDecl->setIsVariadic(isVariadic);
13340 // Context.DependentTy is used as a placeholder for a missing block
13341 // return type. TODO: what should we do with declarators like:
13343 // If the answer is "apply template argument deduction"....
13344 if (RetTy != Context.DependentTy) {
13345 CurBlock->ReturnType = RetTy;
13346 CurBlock->TheDecl->setBlockMissingReturnType(false);
13347 CurBlock->HasImplicitReturnType = false;
13350 // Push block parameters from the declarator if we had them.
13351 SmallVector<ParmVarDecl*, 8> Params;
13352 if (ExplicitSignature) {
13353 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13354 ParmVarDecl *Param = ExplicitSignature.getParam(I);
13355 if (Param->getIdentifier() == nullptr &&
13356 !Param->isImplicit() &&
13357 !Param->isInvalidDecl() &&
13358 !getLangOpts().CPlusPlus)
13359 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13360 Params.push_back(Param);
13363 // Fake up parameter variables if we have a typedef, like
13364 // ^ fntype { ... }
13365 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13366 for (const auto &I : Fn->param_types()) {
13367 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13368 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13369 Params.push_back(Param);
13373 // Set the parameters on the block decl.
13374 if (!Params.empty()) {
13375 CurBlock->TheDecl->setParams(Params);
13376 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13377 /*CheckParameterNames=*/false);
13380 // Finally we can process decl attributes.
13381 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13383 // Put the parameter variables in scope.
13384 for (auto AI : CurBlock->TheDecl->parameters()) {
13385 AI->setOwningFunction(CurBlock->TheDecl);
13387 // If this has an identifier, add it to the scope stack.
13388 if (AI->getIdentifier()) {
13389 CheckShadow(CurBlock->TheScope, AI);
13391 PushOnScopeChains(AI, CurBlock->TheScope);
13396 /// ActOnBlockError - If there is an error parsing a block, this callback
13397 /// is invoked to pop the information about the block from the action impl.
13398 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13399 // Leave the expression-evaluation context.
13400 DiscardCleanupsInEvaluationContext();
13401 PopExpressionEvaluationContext();
13403 // Pop off CurBlock, handle nested blocks.
13405 PopFunctionScopeInfo();
13408 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13409 /// literal was successfully completed. ^(int x){...}
13410 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13411 Stmt *Body, Scope *CurScope) {
13412 // If blocks are disabled, emit an error.
13413 if (!LangOpts.Blocks)
13414 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13416 // Leave the expression-evaluation context.
13417 if (hasAnyUnrecoverableErrorsInThisFunction())
13418 DiscardCleanupsInEvaluationContext();
13419 assert(!Cleanup.exprNeedsCleanups() &&
13420 "cleanups within block not correctly bound!");
13421 PopExpressionEvaluationContext();
13423 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13425 if (BSI->HasImplicitReturnType)
13426 deduceClosureReturnType(*BSI);
13430 QualType RetTy = Context.VoidTy;
13431 if (!BSI->ReturnType.isNull())
13432 RetTy = BSI->ReturnType;
13434 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13437 // Set the captured variables on the block.
13438 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13439 SmallVector<BlockDecl::Capture, 4> Captures;
13440 for (Capture &Cap : BSI->Captures) {
13441 if (Cap.isThisCapture())
13443 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13444 Cap.isNested(), Cap.getInitExpr());
13445 Captures.push_back(NewCap);
13447 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13449 // If the user wrote a function type in some form, try to use that.
13450 if (!BSI->FunctionType.isNull()) {
13451 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13453 FunctionType::ExtInfo Ext = FTy->getExtInfo();
13454 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13456 // Turn protoless block types into nullary block types.
13457 if (isa<FunctionNoProtoType>(FTy)) {
13458 FunctionProtoType::ExtProtoInfo EPI;
13460 BlockTy = Context.getFunctionType(RetTy, None, EPI);
13462 // Otherwise, if we don't need to change anything about the function type,
13463 // preserve its sugar structure.
13464 } else if (FTy->getReturnType() == RetTy &&
13465 (!NoReturn || FTy->getNoReturnAttr())) {
13466 BlockTy = BSI->FunctionType;
13468 // Otherwise, make the minimal modifications to the function type.
13470 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13471 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13472 EPI.TypeQuals = 0; // FIXME: silently?
13474 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13477 // If we don't have a function type, just build one from nothing.
13479 FunctionProtoType::ExtProtoInfo EPI;
13480 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13481 BlockTy = Context.getFunctionType(RetTy, None, EPI);
13484 DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13485 BlockTy = Context.getBlockPointerType(BlockTy);
13487 // If needed, diagnose invalid gotos and switches in the block.
13488 if (getCurFunction()->NeedsScopeChecking() &&
13489 !PP.isCodeCompletionEnabled())
13490 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13492 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13494 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13495 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13497 // Try to apply the named return value optimization. We have to check again
13498 // if we can do this, though, because blocks keep return statements around
13499 // to deduce an implicit return type.
13500 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13501 !BSI->TheDecl->isDependentContext())
13502 computeNRVO(Body, BSI);
13504 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13505 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13506 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13508 // If the block isn't obviously global, i.e. it captures anything at
13509 // all, then we need to do a few things in the surrounding context:
13510 if (Result->getBlockDecl()->hasCaptures()) {
13511 // First, this expression has a new cleanup object.
13512 ExprCleanupObjects.push_back(Result->getBlockDecl());
13513 Cleanup.setExprNeedsCleanups(true);
13515 // It also gets a branch-protected scope if any of the captured
13516 // variables needs destruction.
13517 for (const auto &CI : Result->getBlockDecl()->captures()) {
13518 const VarDecl *var = CI.getVariable();
13519 if (var->getType().isDestructedType() != QualType::DK_none) {
13520 setFunctionHasBranchProtectedScope();
13529 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13530 SourceLocation RPLoc) {
13531 TypeSourceInfo *TInfo;
13532 GetTypeFromParser(Ty, &TInfo);
13533 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13536 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13537 Expr *E, TypeSourceInfo *TInfo,
13538 SourceLocation RPLoc) {
13539 Expr *OrigExpr = E;
13542 // CUDA device code does not support varargs.
13543 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13544 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13545 CUDAFunctionTarget T = IdentifyCUDATarget(F);
13546 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13547 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13551 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13552 // as Microsoft ABI on an actual Microsoft platform, where
13553 // __builtin_ms_va_list and __builtin_va_list are the same.)
13554 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13555 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13556 QualType MSVaListType = Context.getBuiltinMSVaListType();
13557 if (Context.hasSameType(MSVaListType, E->getType())) {
13558 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13559 return ExprError();
13564 // Get the va_list type
13565 QualType VaListType = Context.getBuiltinVaListType();
13567 if (VaListType->isArrayType()) {
13568 // Deal with implicit array decay; for example, on x86-64,
13569 // va_list is an array, but it's supposed to decay to
13570 // a pointer for va_arg.
13571 VaListType = Context.getArrayDecayedType(VaListType);
13572 // Make sure the input expression also decays appropriately.
13573 ExprResult Result = UsualUnaryConversions(E);
13574 if (Result.isInvalid())
13575 return ExprError();
13577 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13578 // If va_list is a record type and we are compiling in C++ mode,
13579 // check the argument using reference binding.
13580 InitializedEntity Entity = InitializedEntity::InitializeParameter(
13581 Context, Context.getLValueReferenceType(VaListType), false);
13582 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13583 if (Init.isInvalid())
13584 return ExprError();
13585 E = Init.getAs<Expr>();
13587 // Otherwise, the va_list argument must be an l-value because
13588 // it is modified by va_arg.
13589 if (!E->isTypeDependent() &&
13590 CheckForModifiableLvalue(E, BuiltinLoc, *this))
13591 return ExprError();
13595 if (!IsMS && !E->isTypeDependent() &&
13596 !Context.hasSameType(VaListType, E->getType()))
13597 return ExprError(Diag(E->getLocStart(),
13598 diag::err_first_argument_to_va_arg_not_of_type_va_list)
13599 << OrigExpr->getType() << E->getSourceRange());
13601 if (!TInfo->getType()->isDependentType()) {
13602 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13603 diag::err_second_parameter_to_va_arg_incomplete,
13604 TInfo->getTypeLoc()))
13605 return ExprError();
13607 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13609 diag::err_second_parameter_to_va_arg_abstract,
13610 TInfo->getTypeLoc()))
13611 return ExprError();
13613 if (!TInfo->getType().isPODType(Context)) {
13614 Diag(TInfo->getTypeLoc().getBeginLoc(),
13615 TInfo->getType()->isObjCLifetimeType()
13616 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13617 : diag::warn_second_parameter_to_va_arg_not_pod)
13618 << TInfo->getType()
13619 << TInfo->getTypeLoc().getSourceRange();
13622 // Check for va_arg where arguments of the given type will be promoted
13623 // (i.e. this va_arg is guaranteed to have undefined behavior).
13624 QualType PromoteType;
13625 if (TInfo->getType()->isPromotableIntegerType()) {
13626 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13627 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13628 PromoteType = QualType();
13630 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13631 PromoteType = Context.DoubleTy;
13632 if (!PromoteType.isNull())
13633 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13634 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13635 << TInfo->getType()
13637 << TInfo->getTypeLoc().getSourceRange());
13640 QualType T = TInfo->getType().getNonLValueExprType(Context);
13641 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13644 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13645 // The type of __null will be int or long, depending on the size of
13646 // pointers on the target.
13648 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13649 if (pw == Context.getTargetInfo().getIntWidth())
13650 Ty = Context.IntTy;
13651 else if (pw == Context.getTargetInfo().getLongWidth())
13652 Ty = Context.LongTy;
13653 else if (pw == Context.getTargetInfo().getLongLongWidth())
13654 Ty = Context.LongLongTy;
13656 llvm_unreachable("I don't know size of pointer!");
13659 return new (Context) GNUNullExpr(Ty, TokenLoc);
13662 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13664 if (!getLangOpts().ObjC1)
13667 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13671 if (!PT->isObjCIdType()) {
13672 // Check if the destination is the 'NSString' interface.
13673 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13674 if (!ID || !ID->getIdentifier()->isStr("NSString"))
13678 // Ignore any parens, implicit casts (should only be
13679 // array-to-pointer decays), and not-so-opaque values. The last is
13680 // important for making this trigger for property assignments.
13681 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13682 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13683 if (OV->getSourceExpr())
13684 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13686 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13687 if (!SL || !SL->isAscii())
13690 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13691 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13692 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13697 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13698 const Expr *SrcExpr) {
13699 if (!DstType->isFunctionPointerType() ||
13700 !SrcExpr->getType()->isFunctionType())
13703 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13707 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13711 return !S.checkAddressOfFunctionIsAvailable(FD,
13713 SrcExpr->getLocStart());
13716 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13717 SourceLocation Loc,
13718 QualType DstType, QualType SrcType,
13719 Expr *SrcExpr, AssignmentAction Action,
13720 bool *Complained) {
13722 *Complained = false;
13724 // Decode the result (notice that AST's are still created for extensions).
13725 bool CheckInferredResultType = false;
13726 bool isInvalid = false;
13727 unsigned DiagKind = 0;
13729 ConversionFixItGenerator ConvHints;
13730 bool MayHaveConvFixit = false;
13731 bool MayHaveFunctionDiff = false;
13732 const ObjCInterfaceDecl *IFace = nullptr;
13733 const ObjCProtocolDecl *PDecl = nullptr;
13737 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13741 DiagKind = diag::ext_typecheck_convert_pointer_int;
13742 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13743 MayHaveConvFixit = true;
13746 DiagKind = diag::ext_typecheck_convert_int_pointer;
13747 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13748 MayHaveConvFixit = true;
13750 case IncompatiblePointer:
13751 if (Action == AA_Passing_CFAudited)
13752 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13753 else if (SrcType->isFunctionPointerType() &&
13754 DstType->isFunctionPointerType())
13755 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13757 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13759 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13760 SrcType->isObjCObjectPointerType();
13761 if (Hint.isNull() && !CheckInferredResultType) {
13762 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13764 else if (CheckInferredResultType) {
13765 SrcType = SrcType.getUnqualifiedType();
13766 DstType = DstType.getUnqualifiedType();
13768 MayHaveConvFixit = true;
13770 case IncompatiblePointerSign:
13771 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13773 case FunctionVoidPointer:
13774 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13776 case IncompatiblePointerDiscardsQualifiers: {
13777 // Perform array-to-pointer decay if necessary.
13778 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13780 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13781 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13782 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13783 DiagKind = diag::err_typecheck_incompatible_address_space;
13786 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13787 DiagKind = diag::err_typecheck_incompatible_ownership;
13791 llvm_unreachable("unknown error case for discarding qualifiers!");
13794 case CompatiblePointerDiscardsQualifiers:
13795 // If the qualifiers lost were because we were applying the
13796 // (deprecated) C++ conversion from a string literal to a char*
13797 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
13798 // Ideally, this check would be performed in
13799 // checkPointerTypesForAssignment. However, that would require a
13800 // bit of refactoring (so that the second argument is an
13801 // expression, rather than a type), which should be done as part
13802 // of a larger effort to fix checkPointerTypesForAssignment for
13804 if (getLangOpts().CPlusPlus &&
13805 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13807 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13809 case IncompatibleNestedPointerQualifiers:
13810 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13812 case IntToBlockPointer:
13813 DiagKind = diag::err_int_to_block_pointer;
13815 case IncompatibleBlockPointer:
13816 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13818 case IncompatibleObjCQualifiedId: {
13819 if (SrcType->isObjCQualifiedIdType()) {
13820 const ObjCObjectPointerType *srcOPT =
13821 SrcType->getAs<ObjCObjectPointerType>();
13822 for (auto *srcProto : srcOPT->quals()) {
13826 if (const ObjCInterfaceType *IFaceT =
13827 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13828 IFace = IFaceT->getDecl();
13830 else if (DstType->isObjCQualifiedIdType()) {
13831 const ObjCObjectPointerType *dstOPT =
13832 DstType->getAs<ObjCObjectPointerType>();
13833 for (auto *dstProto : dstOPT->quals()) {
13837 if (const ObjCInterfaceType *IFaceT =
13838 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13839 IFace = IFaceT->getDecl();
13841 DiagKind = diag::warn_incompatible_qualified_id;
13844 case IncompatibleVectors:
13845 DiagKind = diag::warn_incompatible_vectors;
13847 case IncompatibleObjCWeakRef:
13848 DiagKind = diag::err_arc_weak_unavailable_assign;
13851 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13853 *Complained = true;
13857 DiagKind = diag::err_typecheck_convert_incompatible;
13858 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13859 MayHaveConvFixit = true;
13861 MayHaveFunctionDiff = true;
13865 QualType FirstType, SecondType;
13868 case AA_Initializing:
13869 // The destination type comes first.
13870 FirstType = DstType;
13871 SecondType = SrcType;
13876 case AA_Passing_CFAudited:
13877 case AA_Converting:
13880 // The source type comes first.
13881 FirstType = SrcType;
13882 SecondType = DstType;
13886 PartialDiagnostic FDiag = PDiag(DiagKind);
13887 if (Action == AA_Passing_CFAudited)
13888 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13890 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13892 // If we can fix the conversion, suggest the FixIts.
13893 assert(ConvHints.isNull() || Hint.isNull());
13894 if (!ConvHints.isNull()) {
13895 for (FixItHint &H : ConvHints.Hints)
13900 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13902 if (MayHaveFunctionDiff)
13903 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13906 if (DiagKind == diag::warn_incompatible_qualified_id &&
13907 PDecl && IFace && !IFace->hasDefinition())
13908 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13911 if (SecondType == Context.OverloadTy)
13912 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13913 FirstType, /*TakingAddress=*/true);
13915 if (CheckInferredResultType)
13916 EmitRelatedResultTypeNote(SrcExpr);
13918 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13919 EmitRelatedResultTypeNoteForReturn(DstType);
13922 *Complained = true;
13926 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13927 llvm::APSInt *Result) {
13928 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13930 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13931 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13935 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13938 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13939 llvm::APSInt *Result,
13942 class IDDiagnoser : public VerifyICEDiagnoser {
13946 IDDiagnoser(unsigned DiagID)
13947 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13949 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13950 S.Diag(Loc, DiagID) << SR;
13952 } Diagnoser(DiagID);
13954 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13957 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13959 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13963 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13964 VerifyICEDiagnoser &Diagnoser,
13966 SourceLocation DiagLoc = E->getLocStart();
13968 if (getLangOpts().CPlusPlus11) {
13969 // C++11 [expr.const]p5:
13970 // If an expression of literal class type is used in a context where an
13971 // integral constant expression is required, then that class type shall
13972 // have a single non-explicit conversion function to an integral or
13973 // unscoped enumeration type
13974 ExprResult Converted;
13975 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13977 CXX11ConvertDiagnoser(bool Silent)
13978 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13981 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13982 QualType T) override {
13983 return S.Diag(Loc, diag::err_ice_not_integral) << T;
13986 SemaDiagnosticBuilder diagnoseIncomplete(
13987 Sema &S, SourceLocation Loc, QualType T) override {
13988 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13991 SemaDiagnosticBuilder diagnoseExplicitConv(
13992 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13993 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13996 SemaDiagnosticBuilder noteExplicitConv(
13997 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13998 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13999 << ConvTy->isEnumeralType() << ConvTy;
14002 SemaDiagnosticBuilder diagnoseAmbiguous(
14003 Sema &S, SourceLocation Loc, QualType T) override {
14004 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14007 SemaDiagnosticBuilder noteAmbiguous(
14008 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14009 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14010 << ConvTy->isEnumeralType() << ConvTy;
14013 SemaDiagnosticBuilder diagnoseConversion(
14014 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14015 llvm_unreachable("conversion functions are permitted");
14017 } ConvertDiagnoser(Diagnoser.Suppress);
14019 Converted = PerformContextualImplicitConversion(DiagLoc, E,
14021 if (Converted.isInvalid())
14023 E = Converted.get();
14024 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14025 return ExprError();
14026 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14027 // An ICE must be of integral or unscoped enumeration type.
14028 if (!Diagnoser.Suppress)
14029 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14030 return ExprError();
14033 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14034 // in the non-ICE case.
14035 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14037 *Result = E->EvaluateKnownConstInt(Context);
14041 Expr::EvalResult EvalResult;
14042 SmallVector<PartialDiagnosticAt, 8> Notes;
14043 EvalResult.Diag = &Notes;
14045 // Try to evaluate the expression, and produce diagnostics explaining why it's
14046 // not a constant expression as a side-effect.
14047 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14048 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14050 // In C++11, we can rely on diagnostics being produced for any expression
14051 // which is not a constant expression. If no diagnostics were produced, then
14052 // this is a constant expression.
14053 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14055 *Result = EvalResult.Val.getInt();
14059 // If our only note is the usual "invalid subexpression" note, just point
14060 // the caret at its location rather than producing an essentially
14062 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14063 diag::note_invalid_subexpr_in_const_expr) {
14064 DiagLoc = Notes[0].first;
14068 if (!Folded || !AllowFold) {
14069 if (!Diagnoser.Suppress) {
14070 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14071 for (const PartialDiagnosticAt &Note : Notes)
14072 Diag(Note.first, Note.second);
14075 return ExprError();
14078 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14079 for (const PartialDiagnosticAt &Note : Notes)
14080 Diag(Note.first, Note.second);
14083 *Result = EvalResult.Val.getInt();
14088 // Handle the case where we conclude a expression which we speculatively
14089 // considered to be unevaluated is actually evaluated.
14090 class TransformToPE : public TreeTransform<TransformToPE> {
14091 typedef TreeTransform<TransformToPE> BaseTransform;
14094 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14096 // Make sure we redo semantic analysis
14097 bool AlwaysRebuild() { return true; }
14099 // Make sure we handle LabelStmts correctly.
14100 // FIXME: This does the right thing, but maybe we need a more general
14101 // fix to TreeTransform?
14102 StmtResult TransformLabelStmt(LabelStmt *S) {
14103 S->getDecl()->setStmt(nullptr);
14104 return BaseTransform::TransformLabelStmt(S);
14107 // We need to special-case DeclRefExprs referring to FieldDecls which
14108 // are not part of a member pointer formation; normal TreeTransforming
14109 // doesn't catch this case because of the way we represent them in the AST.
14110 // FIXME: This is a bit ugly; is it really the best way to handle this
14113 // Error on DeclRefExprs referring to FieldDecls.
14114 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14115 if (isa<FieldDecl>(E->getDecl()) &&
14116 !SemaRef.isUnevaluatedContext())
14117 return SemaRef.Diag(E->getLocation(),
14118 diag::err_invalid_non_static_member_use)
14119 << E->getDecl() << E->getSourceRange();
14121 return BaseTransform::TransformDeclRefExpr(E);
14124 // Exception: filter out member pointer formation
14125 ExprResult TransformUnaryOperator(UnaryOperator *E) {
14126 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14129 return BaseTransform::TransformUnaryOperator(E);
14132 ExprResult TransformLambdaExpr(LambdaExpr *E) {
14133 // Lambdas never need to be transformed.
14139 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14140 assert(isUnevaluatedContext() &&
14141 "Should only transform unevaluated expressions");
14142 ExprEvalContexts.back().Context =
14143 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14144 if (isUnevaluatedContext())
14146 return TransformToPE(*this).TransformExpr(E);
14150 Sema::PushExpressionEvaluationContext(
14151 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14152 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14153 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14154 LambdaContextDecl, ExprContext);
14156 if (!MaybeODRUseExprs.empty())
14157 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14161 Sema::PushExpressionEvaluationContext(
14162 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14163 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14164 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14165 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14168 void Sema::PopExpressionEvaluationContext() {
14169 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14170 unsigned NumTypos = Rec.NumTypos;
14172 if (!Rec.Lambdas.empty()) {
14173 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14174 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14175 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14177 if (Rec.isUnevaluated()) {
14178 // C++11 [expr.prim.lambda]p2:
14179 // A lambda-expression shall not appear in an unevaluated operand
14181 D = diag::err_lambda_unevaluated_operand;
14182 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14183 // C++1y [expr.const]p2:
14184 // A conditional-expression e is a core constant expression unless the
14185 // evaluation of e, following the rules of the abstract machine, would
14186 // evaluate [...] a lambda-expression.
14187 D = diag::err_lambda_in_constant_expression;
14188 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14189 // C++17 [expr.prim.lamda]p2:
14190 // A lambda-expression shall not appear [...] in a template-argument.
14191 D = diag::err_lambda_in_invalid_context;
14193 llvm_unreachable("Couldn't infer lambda error message.");
14195 for (const auto *L : Rec.Lambdas)
14196 Diag(L->getLocStart(), D);
14198 // Mark the capture expressions odr-used. This was deferred
14199 // during lambda expression creation.
14200 for (auto *Lambda : Rec.Lambdas) {
14201 for (auto *C : Lambda->capture_inits())
14202 MarkDeclarationsReferencedInExpr(C);
14207 // When are coming out of an unevaluated context, clear out any
14208 // temporaries that we may have created as part of the evaluation of
14209 // the expression in that context: they aren't relevant because they
14210 // will never be constructed.
14211 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14212 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14213 ExprCleanupObjects.end());
14214 Cleanup = Rec.ParentCleanup;
14215 CleanupVarDeclMarking();
14216 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14217 // Otherwise, merge the contexts together.
14219 Cleanup.mergeFrom(Rec.ParentCleanup);
14220 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14221 Rec.SavedMaybeODRUseExprs.end());
14224 // Pop the current expression evaluation context off the stack.
14225 ExprEvalContexts.pop_back();
14227 if (!ExprEvalContexts.empty())
14228 ExprEvalContexts.back().NumTypos += NumTypos;
14230 assert(NumTypos == 0 && "There are outstanding typos after popping the "
14231 "last ExpressionEvaluationContextRecord");
14234 void Sema::DiscardCleanupsInEvaluationContext() {
14235 ExprCleanupObjects.erase(
14236 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14237 ExprCleanupObjects.end());
14239 MaybeODRUseExprs.clear();
14242 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14243 if (!E->getType()->isVariablyModifiedType())
14245 return TransformToPotentiallyEvaluated(E);
14248 /// Are we within a context in which some evaluation could be performed (be it
14249 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14250 /// captured by C++'s idea of an "unevaluated context".
14251 static bool isEvaluatableContext(Sema &SemaRef) {
14252 switch (SemaRef.ExprEvalContexts.back().Context) {
14253 case Sema::ExpressionEvaluationContext::Unevaluated:
14254 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14255 // Expressions in this context are never evaluated.
14258 case Sema::ExpressionEvaluationContext::UnevaluatedList:
14259 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14260 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14261 case Sema::ExpressionEvaluationContext::DiscardedStatement:
14262 // Expressions in this context could be evaluated.
14265 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14266 // Referenced declarations will only be used if the construct in the
14267 // containing expression is used, at which point we'll be given another
14268 // turn to mark them.
14271 llvm_unreachable("Invalid context");
14274 /// Are we within a context in which references to resolved functions or to
14275 /// variables result in odr-use?
14276 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14277 // An expression in a template is not really an expression until it's been
14278 // instantiated, so it doesn't trigger odr-use.
14279 if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14282 switch (SemaRef.ExprEvalContexts.back().Context) {
14283 case Sema::ExpressionEvaluationContext::Unevaluated:
14284 case Sema::ExpressionEvaluationContext::UnevaluatedList:
14285 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14286 case Sema::ExpressionEvaluationContext::DiscardedStatement:
14289 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14290 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14293 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14296 llvm_unreachable("Invalid context");
14299 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14300 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14301 return Func->isConstexpr() &&
14302 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14305 /// Mark a function referenced, and check whether it is odr-used
14306 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14307 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14308 bool MightBeOdrUse) {
14309 assert(Func && "No function?");
14311 Func->setReferenced();
14313 // C++11 [basic.def.odr]p3:
14314 // A function whose name appears as a potentially-evaluated expression is
14315 // odr-used if it is the unique lookup result or the selected member of a
14316 // set of overloaded functions [...].
14318 // We (incorrectly) mark overload resolution as an unevaluated context, so we
14319 // can just check that here.
14320 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14322 // Determine whether we require a function definition to exist, per
14323 // C++11 [temp.inst]p3:
14324 // Unless a function template specialization has been explicitly
14325 // instantiated or explicitly specialized, the function template
14326 // specialization is implicitly instantiated when the specialization is
14327 // referenced in a context that requires a function definition to exist.
14329 // That is either when this is an odr-use, or when a usage of a constexpr
14330 // function occurs within an evaluatable context.
14331 bool NeedDefinition =
14332 OdrUse || (isEvaluatableContext(*this) &&
14333 isImplicitlyDefinableConstexprFunction(Func));
14335 // C++14 [temp.expl.spec]p6:
14336 // If a template [...] is explicitly specialized then that specialization
14337 // shall be declared before the first use of that specialization that would
14338 // cause an implicit instantiation to take place, in every translation unit
14339 // in which such a use occurs
14340 if (NeedDefinition &&
14341 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14342 Func->getMemberSpecializationInfo()))
14343 checkSpecializationVisibility(Loc, Func);
14345 // C++14 [except.spec]p17:
14346 // An exception-specification is considered to be needed when:
14347 // - the function is odr-used or, if it appears in an unevaluated operand,
14348 // would be odr-used if the expression were potentially-evaluated;
14350 // Note, we do this even if MightBeOdrUse is false. That indicates that the
14351 // function is a pure virtual function we're calling, and in that case the
14352 // function was selected by overload resolution and we need to resolve its
14353 // exception specification for a different reason.
14354 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14355 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14356 ResolveExceptionSpec(Loc, FPT);
14358 // If we don't need to mark the function as used, and we don't need to
14359 // try to provide a definition, there's nothing more to do.
14360 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14361 (!NeedDefinition || Func->getBody()))
14364 // Note that this declaration has been used.
14365 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14366 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14367 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14368 if (Constructor->isDefaultConstructor()) {
14369 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14371 DefineImplicitDefaultConstructor(Loc, Constructor);
14372 } else if (Constructor->isCopyConstructor()) {
14373 DefineImplicitCopyConstructor(Loc, Constructor);
14374 } else if (Constructor->isMoveConstructor()) {
14375 DefineImplicitMoveConstructor(Loc, Constructor);
14377 } else if (Constructor->getInheritedConstructor()) {
14378 DefineInheritingConstructor(Loc, Constructor);
14380 } else if (CXXDestructorDecl *Destructor =
14381 dyn_cast<CXXDestructorDecl>(Func)) {
14382 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14383 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14384 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14386 DefineImplicitDestructor(Loc, Destructor);
14388 if (Destructor->isVirtual() && getLangOpts().AppleKext)
14389 MarkVTableUsed(Loc, Destructor->getParent());
14390 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14391 if (MethodDecl->isOverloadedOperator() &&
14392 MethodDecl->getOverloadedOperator() == OO_Equal) {
14393 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14394 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14395 if (MethodDecl->isCopyAssignmentOperator())
14396 DefineImplicitCopyAssignment(Loc, MethodDecl);
14397 else if (MethodDecl->isMoveAssignmentOperator())
14398 DefineImplicitMoveAssignment(Loc, MethodDecl);
14400 } else if (isa<CXXConversionDecl>(MethodDecl) &&
14401 MethodDecl->getParent()->isLambda()) {
14402 CXXConversionDecl *Conversion =
14403 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14404 if (Conversion->isLambdaToBlockPointerConversion())
14405 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14407 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14408 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14409 MarkVTableUsed(Loc, MethodDecl->getParent());
14412 // Recursive functions should be marked when used from another function.
14413 // FIXME: Is this really right?
14414 if (CurContext == Func) return;
14416 // Implicit instantiation of function templates and member functions of
14417 // class templates.
14418 if (Func->isImplicitlyInstantiable()) {
14419 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14420 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14421 bool FirstInstantiation = PointOfInstantiation.isInvalid();
14422 if (FirstInstantiation) {
14423 PointOfInstantiation = Loc;
14424 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14425 } else if (TSK != TSK_ImplicitInstantiation) {
14426 // Use the point of use as the point of instantiation, instead of the
14427 // point of explicit instantiation (which we track as the actual point of
14428 // instantiation). This gives better backtraces in diagnostics.
14429 PointOfInstantiation = Loc;
14432 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14433 Func->isConstexpr()) {
14434 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14435 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14436 CodeSynthesisContexts.size())
14437 PendingLocalImplicitInstantiations.push_back(
14438 std::make_pair(Func, PointOfInstantiation));
14439 else if (Func->isConstexpr())
14440 // Do not defer instantiations of constexpr functions, to avoid the
14441 // expression evaluator needing to call back into Sema if it sees a
14442 // call to such a function.
14443 InstantiateFunctionDefinition(PointOfInstantiation, Func);
14445 Func->setInstantiationIsPending(true);
14446 PendingInstantiations.push_back(std::make_pair(Func,
14447 PointOfInstantiation));
14448 // Notify the consumer that a function was implicitly instantiated.
14449 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14453 // Walk redefinitions, as some of them may be instantiable.
14454 for (auto i : Func->redecls()) {
14455 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14456 MarkFunctionReferenced(Loc, i, OdrUse);
14460 if (!OdrUse) return;
14462 // Keep track of used but undefined functions.
14463 if (!Func->isDefined()) {
14464 if (mightHaveNonExternalLinkage(Func))
14465 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14466 else if (Func->getMostRecentDecl()->isInlined() &&
14467 !LangOpts.GNUInline &&
14468 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14469 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14470 else if (isExternalWithNoLinkageType(Func))
14471 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14474 Func->markUsed(Context);
14478 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14479 ValueDecl *var, DeclContext *DC) {
14480 DeclContext *VarDC = var->getDeclContext();
14482 // If the parameter still belongs to the translation unit, then
14483 // we're actually just using one parameter in the declaration of
14485 if (isa<ParmVarDecl>(var) &&
14486 isa<TranslationUnitDecl>(VarDC))
14489 // For C code, don't diagnose about capture if we're not actually in code
14490 // right now; it's impossible to write a non-constant expression outside of
14491 // function context, so we'll get other (more useful) diagnostics later.
14493 // For C++, things get a bit more nasty... it would be nice to suppress this
14494 // diagnostic for certain cases like using a local variable in an array bound
14495 // for a member of a local class, but the correct predicate is not obvious.
14496 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14499 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14500 unsigned ContextKind = 3; // unknown
14501 if (isa<CXXMethodDecl>(VarDC) &&
14502 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14504 } else if (isa<FunctionDecl>(VarDC)) {
14506 } else if (isa<BlockDecl>(VarDC)) {
14510 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14511 << var << ValueKind << ContextKind << VarDC;
14512 S.Diag(var->getLocation(), diag::note_entity_declared_at)
14515 // FIXME: Add additional diagnostic info about class etc. which prevents
14520 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14521 bool &SubCapturesAreNested,
14522 QualType &CaptureType,
14523 QualType &DeclRefType) {
14524 // Check whether we've already captured it.
14525 if (CSI->CaptureMap.count(Var)) {
14526 // If we found a capture, any subcaptures are nested.
14527 SubCapturesAreNested = true;
14529 // Retrieve the capture type for this variable.
14530 CaptureType = CSI->getCapture(Var).getCaptureType();
14532 // Compute the type of an expression that refers to this variable.
14533 DeclRefType = CaptureType.getNonReferenceType();
14535 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14536 // are mutable in the sense that user can change their value - they are
14537 // private instances of the captured declarations.
14538 const Capture &Cap = CSI->getCapture(Var);
14539 if (Cap.isCopyCapture() &&
14540 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14541 !(isa<CapturedRegionScopeInfo>(CSI) &&
14542 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14543 DeclRefType.addConst();
14549 // Only block literals, captured statements, and lambda expressions can
14550 // capture; other scopes don't work.
14551 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14552 SourceLocation Loc,
14553 const bool Diagnose, Sema &S) {
14554 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14555 return getLambdaAwareParentOfDeclContext(DC);
14556 else if (Var->hasLocalStorage()) {
14558 diagnoseUncapturableValueReference(S, Loc, Var, DC);
14563 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14564 // certain types of variables (unnamed, variably modified types etc.)
14565 // so check for eligibility.
14566 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14567 SourceLocation Loc,
14568 const bool Diagnose, Sema &S) {
14570 bool IsBlock = isa<BlockScopeInfo>(CSI);
14571 bool IsLambda = isa<LambdaScopeInfo>(CSI);
14573 // Lambdas are not allowed to capture unnamed variables
14574 // (e.g. anonymous unions).
14575 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14576 // assuming that's the intent.
14577 if (IsLambda && !Var->getDeclName()) {
14579 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14580 S.Diag(Var->getLocation(), diag::note_declared_at);
14585 // Prohibit variably-modified types in blocks; they're difficult to deal with.
14586 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14588 S.Diag(Loc, diag::err_ref_vm_type);
14589 S.Diag(Var->getLocation(), diag::note_previous_decl)
14590 << Var->getDeclName();
14594 // Prohibit structs with flexible array members too.
14595 // We cannot capture what is in the tail end of the struct.
14596 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14597 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14600 S.Diag(Loc, diag::err_ref_flexarray_type);
14602 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14603 << Var->getDeclName();
14604 S.Diag(Var->getLocation(), diag::note_previous_decl)
14605 << Var->getDeclName();
14610 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14611 // Lambdas and captured statements are not allowed to capture __block
14612 // variables; they don't support the expected semantics.
14613 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14615 S.Diag(Loc, diag::err_capture_block_variable)
14616 << Var->getDeclName() << !IsLambda;
14617 S.Diag(Var->getLocation(), diag::note_previous_decl)
14618 << Var->getDeclName();
14622 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14623 if (S.getLangOpts().OpenCL && IsBlock &&
14624 Var->getType()->isBlockPointerType()) {
14626 S.Diag(Loc, diag::err_opencl_block_ref_block);
14633 // Returns true if the capture by block was successful.
14634 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14635 SourceLocation Loc,
14636 const bool BuildAndDiagnose,
14637 QualType &CaptureType,
14638 QualType &DeclRefType,
14641 Expr *CopyExpr = nullptr;
14642 bool ByRef = false;
14644 // Blocks are not allowed to capture arrays.
14645 if (CaptureType->isArrayType()) {
14646 if (BuildAndDiagnose) {
14647 S.Diag(Loc, diag::err_ref_array_type);
14648 S.Diag(Var->getLocation(), diag::note_previous_decl)
14649 << Var->getDeclName();
14654 // Forbid the block-capture of autoreleasing variables.
14655 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14656 if (BuildAndDiagnose) {
14657 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14659 S.Diag(Var->getLocation(), diag::note_previous_decl)
14660 << Var->getDeclName();
14665 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14666 if (const auto *PT = CaptureType->getAs<PointerType>()) {
14667 // This function finds out whether there is an AttributedType of kind
14668 // attr_objc_ownership in Ty. The existence of AttributedType of kind
14669 // attr_objc_ownership implies __autoreleasing was explicitly specified
14670 // rather than being added implicitly by the compiler.
14671 auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14672 while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14673 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14676 // Peel off AttributedTypes that are not of kind objc_ownership.
14677 Ty = AttrTy->getModifiedType();
14683 QualType PointeeTy = PT->getPointeeType();
14685 if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14686 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14687 !IsObjCOwnershipAttributedType(PointeeTy)) {
14688 if (BuildAndDiagnose) {
14689 SourceLocation VarLoc = Var->getLocation();
14690 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14691 S.Diag(VarLoc, diag::note_declare_parameter_strong);
14696 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14697 if (HasBlocksAttr || CaptureType->isReferenceType() ||
14698 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14699 // Block capture by reference does not change the capture or
14700 // declaration reference types.
14703 // Block capture by copy introduces 'const'.
14704 CaptureType = CaptureType.getNonReferenceType().withConst();
14705 DeclRefType = CaptureType;
14707 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14708 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14709 // The capture logic needs the destructor, so make sure we mark it.
14710 // Usually this is unnecessary because most local variables have
14711 // their destructors marked at declaration time, but parameters are
14712 // an exception because it's technically only the call site that
14713 // actually requires the destructor.
14714 if (isa<ParmVarDecl>(Var))
14715 S.FinalizeVarWithDestructor(Var, Record);
14717 // Enter a new evaluation context to insulate the copy
14718 // full-expression.
14719 EnterExpressionEvaluationContext scope(
14720 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14722 // According to the blocks spec, the capture of a variable from
14723 // the stack requires a const copy constructor. This is not true
14724 // of the copy/move done to move a __block variable to the heap.
14725 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14726 DeclRefType.withConst(),
14730 = S.PerformCopyInitialization(
14731 InitializedEntity::InitializeBlock(Var->getLocation(),
14732 CaptureType, false),
14735 // Build a full-expression copy expression if initialization
14736 // succeeded and used a non-trivial constructor. Recover from
14737 // errors by pretending that the copy isn't necessary.
14738 if (!Result.isInvalid() &&
14739 !cast<CXXConstructExpr>(Result.get())->getConstructor()
14741 Result = S.MaybeCreateExprWithCleanups(Result);
14742 CopyExpr = Result.get();
14748 // Actually capture the variable.
14749 if (BuildAndDiagnose)
14750 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14751 SourceLocation(), CaptureType, CopyExpr);
14758 /// Capture the given variable in the captured region.
14759 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14761 SourceLocation Loc,
14762 const bool BuildAndDiagnose,
14763 QualType &CaptureType,
14764 QualType &DeclRefType,
14765 const bool RefersToCapturedVariable,
14767 // By default, capture variables by reference.
14769 // Using an LValue reference type is consistent with Lambdas (see below).
14770 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14771 if (S.isOpenMPCapturedDecl(Var)) {
14772 bool HasConst = DeclRefType.isConstQualified();
14773 DeclRefType = DeclRefType.getUnqualifiedType();
14774 // Don't lose diagnostics about assignments to const.
14776 DeclRefType.addConst();
14778 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14782 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14784 CaptureType = DeclRefType;
14786 Expr *CopyExpr = nullptr;
14787 if (BuildAndDiagnose) {
14788 // The current implementation assumes that all variables are captured
14789 // by references. Since there is no capture by copy, no expression
14790 // evaluation will be needed.
14791 RecordDecl *RD = RSI->TheRecordDecl;
14794 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14795 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14796 nullptr, false, ICIS_NoInit);
14797 Field->setImplicit(true);
14798 Field->setAccess(AS_private);
14799 RD->addDecl(Field);
14800 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14801 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14803 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14804 DeclRefType, VK_LValue, Loc);
14805 Var->setReferenced(true);
14806 Var->markUsed(S.Context);
14809 // Actually capture the variable.
14810 if (BuildAndDiagnose)
14811 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14812 SourceLocation(), CaptureType, CopyExpr);
14818 /// Create a field within the lambda class for the variable
14819 /// being captured.
14820 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14821 QualType FieldType, QualType DeclRefType,
14822 SourceLocation Loc,
14823 bool RefersToCapturedVariable) {
14824 CXXRecordDecl *Lambda = LSI->Lambda;
14826 // Build the non-static data member.
14828 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14829 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14830 nullptr, false, ICIS_NoInit);
14831 Field->setImplicit(true);
14832 Field->setAccess(AS_private);
14833 Lambda->addDecl(Field);
14836 /// Capture the given variable in the lambda.
14837 static bool captureInLambda(LambdaScopeInfo *LSI,
14839 SourceLocation Loc,
14840 const bool BuildAndDiagnose,
14841 QualType &CaptureType,
14842 QualType &DeclRefType,
14843 const bool RefersToCapturedVariable,
14844 const Sema::TryCaptureKind Kind,
14845 SourceLocation EllipsisLoc,
14846 const bool IsTopScope,
14849 // Determine whether we are capturing by reference or by value.
14850 bool ByRef = false;
14851 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14852 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14854 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14857 // Compute the type of the field that will capture this variable.
14859 // C++11 [expr.prim.lambda]p15:
14860 // An entity is captured by reference if it is implicitly or
14861 // explicitly captured but not captured by copy. It is
14862 // unspecified whether additional unnamed non-static data
14863 // members are declared in the closure type for entities
14864 // captured by reference.
14866 // FIXME: It is not clear whether we want to build an lvalue reference
14867 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14868 // to do the former, while EDG does the latter. Core issue 1249 will
14869 // clarify, but for now we follow GCC because it's a more permissive and
14870 // easily defensible position.
14871 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14873 // C++11 [expr.prim.lambda]p14:
14874 // For each entity captured by copy, an unnamed non-static
14875 // data member is declared in the closure type. The
14876 // declaration order of these members is unspecified. The type
14877 // of such a data member is the type of the corresponding
14878 // captured entity if the entity is not a reference to an
14879 // object, or the referenced type otherwise. [Note: If the
14880 // captured entity is a reference to a function, the
14881 // corresponding data member is also a reference to a
14882 // function. - end note ]
14883 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14884 if (!RefType->getPointeeType()->isFunctionType())
14885 CaptureType = RefType->getPointeeType();
14888 // Forbid the lambda copy-capture of autoreleasing variables.
14889 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14890 if (BuildAndDiagnose) {
14891 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14892 S.Diag(Var->getLocation(), diag::note_previous_decl)
14893 << Var->getDeclName();
14898 // Make sure that by-copy captures are of a complete and non-abstract type.
14899 if (BuildAndDiagnose) {
14900 if (!CaptureType->isDependentType() &&
14901 S.RequireCompleteType(Loc, CaptureType,
14902 diag::err_capture_of_incomplete_type,
14903 Var->getDeclName()))
14906 if (S.RequireNonAbstractType(Loc, CaptureType,
14907 diag::err_capture_of_abstract_type))
14912 // Capture this variable in the lambda.
14913 if (BuildAndDiagnose)
14914 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14915 RefersToCapturedVariable);
14917 // Compute the type of a reference to this captured variable.
14919 DeclRefType = CaptureType.getNonReferenceType();
14921 // C++ [expr.prim.lambda]p5:
14922 // The closure type for a lambda-expression has a public inline
14923 // function call operator [...]. This function call operator is
14924 // declared const (9.3.1) if and only if the lambda-expression's
14925 // parameter-declaration-clause is not followed by mutable.
14926 DeclRefType = CaptureType.getNonReferenceType();
14927 if (!LSI->Mutable && !CaptureType->isReferenceType())
14928 DeclRefType.addConst();
14931 // Add the capture.
14932 if (BuildAndDiagnose)
14933 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14934 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14939 bool Sema::tryCaptureVariable(
14940 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14941 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14942 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14943 // An init-capture is notionally from the context surrounding its
14944 // declaration, but its parent DC is the lambda class.
14945 DeclContext *VarDC = Var->getDeclContext();
14946 if (Var->isInitCapture())
14947 VarDC = VarDC->getParent();
14949 DeclContext *DC = CurContext;
14950 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14951 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14952 // We need to sync up the Declaration Context with the
14953 // FunctionScopeIndexToStopAt
14954 if (FunctionScopeIndexToStopAt) {
14955 unsigned FSIndex = FunctionScopes.size() - 1;
14956 while (FSIndex != MaxFunctionScopesIndex) {
14957 DC = getLambdaAwareParentOfDeclContext(DC);
14963 // If the variable is declared in the current context, there is no need to
14965 if (VarDC == DC) return true;
14967 // Capture global variables if it is required to use private copy of this
14969 bool IsGlobal = !Var->hasLocalStorage();
14970 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14972 Var = Var->getCanonicalDecl();
14974 // Walk up the stack to determine whether we can capture the variable,
14975 // performing the "simple" checks that don't depend on type. We stop when
14976 // we've either hit the declared scope of the variable or find an existing
14977 // capture of that variable. We start from the innermost capturing-entity
14978 // (the DC) and ensure that all intervening capturing-entities
14979 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14980 // declcontext can either capture the variable or have already captured
14982 CaptureType = Var->getType();
14983 DeclRefType = CaptureType.getNonReferenceType();
14984 bool Nested = false;
14985 bool Explicit = (Kind != TryCapture_Implicit);
14986 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14988 // Only block literals, captured statements, and lambda expressions can
14989 // capture; other scopes don't work.
14990 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14994 // We need to check for the parent *first* because, if we *have*
14995 // private-captured a global variable, we need to recursively capture it in
14996 // intermediate blocks, lambdas, etc.
14999 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15005 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
15006 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15009 // Check whether we've already captured it.
15010 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15012 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15015 // If we are instantiating a generic lambda call operator body,
15016 // we do not want to capture new variables. What was captured
15017 // during either a lambdas transformation or initial parsing
15019 if (isGenericLambdaCallOperatorSpecialization(DC)) {
15020 if (BuildAndDiagnose) {
15021 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15022 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15023 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15024 Diag(Var->getLocation(), diag::note_previous_decl)
15025 << Var->getDeclName();
15026 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
15028 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15032 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15033 // certain types of variables (unnamed, variably modified types etc.)
15034 // so check for eligibility.
15035 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15038 // Try to capture variable-length arrays types.
15039 if (Var->getType()->isVariablyModifiedType()) {
15040 // We're going to walk down into the type and look for VLA
15042 QualType QTy = Var->getType();
15043 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15044 QTy = PVD->getOriginalType();
15045 captureVariablyModifiedType(Context, QTy, CSI);
15048 if (getLangOpts().OpenMP) {
15049 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15050 // OpenMP private variables should not be captured in outer scope, so
15051 // just break here. Similarly, global variables that are captured in a
15052 // target region should not be captured outside the scope of the region.
15053 if (RSI->CapRegionKind == CR_OpenMP) {
15054 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15055 auto IsTargetCap = !IsOpenMPPrivateDecl &&
15056 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15057 // When we detect target captures we are looking from inside the
15058 // target region, therefore we need to propagate the capture from the
15059 // enclosing region. Therefore, the capture is not initially nested.
15061 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15063 if (IsTargetCap || IsOpenMPPrivateDecl) {
15064 Nested = !IsTargetCap;
15065 DeclRefType = DeclRefType.getUnqualifiedType();
15066 CaptureType = Context.getLValueReferenceType(DeclRefType);
15072 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15073 // No capture-default, and this is not an explicit capture
15074 // so cannot capture this variable.
15075 if (BuildAndDiagnose) {
15076 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15077 Diag(Var->getLocation(), diag::note_previous_decl)
15078 << Var->getDeclName();
15079 if (cast<LambdaScopeInfo>(CSI)->Lambda)
15080 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
15081 diag::note_lambda_decl);
15082 // FIXME: If we error out because an outer lambda can not implicitly
15083 // capture a variable that an inner lambda explicitly captures, we
15084 // should have the inner lambda do the explicit capture - because
15085 // it makes for cleaner diagnostics later. This would purely be done
15086 // so that the diagnostic does not misleadingly claim that a variable
15087 // can not be captured by a lambda implicitly even though it is captured
15088 // explicitly. Suggestion:
15089 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15090 // at the function head
15091 // - cache the StartingDeclContext - this must be a lambda
15092 // - captureInLambda in the innermost lambda the variable.
15097 FunctionScopesIndex--;
15100 } while (!VarDC->Equals(DC));
15102 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15103 // computing the type of the capture at each step, checking type-specific
15104 // requirements, and adding captures if requested.
15105 // If the variable had already been captured previously, we start capturing
15106 // at the lambda nested within that one.
15107 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15109 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15111 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15112 if (!captureInBlock(BSI, Var, ExprLoc,
15113 BuildAndDiagnose, CaptureType,
15114 DeclRefType, Nested, *this))
15117 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15118 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15119 BuildAndDiagnose, CaptureType,
15120 DeclRefType, Nested, *this))
15124 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15125 if (!captureInLambda(LSI, Var, ExprLoc,
15126 BuildAndDiagnose, CaptureType,
15127 DeclRefType, Nested, Kind, EllipsisLoc,
15128 /*IsTopScope*/I == N - 1, *this))
15136 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15137 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15138 QualType CaptureType;
15139 QualType DeclRefType;
15140 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15141 /*BuildAndDiagnose=*/true, CaptureType,
15142 DeclRefType, nullptr);
15145 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15146 QualType CaptureType;
15147 QualType DeclRefType;
15148 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15149 /*BuildAndDiagnose=*/false, CaptureType,
15150 DeclRefType, nullptr);
15153 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15154 QualType CaptureType;
15155 QualType DeclRefType;
15157 // Determine whether we can capture this variable.
15158 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15159 /*BuildAndDiagnose=*/false, CaptureType,
15160 DeclRefType, nullptr))
15163 return DeclRefType;
15168 // If either the type of the variable or the initializer is dependent,
15169 // return false. Otherwise, determine whether the variable is a constant
15170 // expression. Use this if you need to know if a variable that might or
15171 // might not be dependent is truly a constant expression.
15172 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15173 ASTContext &Context) {
15175 if (Var->getType()->isDependentType())
15177 const VarDecl *DefVD = nullptr;
15178 Var->getAnyInitializer(DefVD);
15181 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15182 Expr *Init = cast<Expr>(Eval->Value);
15183 if (Init->isValueDependent())
15185 return IsVariableAConstantExpression(Var, Context);
15189 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15190 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15191 // an object that satisfies the requirements for appearing in a
15192 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15193 // is immediately applied." This function handles the lvalue-to-rvalue
15194 // conversion part.
15195 MaybeODRUseExprs.erase(E->IgnoreParens());
15197 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15198 // to a variable that is a constant expression, and if so, identify it as
15199 // a reference to a variable that does not involve an odr-use of that
15201 if (LambdaScopeInfo *LSI = getCurLambda()) {
15202 Expr *SansParensExpr = E->IgnoreParens();
15203 VarDecl *Var = nullptr;
15204 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15205 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15206 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15207 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15209 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15210 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15214 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15215 Res = CorrectDelayedTyposInExpr(Res);
15217 if (!Res.isUsable())
15220 // If a constant-expression is a reference to a variable where we delay
15221 // deciding whether it is an odr-use, just assume we will apply the
15222 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
15223 // (a non-type template argument), we have special handling anyway.
15224 UpdateMarkingForLValueToRValue(Res.get());
15228 void Sema::CleanupVarDeclMarking() {
15229 for (Expr *E : MaybeODRUseExprs) {
15231 SourceLocation Loc;
15232 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15233 Var = cast<VarDecl>(DRE->getDecl());
15234 Loc = DRE->getLocation();
15235 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15236 Var = cast<VarDecl>(ME->getMemberDecl());
15237 Loc = ME->getMemberLoc();
15239 llvm_unreachable("Unexpected expression");
15242 MarkVarDeclODRUsed(Var, Loc, *this,
15243 /*MaxFunctionScopeIndex Pointer*/ nullptr);
15246 MaybeODRUseExprs.clear();
15250 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15251 VarDecl *Var, Expr *E) {
15252 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15253 "Invalid Expr argument to DoMarkVarDeclReferenced");
15254 Var->setReferenced();
15256 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15258 bool OdrUseContext = isOdrUseContext(SemaRef);
15259 bool UsableInConstantExpr =
15260 Var->isUsableInConstantExpressions(SemaRef.Context);
15261 bool NeedDefinition =
15262 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15264 VarTemplateSpecializationDecl *VarSpec =
15265 dyn_cast<VarTemplateSpecializationDecl>(Var);
15266 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15267 "Can't instantiate a partial template specialization.");
15269 // If this might be a member specialization of a static data member, check
15270 // the specialization is visible. We already did the checks for variable
15271 // template specializations when we created them.
15272 if (NeedDefinition && TSK != TSK_Undeclared &&
15273 !isa<VarTemplateSpecializationDecl>(Var))
15274 SemaRef.checkSpecializationVisibility(Loc, Var);
15276 // Perform implicit instantiation of static data members, static data member
15277 // templates of class templates, and variable template specializations. Delay
15278 // instantiations of variable templates, except for those that could be used
15279 // in a constant expression.
15280 if (NeedDefinition && isTemplateInstantiation(TSK)) {
15281 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15282 // instantiation declaration if a variable is usable in a constant
15283 // expression (among other cases).
15284 bool TryInstantiating =
15285 TSK == TSK_ImplicitInstantiation ||
15286 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15288 if (TryInstantiating) {
15289 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15290 bool FirstInstantiation = PointOfInstantiation.isInvalid();
15291 if (FirstInstantiation) {
15292 PointOfInstantiation = Loc;
15293 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15296 bool InstantiationDependent = false;
15297 bool IsNonDependent =
15298 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15299 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15302 // Do not instantiate specializations that are still type-dependent.
15303 if (IsNonDependent) {
15304 if (UsableInConstantExpr) {
15305 // Do not defer instantiations of variables that could be used in a
15306 // constant expression.
15307 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15308 } else if (FirstInstantiation ||
15309 isa<VarTemplateSpecializationDecl>(Var)) {
15310 // FIXME: For a specialization of a variable template, we don't
15311 // distinguish between "declaration and type implicitly instantiated"
15312 // and "implicit instantiation of definition requested", so we have
15313 // no direct way to avoid enqueueing the pending instantiation
15315 SemaRef.PendingInstantiations
15316 .push_back(std::make_pair(Var, PointOfInstantiation));
15322 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15323 // the requirements for appearing in a constant expression (5.19) and, if
15324 // it is an object, the lvalue-to-rvalue conversion (4.1)
15325 // is immediately applied." We check the first part here, and
15326 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15327 // Note that we use the C++11 definition everywhere because nothing in
15328 // C++03 depends on whether we get the C++03 version correct. The second
15329 // part does not apply to references, since they are not objects.
15330 if (OdrUseContext && E &&
15331 IsVariableAConstantExpression(Var, SemaRef.Context)) {
15332 // A reference initialized by a constant expression can never be
15333 // odr-used, so simply ignore it.
15334 if (!Var->getType()->isReferenceType() ||
15335 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15336 SemaRef.MaybeODRUseExprs.insert(E);
15337 } else if (OdrUseContext) {
15338 MarkVarDeclODRUsed(Var, Loc, SemaRef,
15339 /*MaxFunctionScopeIndex ptr*/ nullptr);
15340 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15341 // If this is a dependent context, we don't need to mark variables as
15342 // odr-used, but we may still need to track them for lambda capture.
15343 // FIXME: Do we also need to do this inside dependent typeid expressions
15344 // (which are modeled as unevaluated at this point)?
15345 const bool RefersToEnclosingScope =
15346 (SemaRef.CurContext != Var->getDeclContext() &&
15347 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15348 if (RefersToEnclosingScope) {
15349 LambdaScopeInfo *const LSI =
15350 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15351 if (LSI && (!LSI->CallOperator ||
15352 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15353 // If a variable could potentially be odr-used, defer marking it so
15354 // until we finish analyzing the full expression for any
15355 // lvalue-to-rvalue
15356 // or discarded value conversions that would obviate odr-use.
15357 // Add it to the list of potential captures that will be analyzed
15358 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15359 // unless the variable is a reference that was initialized by a constant
15360 // expression (this will never need to be captured or odr-used).
15361 assert(E && "Capture variable should be used in an expression.");
15362 if (!Var->getType()->isReferenceType() ||
15363 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15364 LSI->addPotentialCapture(E->IgnoreParens());
15370 /// Mark a variable referenced, and check whether it is odr-used
15371 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
15372 /// used directly for normal expressions referring to VarDecl.
15373 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15374 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15377 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15378 Decl *D, Expr *E, bool MightBeOdrUse) {
15379 if (SemaRef.isInOpenMPDeclareTargetContext())
15380 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15382 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15383 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15387 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15389 // If this is a call to a method via a cast, also mark the method in the
15390 // derived class used in case codegen can devirtualize the call.
15391 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15394 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15397 // Only attempt to devirtualize if this is truly a virtual call.
15398 bool IsVirtualCall = MD->isVirtual() &&
15399 ME->performsVirtualDispatch(SemaRef.getLangOpts());
15400 if (!IsVirtualCall)
15403 // If it's possible to devirtualize the call, mark the called function
15405 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15406 ME->getBase(), SemaRef.getLangOpts().AppleKext);
15408 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15411 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15412 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15413 // TODO: update this with DR# once a defect report is filed.
15414 // C++11 defect. The address of a pure member should not be an ODR use, even
15415 // if it's a qualified reference.
15416 bool OdrUse = true;
15417 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15418 if (Method->isVirtual() &&
15419 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15421 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15424 /// Perform reference-marking and odr-use handling for a MemberExpr.
15425 void Sema::MarkMemberReferenced(MemberExpr *E) {
15426 // C++11 [basic.def.odr]p2:
15427 // A non-overloaded function whose name appears as a potentially-evaluated
15428 // expression or a member of a set of candidate functions, if selected by
15429 // overload resolution when referred to from a potentially-evaluated
15430 // expression, is odr-used, unless it is a pure virtual function and its
15431 // name is not explicitly qualified.
15432 bool MightBeOdrUse = true;
15433 if (E->performsVirtualDispatch(getLangOpts())) {
15434 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15435 if (Method->isPure())
15436 MightBeOdrUse = false;
15438 SourceLocation Loc = E->getMemberLoc().isValid() ?
15439 E->getMemberLoc() : E->getLocStart();
15440 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15443 /// Perform marking for a reference to an arbitrary declaration. It
15444 /// marks the declaration referenced, and performs odr-use checking for
15445 /// functions and variables. This method should not be used when building a
15446 /// normal expression which refers to a variable.
15447 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15448 bool MightBeOdrUse) {
15449 if (MightBeOdrUse) {
15450 if (auto *VD = dyn_cast<VarDecl>(D)) {
15451 MarkVariableReferenced(Loc, VD);
15455 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15456 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15459 D->setReferenced();
15463 // Mark all of the declarations used by a type as referenced.
15464 // FIXME: Not fully implemented yet! We need to have a better understanding
15465 // of when we're entering a context we should not recurse into.
15466 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15467 // TreeTransforms rebuilding the type in a new context. Rather than
15468 // duplicating the TreeTransform logic, we should consider reusing it here.
15469 // Currently that causes problems when rebuilding LambdaExprs.
15470 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15472 SourceLocation Loc;
15475 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15477 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15479 bool TraverseTemplateArgument(const TemplateArgument &Arg);
15483 bool MarkReferencedDecls::TraverseTemplateArgument(
15484 const TemplateArgument &Arg) {
15486 // A non-type template argument is a constant-evaluated context.
15487 EnterExpressionEvaluationContext Evaluated(
15488 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15489 if (Arg.getKind() == TemplateArgument::Declaration) {
15490 if (Decl *D = Arg.getAsDecl())
15491 S.MarkAnyDeclReferenced(Loc, D, true);
15492 } else if (Arg.getKind() == TemplateArgument::Expression) {
15493 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15497 return Inherited::TraverseTemplateArgument(Arg);
15500 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15501 MarkReferencedDecls Marker(*this, Loc);
15502 Marker.TraverseType(T);
15506 /// Helper class that marks all of the declarations referenced by
15507 /// potentially-evaluated subexpressions as "referenced".
15508 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15510 bool SkipLocalVariables;
15513 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15515 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15516 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15518 void VisitDeclRefExpr(DeclRefExpr *E) {
15519 // If we were asked not to visit local variables, don't.
15520 if (SkipLocalVariables) {
15521 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15522 if (VD->hasLocalStorage())
15526 S.MarkDeclRefReferenced(E);
15529 void VisitMemberExpr(MemberExpr *E) {
15530 S.MarkMemberReferenced(E);
15531 Inherited::VisitMemberExpr(E);
15534 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15535 S.MarkFunctionReferenced(E->getLocStart(),
15536 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15537 Visit(E->getSubExpr());
15540 void VisitCXXNewExpr(CXXNewExpr *E) {
15541 if (E->getOperatorNew())
15542 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15543 if (E->getOperatorDelete())
15544 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15545 Inherited::VisitCXXNewExpr(E);
15548 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15549 if (E->getOperatorDelete())
15550 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15551 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15552 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15553 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15554 S.MarkFunctionReferenced(E->getLocStart(),
15555 S.LookupDestructor(Record));
15558 Inherited::VisitCXXDeleteExpr(E);
15561 void VisitCXXConstructExpr(CXXConstructExpr *E) {
15562 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15563 Inherited::VisitCXXConstructExpr(E);
15566 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15567 Visit(E->getExpr());
15570 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15571 Inherited::VisitImplicitCastExpr(E);
15573 if (E->getCastKind() == CK_LValueToRValue)
15574 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15579 /// Mark any declarations that appear within this expression or any
15580 /// potentially-evaluated subexpressions as "referenced".
15582 /// \param SkipLocalVariables If true, don't mark local variables as
15584 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15585 bool SkipLocalVariables) {
15586 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15589 /// Emit a diagnostic that describes an effect on the run-time behavior
15590 /// of the program being compiled.
15592 /// This routine emits the given diagnostic when the code currently being
15593 /// type-checked is "potentially evaluated", meaning that there is a
15594 /// possibility that the code will actually be executable. Code in sizeof()
15595 /// expressions, code used only during overload resolution, etc., are not
15596 /// potentially evaluated. This routine will suppress such diagnostics or,
15597 /// in the absolutely nutty case of potentially potentially evaluated
15598 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15601 /// This routine should be used for all diagnostics that describe the run-time
15602 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15603 /// Failure to do so will likely result in spurious diagnostics or failures
15604 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15605 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15606 const PartialDiagnostic &PD) {
15607 switch (ExprEvalContexts.back().Context) {
15608 case ExpressionEvaluationContext::Unevaluated:
15609 case ExpressionEvaluationContext::UnevaluatedList:
15610 case ExpressionEvaluationContext::UnevaluatedAbstract:
15611 case ExpressionEvaluationContext::DiscardedStatement:
15612 // The argument will never be evaluated, so don't complain.
15615 case ExpressionEvaluationContext::ConstantEvaluated:
15616 // Relevant diagnostics should be produced by constant evaluation.
15619 case ExpressionEvaluationContext::PotentiallyEvaluated:
15620 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15621 if (Statement && getCurFunctionOrMethodDecl()) {
15622 FunctionScopes.back()->PossiblyUnreachableDiags.
15623 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15627 // The initializer of a constexpr variable or of the first declaration of a
15628 // static data member is not syntactically a constant evaluated constant,
15629 // but nonetheless is always required to be a constant expression, so we
15630 // can skip diagnosing.
15631 // FIXME: Using the mangling context here is a hack.
15632 if (auto *VD = dyn_cast_or_null<VarDecl>(
15633 ExprEvalContexts.back().ManglingContextDecl)) {
15634 if (VD->isConstexpr() ||
15635 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15637 // FIXME: For any other kind of variable, we should build a CFG for its
15638 // initializer and check whether the context in question is reachable.
15648 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15649 CallExpr *CE, FunctionDecl *FD) {
15650 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15653 // If we're inside a decltype's expression, don't check for a valid return
15654 // type or construct temporaries until we know whether this is the last call.
15655 if (ExprEvalContexts.back().ExprContext ==
15656 ExpressionEvaluationContextRecord::EK_Decltype) {
15657 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15661 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15666 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15667 : FD(FD), CE(CE) { }
15669 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15671 S.Diag(Loc, diag::err_call_incomplete_return)
15672 << T << CE->getSourceRange();
15676 S.Diag(Loc, diag::err_call_function_incomplete_return)
15677 << CE->getSourceRange() << FD->getDeclName() << T;
15678 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15679 << FD->getDeclName();
15681 } Diagnoser(FD, CE);
15683 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15689 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15690 // will prevent this condition from triggering, which is what we want.
15691 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15692 SourceLocation Loc;
15694 unsigned diagnostic = diag::warn_condition_is_assignment;
15695 bool IsOrAssign = false;
15697 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15698 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15701 IsOrAssign = Op->getOpcode() == BO_OrAssign;
15703 // Greylist some idioms by putting them into a warning subcategory.
15704 if (ObjCMessageExpr *ME
15705 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15706 Selector Sel = ME->getSelector();
15708 // self = [<foo> init...]
15709 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15710 diagnostic = diag::warn_condition_is_idiomatic_assignment;
15712 // <foo> = [<bar> nextObject]
15713 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15714 diagnostic = diag::warn_condition_is_idiomatic_assignment;
15717 Loc = Op->getOperatorLoc();
15718 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15719 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15722 IsOrAssign = Op->getOperator() == OO_PipeEqual;
15723 Loc = Op->getOperatorLoc();
15724 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15725 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15727 // Not an assignment.
15731 Diag(Loc, diagnostic) << E->getSourceRange();
15733 SourceLocation Open = E->getLocStart();
15734 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15735 Diag(Loc, diag::note_condition_assign_silence)
15736 << FixItHint::CreateInsertion(Open, "(")
15737 << FixItHint::CreateInsertion(Close, ")");
15740 Diag(Loc, diag::note_condition_or_assign_to_comparison)
15741 << FixItHint::CreateReplacement(Loc, "!=");
15743 Diag(Loc, diag::note_condition_assign_to_comparison)
15744 << FixItHint::CreateReplacement(Loc, "==");
15747 /// Redundant parentheses over an equality comparison can indicate
15748 /// that the user intended an assignment used as condition.
15749 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15750 // Don't warn if the parens came from a macro.
15751 SourceLocation parenLoc = ParenE->getLocStart();
15752 if (parenLoc.isInvalid() || parenLoc.isMacroID())
15754 // Don't warn for dependent expressions.
15755 if (ParenE->isTypeDependent())
15758 Expr *E = ParenE->IgnoreParens();
15760 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15761 if (opE->getOpcode() == BO_EQ &&
15762 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15763 == Expr::MLV_Valid) {
15764 SourceLocation Loc = opE->getOperatorLoc();
15766 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15767 SourceRange ParenERange = ParenE->getSourceRange();
15768 Diag(Loc, diag::note_equality_comparison_silence)
15769 << FixItHint::CreateRemoval(ParenERange.getBegin())
15770 << FixItHint::CreateRemoval(ParenERange.getEnd());
15771 Diag(Loc, diag::note_equality_comparison_to_assign)
15772 << FixItHint::CreateReplacement(Loc, "=");
15776 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15777 bool IsConstexpr) {
15778 DiagnoseAssignmentAsCondition(E);
15779 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15780 DiagnoseEqualityWithExtraParens(parenE);
15782 ExprResult result = CheckPlaceholderExpr(E);
15783 if (result.isInvalid()) return ExprError();
15786 if (!E->isTypeDependent()) {
15787 if (getLangOpts().CPlusPlus)
15788 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15790 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15791 if (ERes.isInvalid())
15792 return ExprError();
15795 QualType T = E->getType();
15796 if (!T->isScalarType()) { // C99 6.8.4.1p1
15797 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15798 << T << E->getSourceRange();
15799 return ExprError();
15801 CheckBoolLikeConversion(E, Loc);
15807 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15808 Expr *SubExpr, ConditionKind CK) {
15809 // Empty conditions are valid in for-statements.
15811 return ConditionResult();
15815 case ConditionKind::Boolean:
15816 Cond = CheckBooleanCondition(Loc, SubExpr);
15819 case ConditionKind::ConstexprIf:
15820 Cond = CheckBooleanCondition(Loc, SubExpr, true);
15823 case ConditionKind::Switch:
15824 Cond = CheckSwitchCondition(Loc, SubExpr);
15827 if (Cond.isInvalid())
15828 return ConditionError();
15830 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15831 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15832 if (!FullExpr.get())
15833 return ConditionError();
15835 return ConditionResult(*this, nullptr, FullExpr,
15836 CK == ConditionKind::ConstexprIf);
15840 /// A visitor for rebuilding a call to an __unknown_any expression
15841 /// to have an appropriate type.
15842 struct RebuildUnknownAnyFunction
15843 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15847 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15849 ExprResult VisitStmt(Stmt *S) {
15850 llvm_unreachable("unexpected statement!");
15853 ExprResult VisitExpr(Expr *E) {
15854 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15855 << E->getSourceRange();
15856 return ExprError();
15859 /// Rebuild an expression which simply semantically wraps another
15860 /// expression which it shares the type and value kind of.
15861 template <class T> ExprResult rebuildSugarExpr(T *E) {
15862 ExprResult SubResult = Visit(E->getSubExpr());
15863 if (SubResult.isInvalid()) return ExprError();
15865 Expr *SubExpr = SubResult.get();
15866 E->setSubExpr(SubExpr);
15867 E->setType(SubExpr->getType());
15868 E->setValueKind(SubExpr->getValueKind());
15869 assert(E->getObjectKind() == OK_Ordinary);
15873 ExprResult VisitParenExpr(ParenExpr *E) {
15874 return rebuildSugarExpr(E);
15877 ExprResult VisitUnaryExtension(UnaryOperator *E) {
15878 return rebuildSugarExpr(E);
15881 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15882 ExprResult SubResult = Visit(E->getSubExpr());
15883 if (SubResult.isInvalid()) return ExprError();
15885 Expr *SubExpr = SubResult.get();
15886 E->setSubExpr(SubExpr);
15887 E->setType(S.Context.getPointerType(SubExpr->getType()));
15888 assert(E->getValueKind() == VK_RValue);
15889 assert(E->getObjectKind() == OK_Ordinary);
15893 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15894 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15896 E->setType(VD->getType());
15898 assert(E->getValueKind() == VK_RValue);
15899 if (S.getLangOpts().CPlusPlus &&
15900 !(isa<CXXMethodDecl>(VD) &&
15901 cast<CXXMethodDecl>(VD)->isInstance()))
15902 E->setValueKind(VK_LValue);
15907 ExprResult VisitMemberExpr(MemberExpr *E) {
15908 return resolveDecl(E, E->getMemberDecl());
15911 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15912 return resolveDecl(E, E->getDecl());
15917 /// Given a function expression of unknown-any type, try to rebuild it
15918 /// to have a function type.
15919 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15920 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15921 if (Result.isInvalid()) return ExprError();
15922 return S.DefaultFunctionArrayConversion(Result.get());
15926 /// A visitor for rebuilding an expression of type __unknown_anytype
15927 /// into one which resolves the type directly on the referring
15928 /// expression. Strict preservation of the original source
15929 /// structure is not a goal.
15930 struct RebuildUnknownAnyExpr
15931 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15935 /// The current destination type.
15938 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15939 : S(S), DestType(CastType) {}
15941 ExprResult VisitStmt(Stmt *S) {
15942 llvm_unreachable("unexpected statement!");
15945 ExprResult VisitExpr(Expr *E) {
15946 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15947 << E->getSourceRange();
15948 return ExprError();
15951 ExprResult VisitCallExpr(CallExpr *E);
15952 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15954 /// Rebuild an expression which simply semantically wraps another
15955 /// expression which it shares the type and value kind of.
15956 template <class T> ExprResult rebuildSugarExpr(T *E) {
15957 ExprResult SubResult = Visit(E->getSubExpr());
15958 if (SubResult.isInvalid()) return ExprError();
15959 Expr *SubExpr = SubResult.get();
15960 E->setSubExpr(SubExpr);
15961 E->setType(SubExpr->getType());
15962 E->setValueKind(SubExpr->getValueKind());
15963 assert(E->getObjectKind() == OK_Ordinary);
15967 ExprResult VisitParenExpr(ParenExpr *E) {
15968 return rebuildSugarExpr(E);
15971 ExprResult VisitUnaryExtension(UnaryOperator *E) {
15972 return rebuildSugarExpr(E);
15975 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15976 const PointerType *Ptr = DestType->getAs<PointerType>();
15978 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15979 << E->getSourceRange();
15980 return ExprError();
15983 if (isa<CallExpr>(E->getSubExpr())) {
15984 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15985 << E->getSourceRange();
15986 return ExprError();
15989 assert(E->getValueKind() == VK_RValue);
15990 assert(E->getObjectKind() == OK_Ordinary);
15991 E->setType(DestType);
15993 // Build the sub-expression as if it were an object of the pointee type.
15994 DestType = Ptr->getPointeeType();
15995 ExprResult SubResult = Visit(E->getSubExpr());
15996 if (SubResult.isInvalid()) return ExprError();
15997 E->setSubExpr(SubResult.get());
16001 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16003 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16005 ExprResult VisitMemberExpr(MemberExpr *E) {
16006 return resolveDecl(E, E->getMemberDecl());
16009 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16010 return resolveDecl(E, E->getDecl());
16015 /// Rebuilds a call expression which yielded __unknown_anytype.
16016 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16017 Expr *CalleeExpr = E->getCallee();
16021 FK_FunctionPointer,
16026 QualType CalleeType = CalleeExpr->getType();
16027 if (CalleeType == S.Context.BoundMemberTy) {
16028 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16029 Kind = FK_MemberFunction;
16030 CalleeType = Expr::findBoundMemberType(CalleeExpr);
16031 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16032 CalleeType = Ptr->getPointeeType();
16033 Kind = FK_FunctionPointer;
16035 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16036 Kind = FK_BlockPointer;
16038 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16040 // Verify that this is a legal result type of a function.
16041 if (DestType->isArrayType() || DestType->isFunctionType()) {
16042 unsigned diagID = diag::err_func_returning_array_function;
16043 if (Kind == FK_BlockPointer)
16044 diagID = diag::err_block_returning_array_function;
16046 S.Diag(E->getExprLoc(), diagID)
16047 << DestType->isFunctionType() << DestType;
16048 return ExprError();
16051 // Otherwise, go ahead and set DestType as the call's result.
16052 E->setType(DestType.getNonLValueExprType(S.Context));
16053 E->setValueKind(Expr::getValueKindForType(DestType));
16054 assert(E->getObjectKind() == OK_Ordinary);
16056 // Rebuild the function type, replacing the result type with DestType.
16057 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16059 // __unknown_anytype(...) is a special case used by the debugger when
16060 // it has no idea what a function's signature is.
16062 // We want to build this call essentially under the K&R
16063 // unprototyped rules, but making a FunctionNoProtoType in C++
16064 // would foul up all sorts of assumptions. However, we cannot
16065 // simply pass all arguments as variadic arguments, nor can we
16066 // portably just call the function under a non-variadic type; see
16067 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16068 // However, it turns out that in practice it is generally safe to
16069 // call a function declared as "A foo(B,C,D);" under the prototype
16070 // "A foo(B,C,D,...);". The only known exception is with the
16071 // Windows ABI, where any variadic function is implicitly cdecl
16072 // regardless of its normal CC. Therefore we change the parameter
16073 // types to match the types of the arguments.
16075 // This is a hack, but it is far superior to moving the
16076 // corresponding target-specific code from IR-gen to Sema/AST.
16078 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16079 SmallVector<QualType, 8> ArgTypes;
16080 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16081 ArgTypes.reserve(E->getNumArgs());
16082 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16083 Expr *Arg = E->getArg(i);
16084 QualType ArgType = Arg->getType();
16085 if (E->isLValue()) {
16086 ArgType = S.Context.getLValueReferenceType(ArgType);
16087 } else if (E->isXValue()) {
16088 ArgType = S.Context.getRValueReferenceType(ArgType);
16090 ArgTypes.push_back(ArgType);
16092 ParamTypes = ArgTypes;
16094 DestType = S.Context.getFunctionType(DestType, ParamTypes,
16095 Proto->getExtProtoInfo());
16097 DestType = S.Context.getFunctionNoProtoType(DestType,
16098 FnType->getExtInfo());
16101 // Rebuild the appropriate pointer-to-function type.
16103 case FK_MemberFunction:
16107 case FK_FunctionPointer:
16108 DestType = S.Context.getPointerType(DestType);
16111 case FK_BlockPointer:
16112 DestType = S.Context.getBlockPointerType(DestType);
16116 // Finally, we can recurse.
16117 ExprResult CalleeResult = Visit(CalleeExpr);
16118 if (!CalleeResult.isUsable()) return ExprError();
16119 E->setCallee(CalleeResult.get());
16121 // Bind a temporary if necessary.
16122 return S.MaybeBindToTemporary(E);
16125 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16126 // Verify that this is a legal result type of a call.
16127 if (DestType->isArrayType() || DestType->isFunctionType()) {
16128 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16129 << DestType->isFunctionType() << DestType;
16130 return ExprError();
16133 // Rewrite the method result type if available.
16134 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16135 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16136 Method->setReturnType(DestType);
16139 // Change the type of the message.
16140 E->setType(DestType.getNonReferenceType());
16141 E->setValueKind(Expr::getValueKindForType(DestType));
16143 return S.MaybeBindToTemporary(E);
16146 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16147 // The only case we should ever see here is a function-to-pointer decay.
16148 if (E->getCastKind() == CK_FunctionToPointerDecay) {
16149 assert(E->getValueKind() == VK_RValue);
16150 assert(E->getObjectKind() == OK_Ordinary);
16152 E->setType(DestType);
16154 // Rebuild the sub-expression as the pointee (function) type.
16155 DestType = DestType->castAs<PointerType>()->getPointeeType();
16157 ExprResult Result = Visit(E->getSubExpr());
16158 if (!Result.isUsable()) return ExprError();
16160 E->setSubExpr(Result.get());
16162 } else if (E->getCastKind() == CK_LValueToRValue) {
16163 assert(E->getValueKind() == VK_RValue);
16164 assert(E->getObjectKind() == OK_Ordinary);
16166 assert(isa<BlockPointerType>(E->getType()));
16168 E->setType(DestType);
16170 // The sub-expression has to be a lvalue reference, so rebuild it as such.
16171 DestType = S.Context.getLValueReferenceType(DestType);
16173 ExprResult Result = Visit(E->getSubExpr());
16174 if (!Result.isUsable()) return ExprError();
16176 E->setSubExpr(Result.get());
16179 llvm_unreachable("Unhandled cast type!");
16183 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16184 ExprValueKind ValueKind = VK_LValue;
16185 QualType Type = DestType;
16187 // We know how to make this work for certain kinds of decls:
16190 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16191 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16192 DestType = Ptr->getPointeeType();
16193 ExprResult Result = resolveDecl(E, VD);
16194 if (Result.isInvalid()) return ExprError();
16195 return S.ImpCastExprToType(Result.get(), Type,
16196 CK_FunctionToPointerDecay, VK_RValue);
16199 if (!Type->isFunctionType()) {
16200 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16201 << VD << E->getSourceRange();
16202 return ExprError();
16204 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16205 // We must match the FunctionDecl's type to the hack introduced in
16206 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16207 // type. See the lengthy commentary in that routine.
16208 QualType FDT = FD->getType();
16209 const FunctionType *FnType = FDT->castAs<FunctionType>();
16210 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16211 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16212 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16213 SourceLocation Loc = FD->getLocation();
16214 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16215 FD->getDeclContext(),
16216 Loc, Loc, FD->getNameInfo().getName(),
16217 DestType, FD->getTypeSourceInfo(),
16218 SC_None, false/*isInlineSpecified*/,
16219 FD->hasPrototype(),
16220 false/*isConstexprSpecified*/);
16222 if (FD->getQualifier())
16223 NewFD->setQualifierInfo(FD->getQualifierLoc());
16225 SmallVector<ParmVarDecl*, 16> Params;
16226 for (const auto &AI : FT->param_types()) {
16227 ParmVarDecl *Param =
16228 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16229 Param->setScopeInfo(0, Params.size());
16230 Params.push_back(Param);
16232 NewFD->setParams(Params);
16233 DRE->setDecl(NewFD);
16234 VD = DRE->getDecl();
16238 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16239 if (MD->isInstance()) {
16240 ValueKind = VK_RValue;
16241 Type = S.Context.BoundMemberTy;
16244 // Function references aren't l-values in C.
16245 if (!S.getLangOpts().CPlusPlus)
16246 ValueKind = VK_RValue;
16249 } else if (isa<VarDecl>(VD)) {
16250 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16251 Type = RefTy->getPointeeType();
16252 } else if (Type->isFunctionType()) {
16253 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16254 << VD << E->getSourceRange();
16255 return ExprError();
16260 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16261 << VD << E->getSourceRange();
16262 return ExprError();
16265 // Modifying the declaration like this is friendly to IR-gen but
16266 // also really dangerous.
16267 VD->setType(DestType);
16269 E->setValueKind(ValueKind);
16273 /// Check a cast of an unknown-any type. We intentionally only
16274 /// trigger this for C-style casts.
16275 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16276 Expr *CastExpr, CastKind &CastKind,
16277 ExprValueKind &VK, CXXCastPath &Path) {
16278 // The type we're casting to must be either void or complete.
16279 if (!CastType->isVoidType() &&
16280 RequireCompleteType(TypeRange.getBegin(), CastType,
16281 diag::err_typecheck_cast_to_incomplete))
16282 return ExprError();
16284 // Rewrite the casted expression from scratch.
16285 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16286 if (!result.isUsable()) return ExprError();
16288 CastExpr = result.get();
16289 VK = CastExpr->getValueKind();
16290 CastKind = CK_NoOp;
16295 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16296 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16299 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16300 Expr *arg, QualType ¶mType) {
16301 // If the syntactic form of the argument is not an explicit cast of
16302 // any sort, just do default argument promotion.
16303 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16305 ExprResult result = DefaultArgumentPromotion(arg);
16306 if (result.isInvalid()) return ExprError();
16307 paramType = result.get()->getType();
16311 // Otherwise, use the type that was written in the explicit cast.
16312 assert(!arg->hasPlaceholderType());
16313 paramType = castArg->getTypeAsWritten();
16315 // Copy-initialize a parameter of that type.
16316 InitializedEntity entity =
16317 InitializedEntity::InitializeParameter(Context, paramType,
16318 /*consumed*/ false);
16319 return PerformCopyInitialization(entity, callLoc, arg);
16322 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16324 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16326 E = E->IgnoreParenImpCasts();
16327 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16328 E = call->getCallee();
16329 diagID = diag::err_uncasted_call_of_unknown_any;
16335 SourceLocation loc;
16337 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16338 loc = ref->getLocation();
16339 d = ref->getDecl();
16340 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16341 loc = mem->getMemberLoc();
16342 d = mem->getMemberDecl();
16343 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16344 diagID = diag::err_uncasted_call_of_unknown_any;
16345 loc = msg->getSelectorStartLoc();
16346 d = msg->getMethodDecl();
16348 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16349 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16350 << orig->getSourceRange();
16351 return ExprError();
16354 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16355 << E->getSourceRange();
16356 return ExprError();
16359 S.Diag(loc, diagID) << d << orig->getSourceRange();
16361 // Never recoverable.
16362 return ExprError();
16365 /// Check for operands with placeholder types and complain if found.
16366 /// Returns ExprError() if there was an error and no recovery was possible.
16367 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16368 if (!getLangOpts().CPlusPlus) {
16369 // C cannot handle TypoExpr nodes on either side of a binop because it
16370 // doesn't handle dependent types properly, so make sure any TypoExprs have
16371 // been dealt with before checking the operands.
16372 ExprResult Result = CorrectDelayedTyposInExpr(E);
16373 if (!Result.isUsable()) return ExprError();
16377 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16378 if (!placeholderType) return E;
16380 switch (placeholderType->getKind()) {
16382 // Overloaded expressions.
16383 case BuiltinType::Overload: {
16384 // Try to resolve a single function template specialization.
16385 // This is obligatory.
16386 ExprResult Result = E;
16387 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16390 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16391 // leaves Result unchanged on failure.
16393 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16396 // If that failed, try to recover with a call.
16397 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16398 /*complain*/ true);
16402 // Bound member functions.
16403 case BuiltinType::BoundMember: {
16404 ExprResult result = E;
16405 const Expr *BME = E->IgnoreParens();
16406 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16407 // Try to give a nicer diagnostic if it is a bound member that we recognize.
16408 if (isa<CXXPseudoDestructorExpr>(BME)) {
16409 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16410 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16411 if (ME->getMemberNameInfo().getName().getNameKind() ==
16412 DeclarationName::CXXDestructorName)
16413 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16415 tryToRecoverWithCall(result, PD,
16416 /*complain*/ true);
16420 // ARC unbridged casts.
16421 case BuiltinType::ARCUnbridgedCast: {
16422 Expr *realCast = stripARCUnbridgedCast(E);
16423 diagnoseARCUnbridgedCast(realCast);
16427 // Expressions of unknown type.
16428 case BuiltinType::UnknownAny:
16429 return diagnoseUnknownAnyExpr(*this, E);
16432 case BuiltinType::PseudoObject:
16433 return checkPseudoObjectRValue(E);
16435 case BuiltinType::BuiltinFn: {
16436 // Accept __noop without parens by implicitly converting it to a call expr.
16437 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16439 auto *FD = cast<FunctionDecl>(DRE->getDecl());
16440 if (FD->getBuiltinID() == Builtin::BI__noop) {
16441 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16442 CK_BuiltinFnToFnPtr).get();
16443 return new (Context) CallExpr(Context, E, None, Context.IntTy,
16444 VK_RValue, SourceLocation());
16448 Diag(E->getLocStart(), diag::err_builtin_fn_use);
16449 return ExprError();
16452 // Expressions of unknown type.
16453 case BuiltinType::OMPArraySection:
16454 Diag(E->getLocStart(), diag::err_omp_array_section_use);
16455 return ExprError();
16457 // Everything else should be impossible.
16458 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16459 case BuiltinType::Id:
16460 #include "clang/Basic/OpenCLImageTypes.def"
16461 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16462 #define PLACEHOLDER_TYPE(Id, SingletonId)
16463 #include "clang/AST/BuiltinTypes.def"
16467 llvm_unreachable("invalid placeholder type!");
16470 bool Sema::CheckCaseExpression(Expr *E) {
16471 if (E->isTypeDependent())
16473 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16474 return E->getType()->isIntegralOrEnumerationType();
16478 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16480 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16481 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16482 "Unknown Objective-C Boolean value!");
16483 QualType BoolT = Context.ObjCBuiltinBoolTy;
16484 if (!Context.getBOOLDecl()) {
16485 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16486 Sema::LookupOrdinaryName);
16487 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16488 NamedDecl *ND = Result.getFoundDecl();
16489 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16490 Context.setBOOLDecl(TD);
16493 if (Context.getBOOLDecl())
16494 BoolT = Context.getBOOLType();
16495 return new (Context)
16496 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16499 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16500 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16501 SourceLocation RParen) {
16503 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16505 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16506 [&](const AvailabilitySpec &Spec) {
16507 return Spec.getPlatform() == Platform;
16510 VersionTuple Version;
16511 if (Spec != AvailSpecs.end())
16512 Version = Spec->getVersion();
16514 // The use of `@available` in the enclosing function should be analyzed to
16515 // warn when it's used inappropriately (i.e. not if(@available)).
16516 if (getCurFunctionOrMethodDecl())
16517 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16518 else if (getCurBlock() || getCurLambda())
16519 getCurFunction()->HasPotentialAvailabilityViolations = true;
16521 return new (Context)
16522 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);