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 "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 using namespace clang;
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
50 bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60 // If the function has a deduced return type, and we can't deduce it,
61 // then we can't use it either.
62 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
63 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67 // See if this function is unavailable.
68 if (D->getAvailability() == AR_Unavailable &&
69 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
76 // Warn if this is used but marked unused.
77 if (D->hasAttr<UnusedAttr>()) {
78 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
79 if (!DC->hasAttr<UnusedAttr>())
80 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
85 NamedDecl *D, SourceLocation Loc,
86 const ObjCInterfaceDecl *UnknownObjCClass,
87 bool ObjCPropertyAccess) {
88 // See if this declaration is unavailable or deprecated.
91 // Forward class declarations get their attributes from their definition.
92 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
93 if (IDecl->getDefinition())
94 D = IDecl->getDefinition();
96 AvailabilityResult Result = D->getAvailability(&Message);
97 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
98 if (Result == AR_Available) {
99 const DeclContext *DC = ECD->getDeclContext();
100 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
101 Result = TheEnumDecl->getAvailability(&Message);
104 const ObjCPropertyDecl *ObjCPDecl = nullptr;
105 if (Result == AR_Deprecated || Result == AR_Unavailable) {
106 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
107 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
108 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
109 if (PDeclResult == Result)
117 case AR_NotYetIntroduced:
121 if (S.getCurContextAvailability() != AR_Deprecated)
122 S.EmitAvailabilityWarning(Sema::AD_Deprecation,
123 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
128 if (S.getCurContextAvailability() != AR_Unavailable)
129 S.EmitAvailabilityWarning(Sema::AD_Unavailable,
130 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
138 /// \brief Emit a note explaining that this function is deleted.
139 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140 assert(Decl->isDeleted());
142 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
144 if (Method && Method->isDeleted() && Method->isDefaulted()) {
145 // If the method was explicitly defaulted, point at that declaration.
146 if (!Method->isImplicit())
147 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
149 // Try to diagnose why this special member function was implicitly
150 // deleted. This might fail, if that reason no longer applies.
151 CXXSpecialMember CSM = getSpecialMember(Method);
152 if (CSM != CXXInvalid)
153 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
158 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
159 if (CXXConstructorDecl *BaseCD =
160 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
161 Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
162 if (BaseCD->isDeleted()) {
163 NoteDeletedFunction(BaseCD);
165 // FIXME: An explanation of why exactly it can't be inherited
167 Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
173 Diag(Decl->getLocation(), diag::note_availability_specified_here)
177 /// \brief Determine whether a FunctionDecl was ever declared with an
178 /// explicit storage class.
179 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
180 for (auto I : D->redecls()) {
181 if (I->getStorageClass() != SC_None)
187 /// \brief Check whether we're in an extern inline function and referring to a
188 /// variable or function with internal linkage (C11 6.7.4p3).
190 /// This is only a warning because we used to silently accept this code, but
191 /// in many cases it will not behave correctly. This is not enabled in C++ mode
192 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
193 /// and so while there may still be user mistakes, most of the time we can't
194 /// prove that there are errors.
195 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
197 SourceLocation Loc) {
198 // This is disabled under C++; there are too many ways for this to fire in
199 // contexts where the warning is a false positive, or where it is technically
200 // correct but benign.
201 if (S.getLangOpts().CPlusPlus)
204 // Check if this is an inlined function or method.
205 FunctionDecl *Current = S.getCurFunctionDecl();
208 if (!Current->isInlined())
210 if (!Current->isExternallyVisible())
213 // Check if the decl has internal linkage.
214 if (D->getFormalLinkage() != InternalLinkage)
217 // Downgrade from ExtWarn to Extension if
218 // (1) the supposedly external inline function is in the main file,
219 // and probably won't be included anywhere else.
220 // (2) the thing we're referencing is a pure function.
221 // (3) the thing we're referencing is another inline function.
222 // This last can give us false negatives, but it's better than warning on
223 // wrappers for simple C library functions.
224 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
225 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
226 if (!DowngradeWarning && UsedFn)
227 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
229 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
230 : diag::ext_internal_in_extern_inline)
231 << /*IsVar=*/!UsedFn << D;
233 S.MaybeSuggestAddingStaticToDecl(Current);
235 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
239 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
240 const FunctionDecl *First = Cur->getFirstDecl();
242 // Suggest "static" on the function, if possible.
243 if (!hasAnyExplicitStorageClass(First)) {
244 SourceLocation DeclBegin = First->getSourceRange().getBegin();
245 Diag(DeclBegin, diag::note_convert_inline_to_static)
246 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
250 /// \brief Determine whether the use of this declaration is valid, and
251 /// emit any corresponding diagnostics.
253 /// This routine diagnoses various problems with referencing
254 /// declarations that can occur when using a declaration. For example,
255 /// it might warn if a deprecated or unavailable declaration is being
256 /// used, or produce an error (and return true) if a C++0x deleted
257 /// function is being used.
259 /// \returns true if there was an error (this declaration cannot be
260 /// referenced), false otherwise.
262 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
263 const ObjCInterfaceDecl *UnknownObjCClass,
264 bool ObjCPropertyAccess) {
265 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
266 // If there were any diagnostics suppressed by template argument deduction,
268 SuppressedDiagnosticsMap::iterator
269 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
270 if (Pos != SuppressedDiagnostics.end()) {
271 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
272 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
273 Diag(Suppressed[I].first, Suppressed[I].second);
275 // Clear out the list of suppressed diagnostics, so that we don't emit
276 // them again for this specialization. However, we don't obsolete this
277 // entry from the table, because we want to avoid ever emitting these
278 // diagnostics again.
282 // C++ [basic.start.main]p3:
283 // The function 'main' shall not be used within a program.
284 if (cast<FunctionDecl>(D)->isMain())
285 Diag(Loc, diag::ext_main_used);
288 // See if this is an auto-typed variable whose initializer we are parsing.
289 if (ParsingInitForAutoVars.count(D)) {
290 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
295 // See if this is a deleted function.
296 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
297 if (FD->isDeleted()) {
298 Diag(Loc, diag::err_deleted_function_use);
299 NoteDeletedFunction(FD);
303 // If the function has a deduced return type, and we can't deduce it,
304 // then we can't use it either.
305 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
306 DeduceReturnType(FD, Loc))
309 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess);
311 DiagnoseUnusedOfDecl(*this, D, Loc);
313 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
318 /// \brief Retrieve the message suffix that should be added to a
319 /// diagnostic complaining about the given function being deleted or
321 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
323 if (FD->getAvailability(&Message))
324 return ": " + Message;
326 return std::string();
329 /// DiagnoseSentinelCalls - This routine checks whether a call or
330 /// message-send is to a declaration with the sentinel attribute, and
331 /// if so, it checks that the requirements of the sentinel are
333 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
334 ArrayRef<Expr *> Args) {
335 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
339 // The number of formal parameters of the declaration.
340 unsigned numFormalParams;
342 // The kind of declaration. This is also an index into a %select in
344 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
346 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
347 numFormalParams = MD->param_size();
348 calleeType = CT_Method;
349 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
350 numFormalParams = FD->param_size();
351 calleeType = CT_Function;
352 } else if (isa<VarDecl>(D)) {
353 QualType type = cast<ValueDecl>(D)->getType();
354 const FunctionType *fn = nullptr;
355 if (const PointerType *ptr = type->getAs<PointerType>()) {
356 fn = ptr->getPointeeType()->getAs<FunctionType>();
358 calleeType = CT_Function;
359 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
360 fn = ptr->getPointeeType()->castAs<FunctionType>();
361 calleeType = CT_Block;
366 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
367 numFormalParams = proto->getNumParams();
375 // "nullPos" is the number of formal parameters at the end which
376 // effectively count as part of the variadic arguments. This is
377 // useful if you would prefer to not have *any* formal parameters,
378 // but the language forces you to have at least one.
379 unsigned nullPos = attr->getNullPos();
380 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
381 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
383 // The number of arguments which should follow the sentinel.
384 unsigned numArgsAfterSentinel = attr->getSentinel();
386 // If there aren't enough arguments for all the formal parameters,
387 // the sentinel, and the args after the sentinel, complain.
388 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
389 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
390 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
394 // Otherwise, find the sentinel expression.
395 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
396 if (!sentinelExpr) return;
397 if (sentinelExpr->isValueDependent()) return;
398 if (Context.isSentinelNullExpr(sentinelExpr)) return;
400 // Pick a reasonable string to insert. Optimistically use 'nil' or
401 // 'NULL' if those are actually defined in the context. Only use
402 // 'nil' for ObjC methods, where it's much more likely that the
403 // variadic arguments form a list of object pointers.
404 SourceLocation MissingNilLoc
405 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
406 std::string NullValue;
407 if (calleeType == CT_Method &&
408 PP.getIdentifierInfo("nil")->hasMacroDefinition())
410 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
413 NullValue = "(void*) 0";
415 if (MissingNilLoc.isInvalid())
416 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
418 Diag(MissingNilLoc, diag::warn_missing_sentinel)
420 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
421 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
424 SourceRange Sema::getExprRange(Expr *E) const {
425 return E ? E->getSourceRange() : SourceRange();
428 //===----------------------------------------------------------------------===//
429 // Standard Promotions and Conversions
430 //===----------------------------------------------------------------------===//
432 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
433 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
434 // Handle any placeholder expressions which made it here.
435 if (E->getType()->isPlaceholderType()) {
436 ExprResult result = CheckPlaceholderExpr(E);
437 if (result.isInvalid()) return ExprError();
441 QualType Ty = E->getType();
442 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
444 if (Ty->isFunctionType()) {
445 // If we are here, we are not calling a function but taking
446 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
447 if (getLangOpts().OpenCL) {
448 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
451 E = ImpCastExprToType(E, Context.getPointerType(Ty),
452 CK_FunctionToPointerDecay).get();
453 } else if (Ty->isArrayType()) {
454 // In C90 mode, arrays only promote to pointers if the array expression is
455 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
456 // type 'array of type' is converted to an expression that has type 'pointer
457 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
458 // that has type 'array of type' ...". The relevant change is "an lvalue"
459 // (C90) to "an expression" (C99).
462 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
463 // T" can be converted to an rvalue of type "pointer to T".
465 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
466 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
467 CK_ArrayToPointerDecay).get();
472 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
473 // Check to see if we are dereferencing a null pointer. If so,
474 // and if not volatile-qualified, this is undefined behavior that the
475 // optimizer will delete, so warn about it. People sometimes try to use this
476 // to get a deterministic trap and are surprised by clang's behavior. This
477 // only handles the pattern "*null", which is a very syntactic check.
478 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
479 if (UO->getOpcode() == UO_Deref &&
480 UO->getSubExpr()->IgnoreParenCasts()->
481 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
482 !UO->getType().isVolatileQualified()) {
483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
484 S.PDiag(diag::warn_indirection_through_null)
485 << UO->getSubExpr()->getSourceRange());
486 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
487 S.PDiag(diag::note_indirection_through_null));
491 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
492 SourceLocation AssignLoc,
494 const ObjCIvarDecl *IV = OIRE->getDecl();
498 DeclarationName MemberName = IV->getDeclName();
499 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
500 if (!Member || !Member->isStr("isa"))
503 const Expr *Base = OIRE->getBase();
504 QualType BaseType = Base->getType();
506 BaseType = BaseType->getPointeeType();
507 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
508 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
509 ObjCInterfaceDecl *ClassDeclared = nullptr;
510 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
511 if (!ClassDeclared->getSuperClass()
512 && (*ClassDeclared->ivar_begin()) == IV) {
514 NamedDecl *ObjectSetClass =
515 S.LookupSingleName(S.TUScope,
516 &S.Context.Idents.get("object_setClass"),
517 SourceLocation(), S.LookupOrdinaryName);
518 if (ObjectSetClass) {
519 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
520 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
521 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
522 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
524 FixItHint::CreateInsertion(RHSLocEnd, ")");
527 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
529 NamedDecl *ObjectGetClass =
530 S.LookupSingleName(S.TUScope,
531 &S.Context.Idents.get("object_getClass"),
532 SourceLocation(), S.LookupOrdinaryName);
534 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
535 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
536 FixItHint::CreateReplacement(
537 SourceRange(OIRE->getOpLoc(),
538 OIRE->getLocEnd()), ")");
540 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
542 S.Diag(IV->getLocation(), diag::note_ivar_decl);
547 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
548 // Handle any placeholder expressions which made it here.
549 if (E->getType()->isPlaceholderType()) {
550 ExprResult result = CheckPlaceholderExpr(E);
551 if (result.isInvalid()) return ExprError();
555 // C++ [conv.lval]p1:
556 // A glvalue of a non-function, non-array type T can be
557 // converted to a prvalue.
558 if (!E->isGLValue()) return E;
560 QualType T = E->getType();
561 assert(!T.isNull() && "r-value conversion on typeless expression?");
563 // We don't want to throw lvalue-to-rvalue casts on top of
564 // expressions of certain types in C++.
565 if (getLangOpts().CPlusPlus &&
566 (E->getType() == Context.OverloadTy ||
567 T->isDependentType() ||
571 // The C standard is actually really unclear on this point, and
572 // DR106 tells us what the result should be but not why. It's
573 // generally best to say that void types just doesn't undergo
574 // lvalue-to-rvalue at all. Note that expressions of unqualified
575 // 'void' type are never l-values, but qualified void can be.
579 // OpenCL usually rejects direct accesses to values of 'half' type.
580 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
582 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
587 CheckForNullPointerDereference(*this, E);
588 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
589 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
590 &Context.Idents.get("object_getClass"),
591 SourceLocation(), LookupOrdinaryName);
593 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
594 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
595 FixItHint::CreateReplacement(
596 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
598 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
600 else if (const ObjCIvarRefExpr *OIRE =
601 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
602 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
604 // C++ [conv.lval]p1:
605 // [...] If T is a non-class type, the type of the prvalue is the
606 // cv-unqualified version of T. Otherwise, the type of the
610 // If the lvalue has qualified type, the value has the unqualified
611 // version of the type of the lvalue; otherwise, the value has the
612 // type of the lvalue.
613 if (T.hasQualifiers())
614 T = T.getUnqualifiedType();
616 UpdateMarkingForLValueToRValue(E);
618 // Loading a __weak object implicitly retains the value, so we need a cleanup to
620 if (getLangOpts().ObjCAutoRefCount &&
621 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
622 ExprNeedsCleanups = true;
624 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
628 // ... if the lvalue has atomic type, the value has the non-atomic version
629 // of the type of the lvalue ...
630 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
631 T = Atomic->getValueType().getUnqualifiedType();
632 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
639 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
640 ExprResult Res = DefaultFunctionArrayConversion(E);
643 Res = DefaultLvalueConversion(Res.get());
649 /// CallExprUnaryConversions - a special case of an unary conversion
650 /// performed on a function designator of a call expression.
651 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
652 QualType Ty = E->getType();
654 // Only do implicit cast for a function type, but not for a pointer
656 if (Ty->isFunctionType()) {
657 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
658 CK_FunctionToPointerDecay).get();
662 Res = DefaultLvalueConversion(Res.get());
668 /// UsualUnaryConversions - Performs various conversions that are common to most
669 /// operators (C99 6.3). The conversions of array and function types are
670 /// sometimes suppressed. For example, the array->pointer conversion doesn't
671 /// apply if the array is an argument to the sizeof or address (&) operators.
672 /// In these instances, this routine should *not* be called.
673 ExprResult Sema::UsualUnaryConversions(Expr *E) {
674 // First, convert to an r-value.
675 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
680 QualType Ty = E->getType();
681 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
683 // Half FP have to be promoted to float unless it is natively supported
684 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
685 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
687 // Try to perform integral promotions if the object has a theoretically
689 if (Ty->isIntegralOrUnscopedEnumerationType()) {
692 // The following may be used in an expression wherever an int or
693 // unsigned int may be used:
694 // - an object or expression with an integer type whose integer
695 // conversion rank is less than or equal to the rank of int
697 // - A bit-field of type _Bool, int, signed int, or unsigned int.
699 // If an int can represent all values of the original type, the
700 // value is converted to an int; otherwise, it is converted to an
701 // unsigned int. These are called the integer promotions. All
702 // other types are unchanged by the integer promotions.
704 QualType PTy = Context.isPromotableBitField(E);
706 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
709 if (Ty->isPromotableIntegerType()) {
710 QualType PT = Context.getPromotedIntegerType(Ty);
711 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
718 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
719 /// do not have a prototype. Arguments that have type float or __fp16
720 /// are promoted to double. All other argument types are converted by
721 /// UsualUnaryConversions().
722 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
723 QualType Ty = E->getType();
724 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
726 ExprResult Res = UsualUnaryConversions(E);
731 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
733 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
734 if (BTy && (BTy->getKind() == BuiltinType::Half ||
735 BTy->getKind() == BuiltinType::Float))
736 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
738 // C++ performs lvalue-to-rvalue conversion as a default argument
739 // promotion, even on class types, but note:
740 // C++11 [conv.lval]p2:
741 // When an lvalue-to-rvalue conversion occurs in an unevaluated
742 // operand or a subexpression thereof the value contained in the
743 // referenced object is not accessed. Otherwise, if the glvalue
744 // has a class type, the conversion copy-initializes a temporary
745 // of type T from the glvalue and the result of the conversion
746 // is a prvalue for the temporary.
747 // FIXME: add some way to gate this entire thing for correctness in
748 // potentially potentially evaluated contexts.
749 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
750 ExprResult Temp = PerformCopyInitialization(
751 InitializedEntity::InitializeTemporary(E->getType()),
753 if (Temp.isInvalid())
761 /// Determine the degree of POD-ness for an expression.
762 /// Incomplete types are considered POD, since this check can be performed
763 /// when we're in an unevaluated context.
764 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
765 if (Ty->isIncompleteType()) {
766 // C++11 [expr.call]p7:
767 // After these conversions, if the argument does not have arithmetic,
768 // enumeration, pointer, pointer to member, or class type, the program
771 // Since we've already performed array-to-pointer and function-to-pointer
772 // decay, the only such type in C++ is cv void. This also handles
773 // initializer lists as variadic arguments.
774 if (Ty->isVoidType())
777 if (Ty->isObjCObjectType())
782 if (Ty.isCXX98PODType(Context))
785 // C++11 [expr.call]p7:
786 // Passing a potentially-evaluated argument of class type (Clause 9)
787 // having a non-trivial copy constructor, a non-trivial move constructor,
788 // or a non-trivial destructor, with no corresponding parameter,
789 // is conditionally-supported with implementation-defined semantics.
790 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
791 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
792 if (!Record->hasNonTrivialCopyConstructor() &&
793 !Record->hasNonTrivialMoveConstructor() &&
794 !Record->hasNonTrivialDestructor())
795 return VAK_ValidInCXX11;
797 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
800 if (Ty->isObjCObjectType())
803 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
804 // permitted to reject them. We should consider doing so.
805 return VAK_Undefined;
808 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
809 // Don't allow one to pass an Objective-C interface to a vararg.
810 const QualType &Ty = E->getType();
811 VarArgKind VAK = isValidVarArgType(Ty);
813 // Complain about passing non-POD types through varargs.
815 case VAK_ValidInCXX11:
817 E->getLocStart(), nullptr,
818 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
822 if (Ty->isRecordType()) {
823 // This is unlikely to be what the user intended. If the class has a
824 // 'c_str' member function, the user probably meant to call that.
825 DiagRuntimeBehavior(E->getLocStart(), nullptr,
826 PDiag(diag::warn_pass_class_arg_to_vararg)
827 << Ty << CT << hasCStrMethod(E) << ".c_str()");
833 E->getLocStart(), nullptr,
834 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
835 << getLangOpts().CPlusPlus11 << Ty << CT);
839 if (Ty->isObjCObjectType())
841 E->getLocStart(), nullptr,
842 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
845 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
846 << isa<InitListExpr>(E) << Ty << CT;
851 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
852 /// will create a trap if the resulting type is not a POD type.
853 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
854 FunctionDecl *FDecl) {
855 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
856 // Strip the unbridged-cast placeholder expression off, if applicable.
857 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
858 (CT == VariadicMethod ||
859 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
860 E = stripARCUnbridgedCast(E);
862 // Otherwise, do normal placeholder checking.
864 ExprResult ExprRes = CheckPlaceholderExpr(E);
865 if (ExprRes.isInvalid())
871 ExprResult ExprRes = DefaultArgumentPromotion(E);
872 if (ExprRes.isInvalid())
876 // Diagnostics regarding non-POD argument types are
877 // emitted along with format string checking in Sema::CheckFunctionCall().
878 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
879 // Turn this into a trap.
881 SourceLocation TemplateKWLoc;
883 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
885 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
887 if (TrapFn.isInvalid())
890 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
891 E->getLocStart(), None,
893 if (Call.isInvalid())
896 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
898 if (Comma.isInvalid())
903 if (!getLangOpts().CPlusPlus &&
904 RequireCompleteType(E->getExprLoc(), E->getType(),
905 diag::err_call_incomplete_argument))
911 /// \brief Converts an integer to complex float type. Helper function of
912 /// UsualArithmeticConversions()
914 /// \return false if the integer expression is an integer type and is
915 /// successfully converted to the complex type.
916 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
917 ExprResult &ComplexExpr,
921 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
922 if (SkipCast) return false;
923 if (IntTy->isIntegerType()) {
924 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
925 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
926 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
927 CK_FloatingRealToComplex);
929 assert(IntTy->isComplexIntegerType());
930 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
931 CK_IntegralComplexToFloatingComplex);
936 /// \brief Takes two complex float types and converts them to the same type.
937 /// Helper function of UsualArithmeticConversions()
939 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
940 ExprResult &RHS, QualType LHSType,
943 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
946 // _Complex float -> _Complex double
948 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingComplexCast);
952 // _Complex float -> _Complex double
953 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingComplexCast);
957 /// \brief Converts otherExpr to complex float and promotes complexExpr if
958 /// necessary. Helper function of UsualArithmeticConversions()
959 static QualType handleOtherComplexFloatConversion(Sema &S,
960 ExprResult &ComplexExpr,
961 ExprResult &OtherExpr,
964 bool ConvertComplexExpr,
965 bool ConvertOtherExpr) {
966 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
968 // If just the complexExpr is complex, the otherExpr needs to be converted,
969 // and the complexExpr might need to be promoted.
970 if (order > 0) { // complexExpr is wider
971 // float -> _Complex double
972 if (ConvertOtherExpr) {
973 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
974 OtherExpr = S.ImpCastExprToType(OtherExpr.get(), fp, CK_FloatingCast);
975 OtherExpr = S.ImpCastExprToType(OtherExpr.get(), ComplexTy,
976 CK_FloatingRealToComplex);
981 // otherTy is at least as wide. Find its corresponding complex type.
982 QualType result = (order == 0 ? ComplexTy :
983 S.Context.getComplexType(OtherTy));
985 // double -> _Complex double
986 if (ConvertOtherExpr)
987 OtherExpr = S.ImpCastExprToType(OtherExpr.get(), result,
988 CK_FloatingRealToComplex);
990 // _Complex float -> _Complex double
991 if (ConvertComplexExpr && order < 0)
992 ComplexExpr = S.ImpCastExprToType(ComplexExpr.get(), result,
993 CK_FloatingComplexCast);
998 /// \brief Handle arithmetic conversion with complex types. Helper function of
999 /// UsualArithmeticConversions()
1000 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1001 ExprResult &RHS, QualType LHSType,
1003 bool IsCompAssign) {
1004 // if we have an integer operand, the result is the complex type.
1005 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1008 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1009 /*skipCast*/IsCompAssign))
1012 // This handles complex/complex, complex/float, or float/complex.
1013 // When both operands are complex, the shorter operand is converted to the
1014 // type of the longer, and that is the type of the result. This corresponds
1015 // to what is done when combining two real floating-point operands.
1016 // The fun begins when size promotion occur across type domains.
1017 // From H&S 6.3.4: When one operand is complex and the other is a real
1018 // floating-point type, the less precise type is converted, within it's
1019 // real or complex domain, to the precision of the other type. For example,
1020 // when combining a "long double" with a "double _Complex", the
1021 // "double _Complex" is promoted to "long double _Complex".
1023 bool LHSComplexFloat = LHSType->isComplexType();
1024 bool RHSComplexFloat = RHSType->isComplexType();
1026 // If both are complex, just cast to the more precise type.
1027 if (LHSComplexFloat && RHSComplexFloat)
1028 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1032 // If only one operand is complex, promote it if necessary and convert the
1033 // other operand to complex.
1034 if (LHSComplexFloat)
1035 return handleOtherComplexFloatConversion(
1036 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1037 /*convertOtherExpr*/ true);
1039 assert(RHSComplexFloat);
1040 return handleOtherComplexFloatConversion(
1041 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1042 /*convertOtherExpr*/ !IsCompAssign);
1045 /// \brief Hande arithmetic conversion from integer to float. Helper function
1046 /// of UsualArithmeticConversions()
1047 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1048 ExprResult &IntExpr,
1049 QualType FloatTy, QualType IntTy,
1050 bool ConvertFloat, bool ConvertInt) {
1051 if (IntTy->isIntegerType()) {
1053 // Convert intExpr to the lhs floating point type.
1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1055 CK_IntegralToFloating);
1059 // Convert both sides to the appropriate complex float.
1060 assert(IntTy->isComplexIntegerType());
1061 QualType result = S.Context.getComplexType(FloatTy);
1063 // _Complex int -> _Complex float
1065 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1066 CK_IntegralComplexToFloatingComplex);
1068 // float -> _Complex float
1070 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1071 CK_FloatingRealToComplex);
1076 /// \brief Handle arithmethic conversion with floating point types. Helper
1077 /// function of UsualArithmeticConversions()
1078 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1079 ExprResult &RHS, QualType LHSType,
1080 QualType RHSType, bool IsCompAssign) {
1081 bool LHSFloat = LHSType->isRealFloatingType();
1082 bool RHSFloat = RHSType->isRealFloatingType();
1084 // If we have two real floating types, convert the smaller operand
1085 // to the bigger result.
1086 if (LHSFloat && RHSFloat) {
1087 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1089 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1093 assert(order < 0 && "illegal float comparison");
1095 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1100 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1101 /*convertFloat=*/!IsCompAssign,
1102 /*convertInt=*/ true);
1104 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1105 /*convertInt=*/ true,
1106 /*convertFloat=*/!IsCompAssign);
1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1112 /// These helper callbacks are placed in an anonymous namespace to
1113 /// permit their use as function template parameters.
1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1115 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1119 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1120 CK_IntegralComplexCast);
1124 /// \brief Handle integer arithmetic conversions. Helper function of
1125 /// UsualArithmeticConversions()
1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1128 ExprResult &RHS, QualType LHSType,
1129 QualType RHSType, bool IsCompAssign) {
1130 // The rules for this case are in C99 6.3.1.8
1131 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1132 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1133 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1134 if (LHSSigned == RHSSigned) {
1135 // Same signedness; use the higher-ranked type
1137 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1139 } else if (!IsCompAssign)
1140 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1142 } else if (order != (LHSSigned ? 1 : -1)) {
1143 // The unsigned type has greater than or equal rank to the
1144 // signed type, so use the unsigned type
1146 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1148 } else if (!IsCompAssign)
1149 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1151 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1152 // The two types are different widths; if we are here, that
1153 // means the signed type is larger than the unsigned type, so
1154 // use the signed type.
1156 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1158 } else if (!IsCompAssign)
1159 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162 // The signed type is higher-ranked than the unsigned type,
1163 // but isn't actually any bigger (like unsigned int and long
1164 // on most 32-bit systems). Use the unsigned type corresponding
1165 // to the signed type.
1167 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1168 RHS = (*doRHSCast)(S, RHS.get(), result);
1170 LHS = (*doLHSCast)(S, LHS.get(), result);
1175 /// \brief Handle conversions with GCC complex int extension. Helper function
1176 /// of UsualArithmeticConversions()
1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1178 ExprResult &RHS, QualType LHSType,
1180 bool IsCompAssign) {
1181 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1182 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1184 if (LHSComplexInt && RHSComplexInt) {
1185 QualType LHSEltType = LHSComplexInt->getElementType();
1186 QualType RHSEltType = RHSComplexInt->getElementType();
1187 QualType ScalarType =
1188 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1189 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1191 return S.Context.getComplexType(ScalarType);
1194 if (LHSComplexInt) {
1195 QualType LHSEltType = LHSComplexInt->getElementType();
1196 QualType ScalarType =
1197 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1198 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1199 QualType ComplexType = S.Context.getComplexType(ScalarType);
1200 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1201 CK_IntegralRealToComplex);
1206 assert(RHSComplexInt);
1208 QualType RHSEltType = RHSComplexInt->getElementType();
1209 QualType ScalarType =
1210 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1211 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1212 QualType ComplexType = S.Context.getComplexType(ScalarType);
1215 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1216 CK_IntegralRealToComplex);
1220 /// UsualArithmeticConversions - Performs various conversions that are common to
1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1222 /// routine returns the first non-arithmetic type found. The client is
1223 /// responsible for emitting appropriate error diagnostics.
1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1225 bool IsCompAssign) {
1226 if (!IsCompAssign) {
1227 LHS = UsualUnaryConversions(LHS.get());
1228 if (LHS.isInvalid())
1232 RHS = UsualUnaryConversions(RHS.get());
1233 if (RHS.isInvalid())
1236 // For conversion purposes, we ignore any qualifiers.
1237 // For example, "const float" and "float" are equivalent.
1239 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1241 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1243 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1244 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1245 LHSType = AtomicLHS->getValueType();
1247 // If both types are identical, no conversion is needed.
1248 if (LHSType == RHSType)
1251 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1252 // The caller can deal with this (e.g. pointer + int).
1253 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1256 // Apply unary and bitfield promotions to the LHS's type.
1257 QualType LHSUnpromotedType = LHSType;
1258 if (LHSType->isPromotableIntegerType())
1259 LHSType = Context.getPromotedIntegerType(LHSType);
1260 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1261 if (!LHSBitfieldPromoteTy.isNull())
1262 LHSType = LHSBitfieldPromoteTy;
1263 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1264 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1266 // If both types are identical, no conversion is needed.
1267 if (LHSType == RHSType)
1270 // At this point, we have two different arithmetic types.
1272 // Handle complex types first (C99 6.3.1.8p1).
1273 if (LHSType->isComplexType() || RHSType->isComplexType())
1274 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1277 // Now handle "real" floating types (i.e. float, double, long double).
1278 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1279 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1282 // Handle GCC complex int extension.
1283 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1284 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1287 // Finally, we have two differing integer types.
1288 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1289 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1293 //===----------------------------------------------------------------------===//
1294 // Semantic Analysis for various Expression Types
1295 //===----------------------------------------------------------------------===//
1299 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1300 SourceLocation DefaultLoc,
1301 SourceLocation RParenLoc,
1302 Expr *ControllingExpr,
1303 ArrayRef<ParsedType> ArgTypes,
1304 ArrayRef<Expr *> ArgExprs) {
1305 unsigned NumAssocs = ArgTypes.size();
1306 assert(NumAssocs == ArgExprs.size());
1308 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1309 for (unsigned i = 0; i < NumAssocs; ++i) {
1311 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1316 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1318 llvm::makeArrayRef(Types, NumAssocs),
1325 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1326 SourceLocation DefaultLoc,
1327 SourceLocation RParenLoc,
1328 Expr *ControllingExpr,
1329 ArrayRef<TypeSourceInfo *> Types,
1330 ArrayRef<Expr *> Exprs) {
1331 unsigned NumAssocs = Types.size();
1332 assert(NumAssocs == Exprs.size());
1333 if (ControllingExpr->getType()->isPlaceholderType()) {
1334 ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1335 if (result.isInvalid()) return ExprError();
1336 ControllingExpr = result.get();
1339 bool TypeErrorFound = false,
1340 IsResultDependent = ControllingExpr->isTypeDependent(),
1341 ContainsUnexpandedParameterPack
1342 = ControllingExpr->containsUnexpandedParameterPack();
1344 for (unsigned i = 0; i < NumAssocs; ++i) {
1345 if (Exprs[i]->containsUnexpandedParameterPack())
1346 ContainsUnexpandedParameterPack = true;
1349 if (Types[i]->getType()->containsUnexpandedParameterPack())
1350 ContainsUnexpandedParameterPack = true;
1352 if (Types[i]->getType()->isDependentType()) {
1353 IsResultDependent = true;
1355 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1356 // complete object type other than a variably modified type."
1358 if (Types[i]->getType()->isIncompleteType())
1359 D = diag::err_assoc_type_incomplete;
1360 else if (!Types[i]->getType()->isObjectType())
1361 D = diag::err_assoc_type_nonobject;
1362 else if (Types[i]->getType()->isVariablyModifiedType())
1363 D = diag::err_assoc_type_variably_modified;
1366 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1367 << Types[i]->getTypeLoc().getSourceRange()
1368 << Types[i]->getType();
1369 TypeErrorFound = true;
1372 // C11 6.5.1.1p2 "No two generic associations in the same generic
1373 // selection shall specify compatible types."
1374 for (unsigned j = i+1; j < NumAssocs; ++j)
1375 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1376 Context.typesAreCompatible(Types[i]->getType(),
1377 Types[j]->getType())) {
1378 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1379 diag::err_assoc_compatible_types)
1380 << Types[j]->getTypeLoc().getSourceRange()
1381 << Types[j]->getType()
1382 << Types[i]->getType();
1383 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1384 diag::note_compat_assoc)
1385 << Types[i]->getTypeLoc().getSourceRange()
1386 << Types[i]->getType();
1387 TypeErrorFound = true;
1395 // If we determined that the generic selection is result-dependent, don't
1396 // try to compute the result expression.
1397 if (IsResultDependent)
1398 return new (Context) GenericSelectionExpr(
1399 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1400 ContainsUnexpandedParameterPack);
1402 SmallVector<unsigned, 1> CompatIndices;
1403 unsigned DefaultIndex = -1U;
1404 for (unsigned i = 0; i < NumAssocs; ++i) {
1407 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1408 Types[i]->getType()))
1409 CompatIndices.push_back(i);
1412 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1413 // type compatible with at most one of the types named in its generic
1414 // association list."
1415 if (CompatIndices.size() > 1) {
1416 // We strip parens here because the controlling expression is typically
1417 // parenthesized in macro definitions.
1418 ControllingExpr = ControllingExpr->IgnoreParens();
1419 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1420 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1421 << (unsigned) CompatIndices.size();
1422 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1423 E = CompatIndices.end(); I != E; ++I) {
1424 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1425 diag::note_compat_assoc)
1426 << Types[*I]->getTypeLoc().getSourceRange()
1427 << Types[*I]->getType();
1432 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1433 // its controlling expression shall have type compatible with exactly one of
1434 // the types named in its generic association list."
1435 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
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_no_match)
1440 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1444 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1445 // type name that is compatible with the type of the controlling expression,
1446 // then the result expression of the generic selection is the expression
1447 // in that generic association. Otherwise, the result expression of the
1448 // generic selection is the expression in the default generic association."
1449 unsigned ResultIndex =
1450 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1452 return new (Context) GenericSelectionExpr(
1453 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1454 ContainsUnexpandedParameterPack, ResultIndex);
1457 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1458 /// location of the token and the offset of the ud-suffix within it.
1459 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1461 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1465 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1466 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1467 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1468 IdentifierInfo *UDSuffix,
1469 SourceLocation UDSuffixLoc,
1470 ArrayRef<Expr*> Args,
1471 SourceLocation LitEndLoc) {
1472 assert(Args.size() <= 2 && "too many arguments for literal operator");
1475 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1476 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1477 if (ArgTy[ArgIdx]->isArrayType())
1478 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1481 DeclarationName OpName =
1482 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1483 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1484 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1486 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1487 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1488 /*AllowRaw*/false, /*AllowTemplate*/false,
1489 /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1492 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1495 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1496 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1497 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1498 /// multiple tokens. However, the common case is that StringToks points to one
1502 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1503 assert(!StringToks.empty() && "Must have at least one string!");
1505 StringLiteralParser Literal(StringToks, PP);
1506 if (Literal.hadError)
1509 SmallVector<SourceLocation, 4> StringTokLocs;
1510 for (unsigned i = 0; i != StringToks.size(); ++i)
1511 StringTokLocs.push_back(StringToks[i].getLocation());
1513 QualType CharTy = Context.CharTy;
1514 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1515 if (Literal.isWide()) {
1516 CharTy = Context.getWideCharType();
1517 Kind = StringLiteral::Wide;
1518 } else if (Literal.isUTF8()) {
1519 Kind = StringLiteral::UTF8;
1520 } else if (Literal.isUTF16()) {
1521 CharTy = Context.Char16Ty;
1522 Kind = StringLiteral::UTF16;
1523 } else if (Literal.isUTF32()) {
1524 CharTy = Context.Char32Ty;
1525 Kind = StringLiteral::UTF32;
1526 } else if (Literal.isPascal()) {
1527 CharTy = Context.UnsignedCharTy;
1530 QualType CharTyConst = CharTy;
1531 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1532 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1533 CharTyConst.addConst();
1535 // Get an array type for the string, according to C99 6.4.5. This includes
1536 // the nul terminator character as well as the string length for pascal
1538 QualType StrTy = Context.getConstantArrayType(CharTyConst,
1539 llvm::APInt(32, Literal.GetNumStringChars()+1),
1540 ArrayType::Normal, 0);
1542 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1543 if (getLangOpts().OpenCL) {
1544 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1547 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1548 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1549 Kind, Literal.Pascal, StrTy,
1551 StringTokLocs.size());
1552 if (Literal.getUDSuffix().empty())
1555 // We're building a user-defined literal.
1556 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1557 SourceLocation UDSuffixLoc =
1558 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1559 Literal.getUDSuffixOffset());
1561 // Make sure we're allowed user-defined literals here.
1563 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1565 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1566 // operator "" X (str, len)
1567 QualType SizeType = Context.getSizeType();
1569 DeclarationName OpName =
1570 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1571 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1572 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1574 QualType ArgTy[] = {
1575 Context.getArrayDecayedType(StrTy), SizeType
1578 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1579 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1580 /*AllowRaw*/false, /*AllowTemplate*/false,
1581 /*AllowStringTemplate*/true)) {
1584 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1585 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1587 Expr *Args[] = { Lit, LenArg };
1589 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1592 case LOLR_StringTemplate: {
1593 TemplateArgumentListInfo ExplicitArgs;
1595 unsigned CharBits = Context.getIntWidth(CharTy);
1596 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1597 llvm::APSInt Value(CharBits, CharIsUnsigned);
1599 TemplateArgument TypeArg(CharTy);
1600 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1601 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1603 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1604 Value = Lit->getCodeUnit(I);
1605 TemplateArgument Arg(Context, Value, CharTy);
1606 TemplateArgumentLocInfo ArgInfo;
1607 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1609 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1614 llvm_unreachable("unexpected literal operator lookup result");
1618 llvm_unreachable("unexpected literal operator lookup result");
1622 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1624 const CXXScopeSpec *SS) {
1625 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1626 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1629 /// BuildDeclRefExpr - Build an expression that references a
1630 /// declaration that does not require a closure capture.
1632 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1633 const DeclarationNameInfo &NameInfo,
1634 const CXXScopeSpec *SS, NamedDecl *FoundD,
1635 const TemplateArgumentListInfo *TemplateArgs) {
1636 if (getLangOpts().CUDA)
1637 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1638 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1639 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1640 CalleeTarget = IdentifyCUDATarget(Callee);
1641 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1642 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1643 << CalleeTarget << D->getIdentifier() << CallerTarget;
1644 Diag(D->getLocation(), diag::note_previous_decl)
1645 << D->getIdentifier();
1650 bool refersToEnclosingScope =
1651 (CurContext != D->getDeclContext() &&
1652 D->getDeclContext()->isFunctionOrMethod()) ||
1654 cast<VarDecl>(D)->isInitCapture());
1657 if (isa<VarTemplateSpecializationDecl>(D)) {
1658 VarTemplateSpecializationDecl *VarSpec =
1659 cast<VarTemplateSpecializationDecl>(D);
1661 E = DeclRefExpr::Create(
1663 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1664 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1665 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1667 assert(!TemplateArgs && "No template arguments for non-variable"
1668 " template specialization references");
1669 E = DeclRefExpr::Create(
1671 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1672 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1675 MarkDeclRefReferenced(E);
1677 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1678 Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1679 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1680 recordUseOfEvaluatedWeak(E);
1682 // Just in case we're building an illegal pointer-to-member.
1683 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1684 if (FD && FD->isBitField())
1685 E->setObjectKind(OK_BitField);
1690 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1691 /// possibly a list of template arguments.
1693 /// If this produces template arguments, it is permitted to call
1694 /// DecomposeTemplateName.
1696 /// This actually loses a lot of source location information for
1697 /// non-standard name kinds; we should consider preserving that in
1700 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1701 TemplateArgumentListInfo &Buffer,
1702 DeclarationNameInfo &NameInfo,
1703 const TemplateArgumentListInfo *&TemplateArgs) {
1704 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1705 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1706 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1708 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1709 Id.TemplateId->NumArgs);
1710 translateTemplateArguments(TemplateArgsPtr, Buffer);
1712 TemplateName TName = Id.TemplateId->Template.get();
1713 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1714 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1715 TemplateArgs = &Buffer;
1717 NameInfo = GetNameFromUnqualifiedId(Id);
1718 TemplateArgs = nullptr;
1722 /// Diagnose an empty lookup.
1724 /// \return false if new lookup candidates were found
1725 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1726 CorrectionCandidateCallback &CCC,
1727 TemplateArgumentListInfo *ExplicitTemplateArgs,
1728 ArrayRef<Expr *> Args) {
1729 DeclarationName Name = R.getLookupName();
1731 unsigned diagnostic = diag::err_undeclared_var_use;
1732 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1733 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1734 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1735 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1736 diagnostic = diag::err_undeclared_use;
1737 diagnostic_suggest = diag::err_undeclared_use_suggest;
1740 // If the original lookup was an unqualified lookup, fake an
1741 // unqualified lookup. This is useful when (for example) the
1742 // original lookup would not have found something because it was a
1744 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1745 ? CurContext : nullptr;
1747 if (isa<CXXRecordDecl>(DC)) {
1748 LookupQualifiedName(R, DC);
1751 // Don't give errors about ambiguities in this lookup.
1752 R.suppressDiagnostics();
1754 // During a default argument instantiation the CurContext points
1755 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1756 // function parameter list, hence add an explicit check.
1757 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1758 ActiveTemplateInstantiations.back().Kind ==
1759 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1760 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1761 bool isInstance = CurMethod &&
1762 CurMethod->isInstance() &&
1763 DC == CurMethod->getParent() && !isDefaultArgument;
1766 // Give a code modification hint to insert 'this->'.
1767 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1768 // Actually quite difficult!
1769 if (getLangOpts().MSVCCompat)
1770 diagnostic = diag::ext_found_via_dependent_bases_lookup;
1772 Diag(R.getNameLoc(), diagnostic) << Name
1773 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1774 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1775 CallsUndergoingInstantiation.back()->getCallee());
1777 CXXMethodDecl *DepMethod;
1778 if (CurMethod->isDependentContext())
1779 DepMethod = CurMethod;
1780 else if (CurMethod->getTemplatedKind() ==
1781 FunctionDecl::TK_FunctionTemplateSpecialization)
1782 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1783 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1785 DepMethod = cast<CXXMethodDecl>(
1786 CurMethod->getInstantiatedFromMemberFunction());
1787 assert(DepMethod && "No template pattern found");
1789 QualType DepThisType = DepMethod->getThisType(Context);
1790 CheckCXXThisCapture(R.getNameLoc());
1791 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1792 R.getNameLoc(), DepThisType, false);
1793 TemplateArgumentListInfo TList;
1794 if (ULE->hasExplicitTemplateArgs())
1795 ULE->copyTemplateArgumentsInto(TList);
1798 SS.Adopt(ULE->getQualifierLoc());
1799 CXXDependentScopeMemberExpr *DepExpr =
1800 CXXDependentScopeMemberExpr::Create(
1801 Context, DepThis, DepThisType, true, SourceLocation(),
1802 SS.getWithLocInContext(Context),
1803 ULE->getTemplateKeywordLoc(), nullptr,
1804 R.getLookupNameInfo(),
1805 ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1806 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1808 Diag(R.getNameLoc(), diagnostic) << Name;
1811 // Do we really want to note all of these?
1812 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1813 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1815 // Return true if we are inside a default argument instantiation
1816 // and the found name refers to an instance member function, otherwise
1817 // the function calling DiagnoseEmptyLookup will try to create an
1818 // implicit member call and this is wrong for default argument.
1819 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1820 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1824 // Tell the callee to try to recover.
1831 // In Microsoft mode, if we are performing lookup from within a friend
1832 // function definition declared at class scope then we must set
1833 // DC to the lexical parent to be able to search into the parent
1835 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1836 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1837 DC->getLexicalParent()->isRecord())
1838 DC = DC->getLexicalParent();
1840 DC = DC->getParent();
1843 // We didn't find anything, so try to correct for a typo.
1844 TypoCorrection Corrected;
1845 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1846 S, &SS, CCC, CTK_ErrorRecovery))) {
1847 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1848 bool DroppedSpecifier =
1849 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1850 R.setLookupName(Corrected.getCorrection());
1852 bool AcceptableWithRecovery = false;
1853 bool AcceptableWithoutRecovery = false;
1854 NamedDecl *ND = Corrected.getCorrectionDecl();
1856 if (Corrected.isOverloaded()) {
1857 OverloadCandidateSet OCS(R.getNameLoc(),
1858 OverloadCandidateSet::CSK_Normal);
1859 OverloadCandidateSet::iterator Best;
1860 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1861 CDEnd = Corrected.end();
1862 CD != CDEnd; ++CD) {
1863 if (FunctionTemplateDecl *FTD =
1864 dyn_cast<FunctionTemplateDecl>(*CD))
1865 AddTemplateOverloadCandidate(
1866 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1868 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1869 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1870 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1873 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1875 ND = Best->Function;
1876 Corrected.setCorrectionDecl(ND);
1879 // FIXME: Arbitrarily pick the first declaration for the note.
1880 Corrected.setCorrectionDecl(ND);
1885 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1886 CXXRecordDecl *Record = nullptr;
1887 if (Corrected.getCorrectionSpecifier()) {
1888 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1889 Record = Ty->getAsCXXRecordDecl();
1892 Record = cast<CXXRecordDecl>(
1893 ND->getDeclContext()->getRedeclContext());
1894 R.setNamingClass(Record);
1897 AcceptableWithRecovery =
1898 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1899 // FIXME: If we ended up with a typo for a type name or
1900 // Objective-C class name, we're in trouble because the parser
1901 // is in the wrong place to recover. Suggest the typo
1902 // correction, but don't make it a fix-it since we're not going
1903 // to recover well anyway.
1904 AcceptableWithoutRecovery =
1905 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1907 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1908 // because we aren't able to recover.
1909 AcceptableWithoutRecovery = true;
1912 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1913 unsigned NoteID = (Corrected.getCorrectionDecl() &&
1914 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1915 ? diag::note_implicit_param_decl
1916 : diag::note_previous_decl;
1918 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1919 PDiag(NoteID), AcceptableWithRecovery);
1921 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1922 << Name << computeDeclContext(SS, false)
1923 << DroppedSpecifier << SS.getRange(),
1924 PDiag(NoteID), AcceptableWithRecovery);
1926 // Tell the callee whether to try to recover.
1927 return !AcceptableWithRecovery;
1932 // Emit a special diagnostic for failed member lookups.
1933 // FIXME: computing the declaration context might fail here (?)
1934 if (!SS.isEmpty()) {
1935 Diag(R.getNameLoc(), diag::err_no_member)
1936 << Name << computeDeclContext(SS, false)
1941 // Give up, we can't recover.
1942 Diag(R.getNameLoc(), diagnostic) << Name;
1946 /// In Microsoft mode, if we are inside a template class whose parent class has
1947 /// dependent base classes, and we can't resolve an unqualified identifier, then
1948 /// assume the identifier is a member of a dependent base class. We can only
1949 /// recover successfully in static methods, instance methods, and other contexts
1950 /// where 'this' is available. This doesn't precisely match MSVC's
1951 /// instantiation model, but it's close enough.
1953 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1954 DeclarationNameInfo &NameInfo,
1955 SourceLocation TemplateKWLoc,
1956 const TemplateArgumentListInfo *TemplateArgs) {
1957 // Only try to recover from lookup into dependent bases in static methods or
1958 // contexts where 'this' is available.
1959 QualType ThisType = S.getCurrentThisType();
1960 const CXXRecordDecl *RD = nullptr;
1961 if (!ThisType.isNull())
1962 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1963 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1964 RD = MD->getParent();
1965 if (!RD || !RD->hasAnyDependentBases())
1968 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
1969 // is available, suggest inserting 'this->' as a fixit.
1970 SourceLocation Loc = NameInfo.getLoc();
1971 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1972 DB << NameInfo.getName() << RD;
1974 if (!ThisType.isNull()) {
1975 DB << FixItHint::CreateInsertion(Loc, "this->");
1976 return CXXDependentScopeMemberExpr::Create(
1977 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
1978 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
1979 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
1982 // Synthesize a fake NNS that points to the derived class. This will
1983 // perform name lookup during template instantiation.
1986 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
1987 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
1988 return DependentScopeDeclRefExpr::Create(
1989 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
1993 ExprResult Sema::ActOnIdExpression(Scope *S,
1995 SourceLocation TemplateKWLoc,
1997 bool HasTrailingLParen,
1998 bool IsAddressOfOperand,
1999 CorrectionCandidateCallback *CCC,
2000 bool IsInlineAsmIdentifier) {
2001 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2002 "cannot be direct & operand and have a trailing lparen");
2006 TemplateArgumentListInfo TemplateArgsBuffer;
2008 // Decompose the UnqualifiedId into the following data.
2009 DeclarationNameInfo NameInfo;
2010 const TemplateArgumentListInfo *TemplateArgs;
2011 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2013 DeclarationName Name = NameInfo.getName();
2014 IdentifierInfo *II = Name.getAsIdentifierInfo();
2015 SourceLocation NameLoc = NameInfo.getLoc();
2017 // C++ [temp.dep.expr]p3:
2018 // An id-expression is type-dependent if it contains:
2019 // -- an identifier that was declared with a dependent type,
2020 // (note: handled after lookup)
2021 // -- a template-id that is dependent,
2022 // (note: handled in BuildTemplateIdExpr)
2023 // -- a conversion-function-id that specifies a dependent type,
2024 // -- a nested-name-specifier that contains a class-name that
2025 // names a dependent type.
2026 // Determine whether this is a member of an unknown specialization;
2027 // we need to handle these differently.
2028 bool DependentID = false;
2029 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2030 Name.getCXXNameType()->isDependentType()) {
2032 } else if (SS.isSet()) {
2033 if (DeclContext *DC = computeDeclContext(SS, false)) {
2034 if (RequireCompleteDeclContext(SS, DC))
2042 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2043 IsAddressOfOperand, TemplateArgs);
2045 // Perform the required lookup.
2046 LookupResult R(*this, NameInfo,
2047 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2048 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2050 // Lookup the template name again to correctly establish the context in
2051 // which it was found. This is really unfortunate as we already did the
2052 // lookup to determine that it was a template name in the first place. If
2053 // this becomes a performance hit, we can work harder to preserve those
2054 // results until we get here but it's likely not worth it.
2055 bool MemberOfUnknownSpecialization;
2056 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2057 MemberOfUnknownSpecialization);
2059 if (MemberOfUnknownSpecialization ||
2060 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2061 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2062 IsAddressOfOperand, TemplateArgs);
2064 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2065 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2067 // If the result might be in a dependent base class, this is a dependent
2069 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2070 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2071 IsAddressOfOperand, TemplateArgs);
2073 // If this reference is in an Objective-C method, then we need to do
2074 // some special Objective-C lookup, too.
2075 if (IvarLookupFollowUp) {
2076 ExprResult E(LookupInObjCMethod(R, S, II, true));
2080 if (Expr *Ex = E.getAs<Expr>())
2085 if (R.isAmbiguous())
2088 // This could be an implicitly declared function reference (legal in C90,
2089 // extension in C99, forbidden in C++).
2090 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2091 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2092 if (D) R.addDecl(D);
2095 // Determine whether this name might be a candidate for
2096 // argument-dependent lookup.
2097 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2099 if (R.empty() && !ADL) {
2100 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2101 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2102 TemplateKWLoc, TemplateArgs))
2106 // Don't diagnose an empty lookup for inline assembly.
2107 if (IsInlineAsmIdentifier)
2110 // If this name wasn't predeclared and if this is not a function
2111 // call, diagnose the problem.
2112 CorrectionCandidateCallback DefaultValidator;
2113 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2114 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2115 "Typo correction callback misconfigured");
2116 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2119 assert(!R.empty() &&
2120 "DiagnoseEmptyLookup returned false but added no results");
2122 // If we found an Objective-C instance variable, let
2123 // LookupInObjCMethod build the appropriate expression to
2124 // reference the ivar.
2125 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2127 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2128 // In a hopelessly buggy code, Objective-C instance variable
2129 // lookup fails and no expression will be built to reference it.
2130 if (!E.isInvalid() && !E.get())
2136 // This is guaranteed from this point on.
2137 assert(!R.empty() || ADL);
2139 // Check whether this might be a C++ implicit instance member access.
2140 // C++ [class.mfct.non-static]p3:
2141 // When an id-expression that is not part of a class member access
2142 // syntax and not used to form a pointer to member is used in the
2143 // body of a non-static member function of class X, if name lookup
2144 // resolves the name in the id-expression to a non-static non-type
2145 // member of some class C, the id-expression is transformed into a
2146 // class member access expression using (*this) as the
2147 // postfix-expression to the left of the . operator.
2149 // But we don't actually need to do this for '&' operands if R
2150 // resolved to a function or overloaded function set, because the
2151 // expression is ill-formed if it actually works out to be a
2152 // non-static member function:
2154 // C++ [expr.ref]p4:
2155 // Otherwise, if E1.E2 refers to a non-static member function. . .
2156 // [t]he expression can be used only as the left-hand operand of a
2157 // member function call.
2159 // There are other safeguards against such uses, but it's important
2160 // to get this right here so that we don't end up making a
2161 // spuriously dependent expression if we're inside a dependent
2163 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2164 bool MightBeImplicitMember;
2165 if (!IsAddressOfOperand)
2166 MightBeImplicitMember = true;
2167 else if (!SS.isEmpty())
2168 MightBeImplicitMember = false;
2169 else if (R.isOverloadedResult())
2170 MightBeImplicitMember = false;
2171 else if (R.isUnresolvableResult())
2172 MightBeImplicitMember = true;
2174 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2175 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2176 isa<MSPropertyDecl>(R.getFoundDecl());
2178 if (MightBeImplicitMember)
2179 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2183 if (TemplateArgs || TemplateKWLoc.isValid()) {
2185 // In C++1y, if this is a variable template id, then check it
2186 // in BuildTemplateIdExpr().
2187 // The single lookup result must be a variable template declaration.
2188 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2189 Id.TemplateId->Kind == TNK_Var_template) {
2190 assert(R.getAsSingle<VarTemplateDecl>() &&
2191 "There should only be one declaration found.");
2194 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2197 return BuildDeclarationNameExpr(SS, R, ADL);
2200 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2201 /// declaration name, generally during template instantiation.
2202 /// There's a large number of things which don't need to be done along
2205 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2206 const DeclarationNameInfo &NameInfo,
2207 bool IsAddressOfOperand,
2208 TypeSourceInfo **RecoveryTSI) {
2209 DeclContext *DC = computeDeclContext(SS, false);
2211 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2212 NameInfo, /*TemplateArgs=*/nullptr);
2214 if (RequireCompleteDeclContext(SS, DC))
2217 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2218 LookupQualifiedName(R, DC);
2220 if (R.isAmbiguous())
2223 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2224 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2225 NameInfo, /*TemplateArgs=*/nullptr);
2228 Diag(NameInfo.getLoc(), diag::err_no_member)
2229 << NameInfo.getName() << DC << SS.getRange();
2233 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2234 // Diagnose a missing typename if this resolved unambiguously to a type in
2235 // a dependent context. If we can recover with a type, downgrade this to
2236 // a warning in Microsoft compatibility mode.
2237 unsigned DiagID = diag::err_typename_missing;
2238 if (RecoveryTSI && getLangOpts().MSVCCompat)
2239 DiagID = diag::ext_typename_missing;
2240 SourceLocation Loc = SS.getBeginLoc();
2241 auto D = Diag(Loc, DiagID);
2242 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2243 << SourceRange(Loc, NameInfo.getEndLoc());
2245 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2250 // Only issue the fixit if we're prepared to recover.
2251 D << FixItHint::CreateInsertion(Loc, "typename ");
2253 // Recover by pretending this was an elaborated type.
2254 QualType Ty = Context.getTypeDeclType(TD);
2256 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2258 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2259 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2260 QTL.setElaboratedKeywordLoc(SourceLocation());
2261 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2263 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2268 // Defend against this resolving to an implicit member access. We usually
2269 // won't get here if this might be a legitimate a class member (we end up in
2270 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2271 // a pointer-to-member or in an unevaluated context in C++11.
2272 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2273 return BuildPossibleImplicitMemberExpr(SS,
2274 /*TemplateKWLoc=*/SourceLocation(),
2275 R, /*TemplateArgs=*/nullptr);
2277 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2280 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2281 /// detected that we're currently inside an ObjC method. Perform some
2282 /// additional lookup.
2284 /// Ideally, most of this would be done by lookup, but there's
2285 /// actually quite a lot of extra work involved.
2287 /// Returns a null sentinel to indicate trivial success.
2289 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2290 IdentifierInfo *II, bool AllowBuiltinCreation) {
2291 SourceLocation Loc = Lookup.getNameLoc();
2292 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2294 // Check for error condition which is already reported.
2298 // There are two cases to handle here. 1) scoped lookup could have failed,
2299 // in which case we should look for an ivar. 2) scoped lookup could have
2300 // found a decl, but that decl is outside the current instance method (i.e.
2301 // a global variable). In these two cases, we do a lookup for an ivar with
2302 // this name, if the lookup sucedes, we replace it our current decl.
2304 // If we're in a class method, we don't normally want to look for
2305 // ivars. But if we don't find anything else, and there's an
2306 // ivar, that's an error.
2307 bool IsClassMethod = CurMethod->isClassMethod();
2311 LookForIvars = true;
2312 else if (IsClassMethod)
2313 LookForIvars = false;
2315 LookForIvars = (Lookup.isSingleResult() &&
2316 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2317 ObjCInterfaceDecl *IFace = nullptr;
2319 IFace = CurMethod->getClassInterface();
2320 ObjCInterfaceDecl *ClassDeclared;
2321 ObjCIvarDecl *IV = nullptr;
2322 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2323 // Diagnose using an ivar in a class method.
2325 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2326 << IV->getDeclName());
2328 // If we're referencing an invalid decl, just return this as a silent
2329 // error node. The error diagnostic was already emitted on the decl.
2330 if (IV->isInvalidDecl())
2333 // Check if referencing a field with __attribute__((deprecated)).
2334 if (DiagnoseUseOfDecl(IV, Loc))
2337 // Diagnose the use of an ivar outside of the declaring class.
2338 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2339 !declaresSameEntity(ClassDeclared, IFace) &&
2340 !getLangOpts().DebuggerSupport)
2341 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2343 // FIXME: This should use a new expr for a direct reference, don't
2344 // turn this into Self->ivar, just return a BareIVarExpr or something.
2345 IdentifierInfo &II = Context.Idents.get("self");
2346 UnqualifiedId SelfName;
2347 SelfName.setIdentifier(&II, SourceLocation());
2348 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2349 CXXScopeSpec SelfScopeSpec;
2350 SourceLocation TemplateKWLoc;
2351 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2352 SelfName, false, false);
2353 if (SelfExpr.isInvalid())
2356 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2357 if (SelfExpr.isInvalid())
2360 MarkAnyDeclReferenced(Loc, IV, true);
2362 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2363 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2364 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2365 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2367 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2368 Loc, IV->getLocation(),
2372 if (getLangOpts().ObjCAutoRefCount) {
2373 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2374 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2375 recordUseOfEvaluatedWeak(Result);
2377 if (CurContext->isClosure())
2378 Diag(Loc, diag::warn_implicitly_retains_self)
2379 << FixItHint::CreateInsertion(Loc, "self->");
2384 } else if (CurMethod->isInstanceMethod()) {
2385 // We should warn if a local variable hides an ivar.
2386 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2387 ObjCInterfaceDecl *ClassDeclared;
2388 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2389 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2390 declaresSameEntity(IFace, ClassDeclared))
2391 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2394 } else if (Lookup.isSingleResult() &&
2395 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2396 // If accessing a stand-alone ivar in a class method, this is an error.
2397 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2398 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2399 << IV->getDeclName());
2402 if (Lookup.empty() && II && AllowBuiltinCreation) {
2403 // FIXME. Consolidate this with similar code in LookupName.
2404 if (unsigned BuiltinID = II->getBuiltinID()) {
2405 if (!(getLangOpts().CPlusPlus &&
2406 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2407 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2408 S, Lookup.isForRedeclaration(),
2409 Lookup.getNameLoc());
2410 if (D) Lookup.addDecl(D);
2414 // Sentinel value saying that we didn't do anything special.
2415 return ExprResult((Expr *)nullptr);
2418 /// \brief Cast a base object to a member's actual type.
2420 /// Logically this happens in three phases:
2422 /// * First we cast from the base type to the naming class.
2423 /// The naming class is the class into which we were looking
2424 /// when we found the member; it's the qualifier type if a
2425 /// qualifier was provided, and otherwise it's the base type.
2427 /// * Next we cast from the naming class to the declaring class.
2428 /// If the member we found was brought into a class's scope by
2429 /// a using declaration, this is that class; otherwise it's
2430 /// the class declaring the member.
2432 /// * Finally we cast from the declaring class to the "true"
2433 /// declaring class of the member. This conversion does not
2434 /// obey access control.
2436 Sema::PerformObjectMemberConversion(Expr *From,
2437 NestedNameSpecifier *Qualifier,
2438 NamedDecl *FoundDecl,
2439 NamedDecl *Member) {
2440 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2444 QualType DestRecordType;
2446 QualType FromRecordType;
2447 QualType FromType = From->getType();
2448 bool PointerConversions = false;
2449 if (isa<FieldDecl>(Member)) {
2450 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2452 if (FromType->getAs<PointerType>()) {
2453 DestType = Context.getPointerType(DestRecordType);
2454 FromRecordType = FromType->getPointeeType();
2455 PointerConversions = true;
2457 DestType = DestRecordType;
2458 FromRecordType = FromType;
2460 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2461 if (Method->isStatic())
2464 DestType = Method->getThisType(Context);
2465 DestRecordType = DestType->getPointeeType();
2467 if (FromType->getAs<PointerType>()) {
2468 FromRecordType = FromType->getPointeeType();
2469 PointerConversions = true;
2471 FromRecordType = FromType;
2472 DestType = DestRecordType;
2475 // No conversion necessary.
2479 if (DestType->isDependentType() || FromType->isDependentType())
2482 // If the unqualified types are the same, no conversion is necessary.
2483 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2486 SourceRange FromRange = From->getSourceRange();
2487 SourceLocation FromLoc = FromRange.getBegin();
2489 ExprValueKind VK = From->getValueKind();
2491 // C++ [class.member.lookup]p8:
2492 // [...] Ambiguities can often be resolved by qualifying a name with its
2495 // If the member was a qualified name and the qualified referred to a
2496 // specific base subobject type, we'll cast to that intermediate type
2497 // first and then to the object in which the member is declared. That allows
2498 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2500 // class Base { public: int x; };
2501 // class Derived1 : public Base { };
2502 // class Derived2 : public Base { };
2503 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2505 // void VeryDerived::f() {
2506 // x = 17; // error: ambiguous base subobjects
2507 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2509 if (Qualifier && Qualifier->getAsType()) {
2510 QualType QType = QualType(Qualifier->getAsType(), 0);
2511 assert(QType->isRecordType() && "lookup done with non-record type");
2513 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2515 // In C++98, the qualifier type doesn't actually have to be a base
2516 // type of the object type, in which case we just ignore it.
2517 // Otherwise build the appropriate casts.
2518 if (IsDerivedFrom(FromRecordType, QRecordType)) {
2519 CXXCastPath BasePath;
2520 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2521 FromLoc, FromRange, &BasePath))
2524 if (PointerConversions)
2525 QType = Context.getPointerType(QType);
2526 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2527 VK, &BasePath).get();
2530 FromRecordType = QRecordType;
2532 // If the qualifier type was the same as the destination type,
2534 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2539 bool IgnoreAccess = false;
2541 // If we actually found the member through a using declaration, cast
2542 // down to the using declaration's type.
2544 // Pointer equality is fine here because only one declaration of a
2545 // class ever has member declarations.
2546 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2547 assert(isa<UsingShadowDecl>(FoundDecl));
2548 QualType URecordType = Context.getTypeDeclType(
2549 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2551 // We only need to do this if the naming-class to declaring-class
2552 // conversion is non-trivial.
2553 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2554 assert(IsDerivedFrom(FromRecordType, URecordType));
2555 CXXCastPath BasePath;
2556 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2557 FromLoc, FromRange, &BasePath))
2560 QualType UType = URecordType;
2561 if (PointerConversions)
2562 UType = Context.getPointerType(UType);
2563 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2564 VK, &BasePath).get();
2566 FromRecordType = URecordType;
2569 // We don't do access control for the conversion from the
2570 // declaring class to the true declaring class.
2571 IgnoreAccess = true;
2574 CXXCastPath BasePath;
2575 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2576 FromLoc, FromRange, &BasePath,
2580 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2584 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2585 const LookupResult &R,
2586 bool HasTrailingLParen) {
2587 // Only when used directly as the postfix-expression of a call.
2588 if (!HasTrailingLParen)
2591 // Never if a scope specifier was provided.
2595 // Only in C++ or ObjC++.
2596 if (!getLangOpts().CPlusPlus)
2599 // Turn off ADL when we find certain kinds of declarations during
2601 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2604 // C++0x [basic.lookup.argdep]p3:
2605 // -- a declaration of a class member
2606 // Since using decls preserve this property, we check this on the
2608 if (D->isCXXClassMember())
2611 // C++0x [basic.lookup.argdep]p3:
2612 // -- a block-scope function declaration that is not a
2613 // using-declaration
2614 // NOTE: we also trigger this for function templates (in fact, we
2615 // don't check the decl type at all, since all other decl types
2616 // turn off ADL anyway).
2617 if (isa<UsingShadowDecl>(D))
2618 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2619 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2622 // C++0x [basic.lookup.argdep]p3:
2623 // -- a declaration that is neither a function or a function
2625 // And also for builtin functions.
2626 if (isa<FunctionDecl>(D)) {
2627 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2629 // But also builtin functions.
2630 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2632 } else if (!isa<FunctionTemplateDecl>(D))
2640 /// Diagnoses obvious problems with the use of the given declaration
2641 /// as an expression. This is only actually called for lookups that
2642 /// were not overloaded, and it doesn't promise that the declaration
2643 /// will in fact be used.
2644 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2645 if (isa<TypedefNameDecl>(D)) {
2646 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2650 if (isa<ObjCInterfaceDecl>(D)) {
2651 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2655 if (isa<NamespaceDecl>(D)) {
2656 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2664 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2667 // If this is a single, fully-resolved result and we don't need ADL,
2668 // just build an ordinary singleton decl ref.
2669 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2670 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2671 R.getRepresentativeDecl());
2673 // We only need to check the declaration if there's exactly one
2674 // result, because in the overloaded case the results can only be
2675 // functions and function templates.
2676 if (R.isSingleResult() &&
2677 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2680 // Otherwise, just build an unresolved lookup expression. Suppress
2681 // any lookup-related diagnostics; we'll hash these out later, when
2682 // we've picked a target.
2683 R.suppressDiagnostics();
2685 UnresolvedLookupExpr *ULE
2686 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2687 SS.getWithLocInContext(Context),
2688 R.getLookupNameInfo(),
2689 NeedsADL, R.isOverloadedResult(),
2690 R.begin(), R.end());
2695 /// \brief Complete semantic analysis for a reference to the given declaration.
2696 ExprResult Sema::BuildDeclarationNameExpr(
2697 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2698 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2699 assert(D && "Cannot refer to a NULL declaration");
2700 assert(!isa<FunctionTemplateDecl>(D) &&
2701 "Cannot refer unambiguously to a function template");
2703 SourceLocation Loc = NameInfo.getLoc();
2704 if (CheckDeclInExpr(*this, Loc, D))
2707 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2708 // Specifically diagnose references to class templates that are missing
2709 // a template argument list.
2710 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2711 << Template << SS.getRange();
2712 Diag(Template->getLocation(), diag::note_template_decl_here);
2716 // Make sure that we're referring to a value.
2717 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2719 Diag(Loc, diag::err_ref_non_value)
2720 << D << SS.getRange();
2721 Diag(D->getLocation(), diag::note_declared_at);
2725 // Check whether this declaration can be used. Note that we suppress
2726 // this check when we're going to perform argument-dependent lookup
2727 // on this function name, because this might not be the function
2728 // that overload resolution actually selects.
2729 if (DiagnoseUseOfDecl(VD, Loc))
2732 // Only create DeclRefExpr's for valid Decl's.
2733 if (VD->isInvalidDecl())
2736 // Handle members of anonymous structs and unions. If we got here,
2737 // and the reference is to a class member indirect field, then this
2738 // must be the subject of a pointer-to-member expression.
2739 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2740 if (!indirectField->isCXXClassMember())
2741 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2745 QualType type = VD->getType();
2746 ExprValueKind valueKind = VK_RValue;
2748 switch (D->getKind()) {
2749 // Ignore all the non-ValueDecl kinds.
2750 #define ABSTRACT_DECL(kind)
2751 #define VALUE(type, base)
2752 #define DECL(type, base) \
2754 #include "clang/AST/DeclNodes.inc"
2755 llvm_unreachable("invalid value decl kind");
2757 // These shouldn't make it here.
2758 case Decl::ObjCAtDefsField:
2759 case Decl::ObjCIvar:
2760 llvm_unreachable("forming non-member reference to ivar?");
2762 // Enum constants are always r-values and never references.
2763 // Unresolved using declarations are dependent.
2764 case Decl::EnumConstant:
2765 case Decl::UnresolvedUsingValue:
2766 valueKind = VK_RValue;
2769 // Fields and indirect fields that got here must be for
2770 // pointer-to-member expressions; we just call them l-values for
2771 // internal consistency, because this subexpression doesn't really
2772 // exist in the high-level semantics.
2774 case Decl::IndirectField:
2775 assert(getLangOpts().CPlusPlus &&
2776 "building reference to field in C?");
2778 // These can't have reference type in well-formed programs, but
2779 // for internal consistency we do this anyway.
2780 type = type.getNonReferenceType();
2781 valueKind = VK_LValue;
2784 // Non-type template parameters are either l-values or r-values
2785 // depending on the type.
2786 case Decl::NonTypeTemplateParm: {
2787 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2788 type = reftype->getPointeeType();
2789 valueKind = VK_LValue; // even if the parameter is an r-value reference
2793 // For non-references, we need to strip qualifiers just in case
2794 // the template parameter was declared as 'const int' or whatever.
2795 valueKind = VK_RValue;
2796 type = type.getUnqualifiedType();
2801 case Decl::VarTemplateSpecialization:
2802 case Decl::VarTemplatePartialSpecialization:
2803 // In C, "extern void blah;" is valid and is an r-value.
2804 if (!getLangOpts().CPlusPlus &&
2805 !type.hasQualifiers() &&
2806 type->isVoidType()) {
2807 valueKind = VK_RValue;
2812 case Decl::ImplicitParam:
2813 case Decl::ParmVar: {
2814 // These are always l-values.
2815 valueKind = VK_LValue;
2816 type = type.getNonReferenceType();
2818 // FIXME: Does the addition of const really only apply in
2819 // potentially-evaluated contexts? Since the variable isn't actually
2820 // captured in an unevaluated context, it seems that the answer is no.
2821 if (!isUnevaluatedContext()) {
2822 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2823 if (!CapturedType.isNull())
2824 type = CapturedType;
2830 case Decl::Function: {
2831 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2832 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2833 type = Context.BuiltinFnTy;
2834 valueKind = VK_RValue;
2839 const FunctionType *fty = type->castAs<FunctionType>();
2841 // If we're referring to a function with an __unknown_anytype
2842 // result type, make the entire expression __unknown_anytype.
2843 if (fty->getReturnType() == Context.UnknownAnyTy) {
2844 type = Context.UnknownAnyTy;
2845 valueKind = VK_RValue;
2849 // Functions are l-values in C++.
2850 if (getLangOpts().CPlusPlus) {
2851 valueKind = VK_LValue;
2855 // C99 DR 316 says that, if a function type comes from a
2856 // function definition (without a prototype), that type is only
2857 // used for checking compatibility. Therefore, when referencing
2858 // the function, we pretend that we don't have the full function
2860 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2861 isa<FunctionProtoType>(fty))
2862 type = Context.getFunctionNoProtoType(fty->getReturnType(),
2865 // Functions are r-values in C.
2866 valueKind = VK_RValue;
2870 case Decl::MSProperty:
2871 valueKind = VK_LValue;
2874 case Decl::CXXMethod:
2875 // If we're referring to a method with an __unknown_anytype
2876 // result type, make the entire expression __unknown_anytype.
2877 // This should only be possible with a type written directly.
2878 if (const FunctionProtoType *proto
2879 = dyn_cast<FunctionProtoType>(VD->getType()))
2880 if (proto->getReturnType() == Context.UnknownAnyTy) {
2881 type = Context.UnknownAnyTy;
2882 valueKind = VK_RValue;
2886 // C++ methods are l-values if static, r-values if non-static.
2887 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2888 valueKind = VK_LValue;
2893 case Decl::CXXConversion:
2894 case Decl::CXXDestructor:
2895 case Decl::CXXConstructor:
2896 valueKind = VK_RValue;
2900 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2905 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2906 PredefinedExpr::IdentType IT) {
2907 // Pick the current block, lambda, captured statement or function.
2908 Decl *currentDecl = nullptr;
2909 if (const BlockScopeInfo *BSI = getCurBlock())
2910 currentDecl = BSI->TheDecl;
2911 else if (const LambdaScopeInfo *LSI = getCurLambda())
2912 currentDecl = LSI->CallOperator;
2913 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2914 currentDecl = CSI->TheCapturedDecl;
2916 currentDecl = getCurFunctionOrMethodDecl();
2919 Diag(Loc, diag::ext_predef_outside_function);
2920 currentDecl = Context.getTranslationUnitDecl();
2924 if (cast<DeclContext>(currentDecl)->isDependentContext())
2925 ResTy = Context.DependentTy;
2927 // Pre-defined identifiers are of type char[x], where x is the length of
2929 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2931 llvm::APInt LengthI(32, Length + 1);
2932 if (IT == PredefinedExpr::LFunction)
2933 ResTy = Context.WideCharTy.withConst();
2935 ResTy = Context.CharTy.withConst();
2936 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2939 return new (Context) PredefinedExpr(Loc, ResTy, IT);
2942 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2943 PredefinedExpr::IdentType IT;
2946 default: llvm_unreachable("Unknown simple primary expr!");
2947 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2948 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2949 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2950 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
2951 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2952 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2955 return BuildPredefinedExpr(Loc, IT);
2958 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2959 SmallString<16> CharBuffer;
2960 bool Invalid = false;
2961 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2965 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2967 if (Literal.hadError())
2971 if (Literal.isWide())
2972 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2973 else if (Literal.isUTF16())
2974 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2975 else if (Literal.isUTF32())
2976 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2977 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2978 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
2980 Ty = Context.CharTy; // 'x' -> char in C++
2982 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2983 if (Literal.isWide())
2984 Kind = CharacterLiteral::Wide;
2985 else if (Literal.isUTF16())
2986 Kind = CharacterLiteral::UTF16;
2987 else if (Literal.isUTF32())
2988 Kind = CharacterLiteral::UTF32;
2990 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2993 if (Literal.getUDSuffix().empty())
2996 // We're building a user-defined literal.
2997 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2998 SourceLocation UDSuffixLoc =
2999 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3001 // Make sure we're allowed user-defined literals here.
3003 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3005 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3006 // operator "" X (ch)
3007 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3008 Lit, Tok.getLocation());
3011 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3012 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3013 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3014 Context.IntTy, Loc);
3017 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3018 QualType Ty, SourceLocation Loc) {
3019 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3021 using llvm::APFloat;
3022 APFloat Val(Format);
3024 APFloat::opStatus result = Literal.GetFloatValue(Val);
3026 // Overflow is always an error, but underflow is only an error if
3027 // we underflowed to zero (APFloat reports denormals as underflow).
3028 if ((result & APFloat::opOverflow) ||
3029 ((result & APFloat::opUnderflow) && Val.isZero())) {
3030 unsigned diagnostic;
3031 SmallString<20> buffer;
3032 if (result & APFloat::opOverflow) {
3033 diagnostic = diag::warn_float_overflow;
3034 APFloat::getLargest(Format).toString(buffer);
3036 diagnostic = diag::warn_float_underflow;
3037 APFloat::getSmallest(Format).toString(buffer);
3040 S.Diag(Loc, diagnostic)
3042 << StringRef(buffer.data(), buffer.size());
3045 bool isExact = (result == APFloat::opOK);
3046 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3049 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3050 // Fast path for a single digit (which is quite common). A single digit
3051 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3052 if (Tok.getLength() == 1) {
3053 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3054 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3057 SmallString<128> SpellingBuffer;
3058 // NumericLiteralParser wants to overread by one character. Add padding to
3059 // the buffer in case the token is copied to the buffer. If getSpelling()
3060 // returns a StringRef to the memory buffer, it should have a null char at
3061 // the EOF, so it is also safe.
3062 SpellingBuffer.resize(Tok.getLength() + 1);
3064 // Get the spelling of the token, which eliminates trigraphs, etc.
3065 bool Invalid = false;
3066 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3070 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3071 if (Literal.hadError)
3074 if (Literal.hasUDSuffix()) {
3075 // We're building a user-defined literal.
3076 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3077 SourceLocation UDSuffixLoc =
3078 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3080 // Make sure we're allowed user-defined literals here.
3082 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3085 if (Literal.isFloatingLiteral()) {
3086 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3087 // long double, the literal is treated as a call of the form
3088 // operator "" X (f L)
3089 CookedTy = Context.LongDoubleTy;
3091 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3092 // unsigned long long, the literal is treated as a call of the form
3093 // operator "" X (n ULL)
3094 CookedTy = Context.UnsignedLongLongTy;
3097 DeclarationName OpName =
3098 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3099 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3100 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3102 SourceLocation TokLoc = Tok.getLocation();
3104 // Perform literal operator lookup to determine if we're building a raw
3105 // literal or a cooked one.
3106 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3107 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3108 /*AllowRaw*/true, /*AllowTemplate*/true,
3109 /*AllowStringTemplate*/false)) {
3115 if (Literal.isFloatingLiteral()) {
3116 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3118 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3119 if (Literal.GetIntegerValue(ResultVal))
3120 Diag(Tok.getLocation(), diag::err_integer_too_large);
3121 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3124 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3128 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3129 // literal is treated as a call of the form
3130 // operator "" X ("n")
3131 unsigned Length = Literal.getUDSuffixOffset();
3132 QualType StrTy = Context.getConstantArrayType(
3133 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3134 ArrayType::Normal, 0);
3135 Expr *Lit = StringLiteral::Create(
3136 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3137 /*Pascal*/false, StrTy, &TokLoc, 1);
3138 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3141 case LOLR_Template: {
3142 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3143 // template), L is treated as a call fo the form
3144 // operator "" X <'c1', 'c2', ... 'ck'>()
3145 // where n is the source character sequence c1 c2 ... ck.
3146 TemplateArgumentListInfo ExplicitArgs;
3147 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3148 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3149 llvm::APSInt Value(CharBits, CharIsUnsigned);
3150 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3151 Value = TokSpelling[I];
3152 TemplateArgument Arg(Context, Value, Context.CharTy);
3153 TemplateArgumentLocInfo ArgInfo;
3154 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3156 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3159 case LOLR_StringTemplate:
3160 llvm_unreachable("unexpected literal operator lookup result");
3166 if (Literal.isFloatingLiteral()) {
3168 if (Literal.isFloat)
3169 Ty = Context.FloatTy;
3170 else if (!Literal.isLong)
3171 Ty = Context.DoubleTy;
3173 Ty = Context.LongDoubleTy;
3175 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3177 if (Ty == Context.DoubleTy) {
3178 if (getLangOpts().SinglePrecisionConstants) {
3179 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3180 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3181 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3182 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3185 } else if (!Literal.isIntegerLiteral()) {
3190 // 'long long' is a C99 or C++11 feature.
3191 if (!getLangOpts().C99 && Literal.isLongLong) {
3192 if (getLangOpts().CPlusPlus)
3193 Diag(Tok.getLocation(),
3194 getLangOpts().CPlusPlus11 ?
3195 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3197 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3200 // Get the value in the widest-possible width.
3201 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3202 // The microsoft literal suffix extensions support 128-bit literals, which
3203 // may be wider than [u]intmax_t.
3204 // FIXME: Actually, they don't. We seem to have accidentally invented the
3206 if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
3207 Context.getTargetInfo().hasInt128Type())
3209 llvm::APInt ResultVal(MaxWidth, 0);
3211 if (Literal.GetIntegerValue(ResultVal)) {
3212 // If this value didn't fit into uintmax_t, error and force to ull.
3213 Diag(Tok.getLocation(), diag::err_integer_too_large);
3214 Ty = Context.UnsignedLongLongTy;
3215 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3216 "long long is not intmax_t?");
3218 // If this value fits into a ULL, try to figure out what else it fits into
3219 // according to the rules of C99 6.4.4.1p5.
3221 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3222 // be an unsigned int.
3223 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3225 // Check from smallest to largest, picking the smallest type we can.
3228 // Microsoft specific integer suffixes are explicitly sized.
3229 if (Literal.MicrosoftInteger) {
3230 if (Literal.MicrosoftInteger > MaxWidth) {
3231 // If this target doesn't support __int128, error and force to ull.
3232 Diag(Tok.getLocation(), diag::err_int128_unsupported);
3234 Ty = Context.getIntMaxType();
3236 Width = Literal.MicrosoftInteger;
3237 Ty = Context.getIntTypeForBitwidth(Width,
3238 /*Signed=*/!Literal.isUnsigned);
3242 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3243 // Are int/unsigned possibilities?
3244 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3246 // Does it fit in a unsigned int?
3247 if (ResultVal.isIntN(IntSize)) {
3248 // Does it fit in a signed int?
3249 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3251 else if (AllowUnsigned)
3252 Ty = Context.UnsignedIntTy;
3257 // Are long/unsigned long possibilities?
3258 if (Ty.isNull() && !Literal.isLongLong) {
3259 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3261 // Does it fit in a unsigned long?
3262 if (ResultVal.isIntN(LongSize)) {
3263 // Does it fit in a signed long?
3264 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3265 Ty = Context.LongTy;
3266 else if (AllowUnsigned)
3267 Ty = Context.UnsignedLongTy;
3272 // Check long long if needed.
3274 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3276 // Does it fit in a unsigned long long?
3277 if (ResultVal.isIntN(LongLongSize)) {
3278 // Does it fit in a signed long long?
3279 // To be compatible with MSVC, hex integer literals ending with the
3280 // LL or i64 suffix are always signed in Microsoft mode.
3281 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3282 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3283 Ty = Context.LongLongTy;
3284 else if (AllowUnsigned)
3285 Ty = Context.UnsignedLongLongTy;
3286 Width = LongLongSize;
3290 // If we still couldn't decide a type, we probably have something that
3291 // does not fit in a signed long long, but has no U suffix.
3293 Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed);
3294 Ty = Context.UnsignedLongLongTy;
3295 Width = Context.getTargetInfo().getLongLongWidth();
3298 if (ResultVal.getBitWidth() != Width)
3299 ResultVal = ResultVal.trunc(Width);
3301 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3304 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3305 if (Literal.isImaginary)
3306 Res = new (Context) ImaginaryLiteral(Res,
3307 Context.getComplexType(Res->getType()));
3312 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3313 assert(E && "ActOnParenExpr() missing expr");
3314 return new (Context) ParenExpr(L, R, E);
3317 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3319 SourceRange ArgRange) {
3320 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3321 // scalar or vector data type argument..."
3322 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3323 // type (C99 6.2.5p18) or void.
3324 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3325 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3330 assert((T->isVoidType() || !T->isIncompleteType()) &&
3331 "Scalar types should always be complete");
3335 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3337 SourceRange ArgRange,
3338 UnaryExprOrTypeTrait TraitKind) {
3339 // Invalid types must be hard errors for SFINAE in C++.
3340 if (S.LangOpts.CPlusPlus)
3344 if (T->isFunctionType() &&
3345 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3346 // sizeof(function)/alignof(function) is allowed as an extension.
3347 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3348 << TraitKind << ArgRange;
3352 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3353 // this is an error (OpenCL v1.1 s6.3.k)
3354 if (T->isVoidType()) {
3355 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3356 : diag::ext_sizeof_alignof_void_type;
3357 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3364 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3366 SourceRange ArgRange,
3367 UnaryExprOrTypeTrait TraitKind) {
3368 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3369 // runtime doesn't allow it.
3370 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3371 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3372 << T << (TraitKind == UETT_SizeOf)
3380 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3381 /// pointer type is equal to T) and emit a warning if it is.
3382 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3384 // Don't warn if the operation changed the type.
3385 if (T != E->getType())
3388 // Now look for array decays.
3389 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3390 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3393 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3395 << ICE->getSubExpr()->getType();
3398 /// \brief Check the constraints on expression operands to unary type expression
3399 /// and type traits.
3401 /// Completes any types necessary and validates the constraints on the operand
3402 /// expression. The logic mostly mirrors the type-based overload, but may modify
3403 /// the expression as it completes the type for that expression through template
3404 /// instantiation, etc.
3405 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3406 UnaryExprOrTypeTrait ExprKind) {
3407 QualType ExprTy = E->getType();
3408 assert(!ExprTy->isReferenceType());
3410 if (ExprKind == UETT_VecStep)
3411 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3412 E->getSourceRange());
3414 // Whitelist some types as extensions
3415 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3416 E->getSourceRange(), ExprKind))
3419 // 'alignof' applied to an expression only requires the base element type of
3420 // the expression to be complete. 'sizeof' requires the expression's type to
3421 // be complete (and will attempt to complete it if it's an array of unknown
3423 if (ExprKind == UETT_AlignOf) {
3424 if (RequireCompleteType(E->getExprLoc(),
3425 Context.getBaseElementType(E->getType()),
3426 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3427 E->getSourceRange()))
3430 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3431 ExprKind, E->getSourceRange()))
3435 // Completing the expression's type may have changed it.
3436 ExprTy = E->getType();
3437 assert(!ExprTy->isReferenceType());
3439 if (ExprTy->isFunctionType()) {
3440 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3441 << ExprKind << E->getSourceRange();
3445 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3446 E->getSourceRange(), ExprKind))
3449 if (ExprKind == UETT_SizeOf) {
3450 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3451 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3452 QualType OType = PVD->getOriginalType();
3453 QualType Type = PVD->getType();
3454 if (Type->isPointerType() && OType->isArrayType()) {
3455 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3457 Diag(PVD->getLocation(), diag::note_declared_at);
3462 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3463 // decays into a pointer and returns an unintended result. This is most
3464 // likely a typo for "sizeof(array) op x".
3465 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3466 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3468 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3476 /// \brief Check the constraints on operands to unary expression and type
3479 /// This will complete any types necessary, and validate the various constraints
3480 /// on those operands.
3482 /// The UsualUnaryConversions() function is *not* called by this routine.
3483 /// C99 6.3.2.1p[2-4] all state:
3484 /// Except when it is the operand of the sizeof operator ...
3486 /// C++ [expr.sizeof]p4
3487 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3488 /// standard conversions are not applied to the operand of sizeof.
3490 /// This policy is followed for all of the unary trait expressions.
3491 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3492 SourceLocation OpLoc,
3493 SourceRange ExprRange,
3494 UnaryExprOrTypeTrait ExprKind) {
3495 if (ExprType->isDependentType())
3498 // C++ [expr.sizeof]p2:
3499 // When applied to a reference or a reference type, the result
3500 // is the size of the referenced type.
3501 // C++11 [expr.alignof]p3:
3502 // When alignof is applied to a reference type, the result
3503 // shall be the alignment of the referenced type.
3504 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3505 ExprType = Ref->getPointeeType();
3507 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3508 // When alignof or _Alignof is applied to an array type, the result
3509 // is the alignment of the element type.
3510 if (ExprKind == UETT_AlignOf)
3511 ExprType = Context.getBaseElementType(ExprType);
3513 if (ExprKind == UETT_VecStep)
3514 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3516 // Whitelist some types as extensions
3517 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3521 if (RequireCompleteType(OpLoc, ExprType,
3522 diag::err_sizeof_alignof_incomplete_type,
3523 ExprKind, ExprRange))
3526 if (ExprType->isFunctionType()) {
3527 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3528 << ExprKind << ExprRange;
3532 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3539 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3540 E = E->IgnoreParens();
3542 // Cannot know anything else if the expression is dependent.
3543 if (E->isTypeDependent())
3546 if (E->getObjectKind() == OK_BitField) {
3547 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3548 << 1 << E->getSourceRange();
3552 ValueDecl *D = nullptr;
3553 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3555 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3556 D = ME->getMemberDecl();
3559 // If it's a field, require the containing struct to have a
3560 // complete definition so that we can compute the layout.
3562 // This can happen in C++11 onwards, either by naming the member
3563 // in a way that is not transformed into a member access expression
3564 // (in an unevaluated operand, for instance), or by naming the member
3565 // in a trailing-return-type.
3567 // For the record, since __alignof__ on expressions is a GCC
3568 // extension, GCC seems to permit this but always gives the
3569 // nonsensical answer 0.
3571 // We don't really need the layout here --- we could instead just
3572 // directly check for all the appropriate alignment-lowing
3573 // attributes --- but that would require duplicating a lot of
3574 // logic that just isn't worth duplicating for such a marginal
3576 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3577 // Fast path this check, since we at least know the record has a
3578 // definition if we can find a member of it.
3579 if (!FD->getParent()->isCompleteDefinition()) {
3580 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3581 << E->getSourceRange();
3585 // Otherwise, if it's a field, and the field doesn't have
3586 // reference type, then it must have a complete type (or be a
3587 // flexible array member, which we explicitly want to
3588 // white-list anyway), which makes the following checks trivial.
3589 if (!FD->getType()->isReferenceType())
3593 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3596 bool Sema::CheckVecStepExpr(Expr *E) {
3597 E = E->IgnoreParens();
3599 // Cannot know anything else if the expression is dependent.
3600 if (E->isTypeDependent())
3603 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3606 /// \brief Build a sizeof or alignof expression given a type operand.
3608 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3609 SourceLocation OpLoc,
3610 UnaryExprOrTypeTrait ExprKind,
3615 QualType T = TInfo->getType();
3617 if (!T->isDependentType() &&
3618 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3621 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3622 return new (Context) UnaryExprOrTypeTraitExpr(
3623 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3626 /// \brief Build a sizeof or alignof expression given an expression
3629 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3630 UnaryExprOrTypeTrait ExprKind) {
3631 ExprResult PE = CheckPlaceholderExpr(E);
3637 // Verify that the operand is valid.
3638 bool isInvalid = false;
3639 if (E->isTypeDependent()) {
3640 // Delay type-checking for type-dependent expressions.
3641 } else if (ExprKind == UETT_AlignOf) {
3642 isInvalid = CheckAlignOfExpr(*this, E);
3643 } else if (ExprKind == UETT_VecStep) {
3644 isInvalid = CheckVecStepExpr(E);
3645 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
3646 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3649 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3655 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3656 PE = TransformToPotentiallyEvaluated(E);
3657 if (PE.isInvalid()) return ExprError();
3661 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3662 return new (Context) UnaryExprOrTypeTraitExpr(
3663 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3666 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3667 /// expr and the same for @c alignof and @c __alignof
3668 /// Note that the ArgRange is invalid if isType is false.
3670 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3671 UnaryExprOrTypeTrait ExprKind, bool IsType,
3672 void *TyOrEx, const SourceRange &ArgRange) {
3673 // If error parsing type, ignore.
3674 if (!TyOrEx) return ExprError();
3677 TypeSourceInfo *TInfo;
3678 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3679 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3682 Expr *ArgEx = (Expr *)TyOrEx;
3683 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3687 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3689 if (V.get()->isTypeDependent())
3690 return S.Context.DependentTy;
3692 // _Real and _Imag are only l-values for normal l-values.
3693 if (V.get()->getObjectKind() != OK_Ordinary) {
3694 V = S.DefaultLvalueConversion(V.get());
3699 // These operators return the element type of a complex type.
3700 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3701 return CT->getElementType();
3703 // Otherwise they pass through real integer and floating point types here.
3704 if (V.get()->getType()->isArithmeticType())
3705 return V.get()->getType();
3707 // Test for placeholders.
3708 ExprResult PR = S.CheckPlaceholderExpr(V.get());
3709 if (PR.isInvalid()) return QualType();
3710 if (PR.get() != V.get()) {
3712 return CheckRealImagOperand(S, V, Loc, IsReal);
3715 // Reject anything else.
3716 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3717 << (IsReal ? "__real" : "__imag");
3724 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3725 tok::TokenKind Kind, Expr *Input) {
3726 UnaryOperatorKind Opc;
3728 default: llvm_unreachable("Unknown unary op!");
3729 case tok::plusplus: Opc = UO_PostInc; break;
3730 case tok::minusminus: Opc = UO_PostDec; break;
3733 // Since this might is a postfix expression, get rid of ParenListExprs.
3734 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3735 if (Result.isInvalid()) return ExprError();
3736 Input = Result.get();
3738 return BuildUnaryOp(S, OpLoc, Opc, Input);
3741 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3743 /// \return true on error
3744 static bool checkArithmeticOnObjCPointer(Sema &S,
3745 SourceLocation opLoc,
3747 assert(op->getType()->isObjCObjectPointerType());
3748 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3749 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3752 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3753 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3754 << op->getSourceRange();
3759 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3760 Expr *idx, SourceLocation rbLoc) {
3761 // Since this might be a postfix expression, get rid of ParenListExprs.
3762 if (isa<ParenListExpr>(base)) {
3763 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3764 if (result.isInvalid()) return ExprError();
3765 base = result.get();
3768 // Handle any non-overload placeholder types in the base and index
3769 // expressions. We can't handle overloads here because the other
3770 // operand might be an overloadable type, in which case the overload
3771 // resolution for the operator overload should get the first crack
3773 if (base->getType()->isNonOverloadPlaceholderType()) {
3774 ExprResult result = CheckPlaceholderExpr(base);
3775 if (result.isInvalid()) return ExprError();
3776 base = result.get();
3778 if (idx->getType()->isNonOverloadPlaceholderType()) {
3779 ExprResult result = CheckPlaceholderExpr(idx);
3780 if (result.isInvalid()) return ExprError();
3784 // Build an unanalyzed expression if either operand is type-dependent.
3785 if (getLangOpts().CPlusPlus &&
3786 (base->isTypeDependent() || idx->isTypeDependent())) {
3787 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3788 VK_LValue, OK_Ordinary, rbLoc);
3791 // Use C++ overloaded-operator rules if either operand has record
3792 // type. The spec says to do this if either type is *overloadable*,
3793 // but enum types can't declare subscript operators or conversion
3794 // operators, so there's nothing interesting for overload resolution
3795 // to do if there aren't any record types involved.
3797 // ObjC pointers have their own subscripting logic that is not tied
3798 // to overload resolution and so should not take this path.
3799 if (getLangOpts().CPlusPlus &&
3800 (base->getType()->isRecordType() ||
3801 (!base->getType()->isObjCObjectPointerType() &&
3802 idx->getType()->isRecordType()))) {
3803 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3806 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3810 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3811 Expr *Idx, SourceLocation RLoc) {
3812 Expr *LHSExp = Base;
3815 // Perform default conversions.
3816 if (!LHSExp->getType()->getAs<VectorType>()) {
3817 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3818 if (Result.isInvalid())
3820 LHSExp = Result.get();
3822 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3823 if (Result.isInvalid())
3825 RHSExp = Result.get();
3827 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3828 ExprValueKind VK = VK_LValue;
3829 ExprObjectKind OK = OK_Ordinary;
3831 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3832 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3833 // in the subscript position. As a result, we need to derive the array base
3834 // and index from the expression types.
3835 Expr *BaseExpr, *IndexExpr;
3836 QualType ResultType;
3837 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3840 ResultType = Context.DependentTy;
3841 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3844 ResultType = PTy->getPointeeType();
3845 } else if (const ObjCObjectPointerType *PTy =
3846 LHSTy->getAs<ObjCObjectPointerType>()) {
3850 // Use custom logic if this should be the pseudo-object subscript
3852 if (!LangOpts.isSubscriptPointerArithmetic())
3853 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
3856 ResultType = PTy->getPointeeType();
3857 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3858 // Handle the uncommon case of "123[Ptr]".
3861 ResultType = PTy->getPointeeType();
3862 } else if (const ObjCObjectPointerType *PTy =
3863 RHSTy->getAs<ObjCObjectPointerType>()) {
3864 // Handle the uncommon case of "123[Ptr]".
3867 ResultType = PTy->getPointeeType();
3868 if (!LangOpts.isSubscriptPointerArithmetic()) {
3869 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3870 << ResultType << BaseExpr->getSourceRange();
3873 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3874 BaseExpr = LHSExp; // vectors: V[123]
3876 VK = LHSExp->getValueKind();
3877 if (VK != VK_RValue)
3878 OK = OK_VectorComponent;
3880 // FIXME: need to deal with const...
3881 ResultType = VTy->getElementType();
3882 } else if (LHSTy->isArrayType()) {
3883 // If we see an array that wasn't promoted by
3884 // DefaultFunctionArrayLvalueConversion, it must be an array that
3885 // wasn't promoted because of the C90 rule that doesn't
3886 // allow promoting non-lvalue arrays. Warn, then
3887 // force the promotion here.
3888 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3889 LHSExp->getSourceRange();
3890 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3891 CK_ArrayToPointerDecay).get();
3892 LHSTy = LHSExp->getType();
3896 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3897 } else if (RHSTy->isArrayType()) {
3898 // Same as previous, except for 123[f().a] case
3899 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3900 RHSExp->getSourceRange();
3901 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3902 CK_ArrayToPointerDecay).get();
3903 RHSTy = RHSExp->getType();
3907 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3909 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3910 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3913 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3914 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3915 << IndexExpr->getSourceRange());
3917 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3918 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3919 && !IndexExpr->isTypeDependent())
3920 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3922 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3923 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3924 // type. Note that Functions are not objects, and that (in C99 parlance)
3925 // incomplete types are not object types.
3926 if (ResultType->isFunctionType()) {
3927 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3928 << ResultType << BaseExpr->getSourceRange();
3932 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3933 // GNU extension: subscripting on pointer to void
3934 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3935 << BaseExpr->getSourceRange();
3937 // C forbids expressions of unqualified void type from being l-values.
3938 // See IsCForbiddenLValueType.
3939 if (!ResultType.hasQualifiers()) VK = VK_RValue;
3940 } else if (!ResultType->isDependentType() &&
3941 RequireCompleteType(LLoc, ResultType,
3942 diag::err_subscript_incomplete_type, BaseExpr))
3945 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3946 !ResultType.isCForbiddenLValueType());
3948 return new (Context)
3949 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
3952 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3954 ParmVarDecl *Param) {
3955 if (Param->hasUnparsedDefaultArg()) {
3957 diag::err_use_of_default_argument_to_function_declared_later) <<
3958 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3959 Diag(UnparsedDefaultArgLocs[Param],
3960 diag::note_default_argument_declared_here);
3964 if (Param->hasUninstantiatedDefaultArg()) {
3965 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3967 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3970 // Instantiate the expression.
3971 MultiLevelTemplateArgumentList MutiLevelArgList
3972 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
3974 InstantiatingTemplate Inst(*this, CallLoc, Param,
3975 MutiLevelArgList.getInnermost());
3976 if (Inst.isInvalid())
3981 // C++ [dcl.fct.default]p5:
3982 // The names in the [default argument] expression are bound, and
3983 // the semantic constraints are checked, at the point where the
3984 // default argument expression appears.
3985 ContextRAII SavedContext(*this, FD);
3986 LocalInstantiationScope Local(*this);
3987 Result = SubstExpr(UninstExpr, MutiLevelArgList);
3989 if (Result.isInvalid())
3992 // Check the expression as an initializer for the parameter.
3993 InitializedEntity Entity
3994 = InitializedEntity::InitializeParameter(Context, Param);
3995 InitializationKind Kind
3996 = InitializationKind::CreateCopy(Param->getLocation(),
3997 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3998 Expr *ResultE = Result.getAs<Expr>();
4000 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4001 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4002 if (Result.isInvalid())
4005 Expr *Arg = Result.getAs<Expr>();
4006 CheckCompletedExpr(Arg, Param->getOuterLocStart());
4007 // Build the default argument expression.
4008 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4011 // If the default expression creates temporaries, we need to
4012 // push them to the current stack of expression temporaries so they'll
4013 // be properly destroyed.
4014 // FIXME: We should really be rebuilding the default argument with new
4015 // bound temporaries; see the comment in PR5810.
4016 // We don't need to do that with block decls, though, because
4017 // blocks in default argument expression can never capture anything.
4018 if (isa<ExprWithCleanups>(Param->getInit())) {
4019 // Set the "needs cleanups" bit regardless of whether there are
4020 // any explicit objects.
4021 ExprNeedsCleanups = true;
4023 // Append all the objects to the cleanup list. Right now, this
4024 // should always be a no-op, because blocks in default argument
4025 // expressions should never be able to capture anything.
4026 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4027 "default argument expression has capturing blocks?");
4030 // We already type-checked the argument, so we know it works.
4031 // Just mark all of the declarations in this potentially-evaluated expression
4032 // as being "referenced".
4033 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4034 /*SkipLocalVariables=*/true);
4035 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4039 Sema::VariadicCallType
4040 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4042 if (Proto && Proto->isVariadic()) {
4043 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4044 return VariadicConstructor;
4045 else if (Fn && Fn->getType()->isBlockPointerType())
4046 return VariadicBlock;
4048 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4049 if (Method->isInstance())
4050 return VariadicMethod;
4051 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4052 return VariadicMethod;
4053 return VariadicFunction;
4055 return VariadicDoesNotApply;
4059 class FunctionCallCCC : public FunctionCallFilterCCC {
4061 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4062 unsigned NumArgs, MemberExpr *ME)
4063 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4064 FunctionName(FuncName) {}
4066 bool ValidateCandidate(const TypoCorrection &candidate) override {
4067 if (!candidate.getCorrectionSpecifier() ||
4068 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4072 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4076 const IdentifierInfo *const FunctionName;
4080 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4081 FunctionDecl *FDecl,
4082 ArrayRef<Expr *> Args) {
4083 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4084 DeclarationName FuncName = FDecl->getDeclName();
4085 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4086 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4088 if (TypoCorrection Corrected = S.CorrectTypo(
4089 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4090 S.getScopeForContext(S.CurContext), nullptr, CCC,
4091 Sema::CTK_ErrorRecovery)) {
4092 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4093 if (Corrected.isOverloaded()) {
4094 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4095 OverloadCandidateSet::iterator Best;
4096 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4097 CDEnd = Corrected.end();
4098 CD != CDEnd; ++CD) {
4099 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4100 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4103 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4105 ND = Best->Function;
4106 Corrected.setCorrectionDecl(ND);
4112 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4117 return TypoCorrection();
4120 /// ConvertArgumentsForCall - Converts the arguments specified in
4121 /// Args/NumArgs to the parameter types of the function FDecl with
4122 /// function prototype Proto. Call is the call expression itself, and
4123 /// Fn is the function expression. For a C++ member function, this
4124 /// routine does not attempt to convert the object argument. Returns
4125 /// true if the call is ill-formed.
4127 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4128 FunctionDecl *FDecl,
4129 const FunctionProtoType *Proto,
4130 ArrayRef<Expr *> Args,
4131 SourceLocation RParenLoc,
4132 bool IsExecConfig) {
4133 // Bail out early if calling a builtin with custom typechecking.
4134 // We don't need to do this in the
4136 if (unsigned ID = FDecl->getBuiltinID())
4137 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4140 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4141 // assignment, to the types of the corresponding parameter, ...
4142 unsigned NumParams = Proto->getNumParams();
4143 bool Invalid = false;
4144 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4145 unsigned FnKind = Fn->getType()->isBlockPointerType()
4147 : (IsExecConfig ? 3 /* kernel function (exec config) */
4148 : 0 /* function */);
4150 // If too few arguments are available (and we don't have default
4151 // arguments for the remaining parameters), don't make the call.
4152 if (Args.size() < NumParams) {
4153 if (Args.size() < MinArgs) {
4155 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4157 MinArgs == NumParams && !Proto->isVariadic()
4158 ? diag::err_typecheck_call_too_few_args_suggest
4159 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4160 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4161 << static_cast<unsigned>(Args.size())
4162 << TC.getCorrectionRange());
4163 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4165 MinArgs == NumParams && !Proto->isVariadic()
4166 ? diag::err_typecheck_call_too_few_args_one
4167 : diag::err_typecheck_call_too_few_args_at_least_one)
4168 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4170 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4171 ? diag::err_typecheck_call_too_few_args
4172 : diag::err_typecheck_call_too_few_args_at_least)
4173 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4174 << Fn->getSourceRange();
4176 // Emit the location of the prototype.
4177 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4178 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4183 Call->setNumArgs(Context, NumParams);
4186 // If too many are passed and not variadic, error on the extras and drop
4188 if (Args.size() > NumParams) {
4189 if (!Proto->isVariadic()) {
4191 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4193 MinArgs == NumParams && !Proto->isVariadic()
4194 ? diag::err_typecheck_call_too_many_args_suggest
4195 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4196 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4197 << static_cast<unsigned>(Args.size())
4198 << TC.getCorrectionRange());
4199 } else if (NumParams == 1 && FDecl &&
4200 FDecl->getParamDecl(0)->getDeclName())
4201 Diag(Args[NumParams]->getLocStart(),
4202 MinArgs == NumParams
4203 ? diag::err_typecheck_call_too_many_args_one
4204 : diag::err_typecheck_call_too_many_args_at_most_one)
4205 << FnKind << FDecl->getParamDecl(0)
4206 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4207 << SourceRange(Args[NumParams]->getLocStart(),
4208 Args.back()->getLocEnd());
4210 Diag(Args[NumParams]->getLocStart(),
4211 MinArgs == NumParams
4212 ? diag::err_typecheck_call_too_many_args
4213 : diag::err_typecheck_call_too_many_args_at_most)
4214 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4215 << Fn->getSourceRange()
4216 << SourceRange(Args[NumParams]->getLocStart(),
4217 Args.back()->getLocEnd());
4219 // Emit the location of the prototype.
4220 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4221 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4224 // This deletes the extra arguments.
4225 Call->setNumArgs(Context, NumParams);
4229 SmallVector<Expr *, 8> AllArgs;
4230 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4232 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4233 Proto, 0, Args, AllArgs, CallType);
4236 unsigned TotalNumArgs = AllArgs.size();
4237 for (unsigned i = 0; i < TotalNumArgs; ++i)
4238 Call->setArg(i, AllArgs[i]);
4243 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4244 const FunctionProtoType *Proto,
4245 unsigned FirstParam, ArrayRef<Expr *> Args,
4246 SmallVectorImpl<Expr *> &AllArgs,
4247 VariadicCallType CallType, bool AllowExplicit,
4248 bool IsListInitialization) {
4249 unsigned NumParams = Proto->getNumParams();
4250 bool Invalid = false;
4252 // Continue to check argument types (even if we have too few/many args).
4253 for (unsigned i = FirstParam; i < NumParams; i++) {
4254 QualType ProtoArgType = Proto->getParamType(i);
4257 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4258 if (ArgIx < Args.size()) {
4259 Arg = Args[ArgIx++];
4261 if (RequireCompleteType(Arg->getLocStart(),
4263 diag::err_call_incomplete_argument, Arg))
4266 // Strip the unbridged-cast placeholder expression off, if applicable.
4267 bool CFAudited = false;
4268 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4269 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4270 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4271 Arg = stripARCUnbridgedCast(Arg);
4272 else if (getLangOpts().ObjCAutoRefCount &&
4273 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4274 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4277 InitializedEntity Entity =
4278 Param ? InitializedEntity::InitializeParameter(Context, Param,
4280 : InitializedEntity::InitializeParameter(
4281 Context, ProtoArgType, Proto->isParamConsumed(i));
4283 // Remember that parameter belongs to a CF audited API.
4285 Entity.setParameterCFAudited();
4287 ExprResult ArgE = PerformCopyInitialization(
4288 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4289 if (ArgE.isInvalid())
4292 Arg = ArgE.getAs<Expr>();
4294 assert(Param && "can't use default arguments without a known callee");
4296 ExprResult ArgExpr =
4297 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4298 if (ArgExpr.isInvalid())
4301 Arg = ArgExpr.getAs<Expr>();
4304 // Check for array bounds violations for each argument to the call. This
4305 // check only triggers warnings when the argument isn't a more complex Expr
4306 // with its own checking, such as a BinaryOperator.
4307 CheckArrayAccess(Arg);
4309 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4310 CheckStaticArrayArgument(CallLoc, Param, Arg);
4312 AllArgs.push_back(Arg);
4315 // If this is a variadic call, handle args passed through "...".
4316 if (CallType != VariadicDoesNotApply) {
4317 // Assume that extern "C" functions with variadic arguments that
4318 // return __unknown_anytype aren't *really* variadic.
4319 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4320 FDecl->isExternC()) {
4321 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4322 QualType paramType; // ignored
4323 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4324 Invalid |= arg.isInvalid();
4325 AllArgs.push_back(arg.get());
4328 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4330 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4331 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4333 Invalid |= Arg.isInvalid();
4334 AllArgs.push_back(Arg.get());
4338 // Check for array bounds violations.
4339 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4340 CheckArrayAccess(Args[i]);
4345 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4346 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4347 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4348 TL = DTL.getOriginalLoc();
4349 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4350 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4351 << ATL.getLocalSourceRange();
4354 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4355 /// array parameter, check that it is non-null, and that if it is formed by
4356 /// array-to-pointer decay, the underlying array is sufficiently large.
4358 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4359 /// array type derivation, then for each call to the function, the value of the
4360 /// corresponding actual argument shall provide access to the first element of
4361 /// an array with at least as many elements as specified by the size expression.
4363 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4365 const Expr *ArgExpr) {
4366 // Static array parameters are not supported in C++.
4367 if (!Param || getLangOpts().CPlusPlus)
4370 QualType OrigTy = Param->getOriginalType();
4372 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4373 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4376 if (ArgExpr->isNullPointerConstant(Context,
4377 Expr::NPC_NeverValueDependent)) {
4378 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4379 DiagnoseCalleeStaticArrayParam(*this, Param);
4383 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4387 const ConstantArrayType *ArgCAT =
4388 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4392 if (ArgCAT->getSize().ult(CAT->getSize())) {
4393 Diag(CallLoc, diag::warn_static_array_too_small)
4394 << ArgExpr->getSourceRange()
4395 << (unsigned) ArgCAT->getSize().getZExtValue()
4396 << (unsigned) CAT->getSize().getZExtValue();
4397 DiagnoseCalleeStaticArrayParam(*this, Param);
4401 /// Given a function expression of unknown-any type, try to rebuild it
4402 /// to have a function type.
4403 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4405 /// Is the given type a placeholder that we need to lower out
4406 /// immediately during argument processing?
4407 static bool isPlaceholderToRemoveAsArg(QualType type) {
4408 // Placeholders are never sugared.
4409 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4410 if (!placeholder) return false;
4412 switch (placeholder->getKind()) {
4413 // Ignore all the non-placeholder types.
4414 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4415 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4416 #include "clang/AST/BuiltinTypes.def"
4419 // We cannot lower out overload sets; they might validly be resolved
4420 // by the call machinery.
4421 case BuiltinType::Overload:
4424 // Unbridged casts in ARC can be handled in some call positions and
4425 // should be left in place.
4426 case BuiltinType::ARCUnbridgedCast:
4429 // Pseudo-objects should be converted as soon as possible.
4430 case BuiltinType::PseudoObject:
4433 // The debugger mode could theoretically but currently does not try
4434 // to resolve unknown-typed arguments based on known parameter types.
4435 case BuiltinType::UnknownAny:
4438 // These are always invalid as call arguments and should be reported.
4439 case BuiltinType::BoundMember:
4440 case BuiltinType::BuiltinFn:
4443 llvm_unreachable("bad builtin type kind");
4446 /// Check an argument list for placeholders that we won't try to
4448 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4449 // Apply this processing to all the arguments at once instead of
4450 // dying at the first failure.
4451 bool hasInvalid = false;
4452 for (size_t i = 0, e = args.size(); i != e; i++) {
4453 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4454 ExprResult result = S.CheckPlaceholderExpr(args[i]);
4455 if (result.isInvalid()) hasInvalid = true;
4456 else args[i] = result.get();
4462 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4463 /// This provides the location of the left/right parens and a list of comma
4466 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4467 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4468 Expr *ExecConfig, bool IsExecConfig) {
4469 // Since this might be a postfix expression, get rid of ParenListExprs.
4470 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4471 if (Result.isInvalid()) return ExprError();
4474 if (checkArgsForPlaceholders(*this, ArgExprs))
4477 if (getLangOpts().CPlusPlus) {
4478 // If this is a pseudo-destructor expression, build the call immediately.
4479 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4480 if (!ArgExprs.empty()) {
4481 // Pseudo-destructor calls should not have any arguments.
4482 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4483 << FixItHint::CreateRemoval(
4484 SourceRange(ArgExprs[0]->getLocStart(),
4485 ArgExprs.back()->getLocEnd()));
4488 return new (Context)
4489 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4491 if (Fn->getType() == Context.PseudoObjectTy) {
4492 ExprResult result = CheckPlaceholderExpr(Fn);
4493 if (result.isInvalid()) return ExprError();
4497 // Determine whether this is a dependent call inside a C++ template,
4498 // in which case we won't do any semantic analysis now.
4499 // FIXME: Will need to cache the results of name lookup (including ADL) in
4501 bool Dependent = false;
4502 if (Fn->isTypeDependent())
4504 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4509 return new (Context) CUDAKernelCallExpr(
4510 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4511 Context.DependentTy, VK_RValue, RParenLoc);
4513 return new (Context) CallExpr(
4514 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4518 // Determine whether this is a call to an object (C++ [over.call.object]).
4519 if (Fn->getType()->isRecordType())
4520 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4523 if (Fn->getType() == Context.UnknownAnyTy) {
4524 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4525 if (result.isInvalid()) return ExprError();
4529 if (Fn->getType() == Context.BoundMemberTy) {
4530 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4534 // Check for overloaded calls. This can happen even in C due to extensions.
4535 if (Fn->getType() == Context.OverloadTy) {
4536 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4538 // We aren't supposed to apply this logic for if there's an '&' involved.
4539 if (!find.HasFormOfMemberPointer) {
4540 OverloadExpr *ovl = find.Expression;
4541 if (isa<UnresolvedLookupExpr>(ovl)) {
4542 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4543 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4544 RParenLoc, ExecConfig);
4546 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4552 // If we're directly calling a function, get the appropriate declaration.
4553 if (Fn->getType() == Context.UnknownAnyTy) {
4554 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4555 if (result.isInvalid()) return ExprError();
4559 Expr *NakedFn = Fn->IgnoreParens();
4561 NamedDecl *NDecl = nullptr;
4562 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4563 if (UnOp->getOpcode() == UO_AddrOf)
4564 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4566 if (isa<DeclRefExpr>(NakedFn))
4567 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4568 else if (isa<MemberExpr>(NakedFn))
4569 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4571 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4572 if (FD->hasAttr<EnableIfAttr>()) {
4573 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4574 Diag(Fn->getLocStart(),
4575 isa<CXXMethodDecl>(FD) ?
4576 diag::err_ovl_no_viable_member_function_in_call :
4577 diag::err_ovl_no_viable_function_in_call)
4578 << FD << FD->getSourceRange();
4579 Diag(FD->getLocation(),
4580 diag::note_ovl_candidate_disabled_by_enable_if_attr)
4581 << Attr->getCond()->getSourceRange() << Attr->getMessage();
4586 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4587 ExecConfig, IsExecConfig);
4591 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4592 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4593 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4595 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4596 << "cudaConfigureCall");
4597 QualType ConfigQTy = ConfigDecl->getType();
4599 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4600 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4601 MarkFunctionReferenced(LLLLoc, ConfigDecl);
4603 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
4604 /*IsExecConfig=*/true);
4607 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4609 /// __builtin_astype( value, dst type )
4611 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4612 SourceLocation BuiltinLoc,
4613 SourceLocation RParenLoc) {
4614 ExprValueKind VK = VK_RValue;
4615 ExprObjectKind OK = OK_Ordinary;
4616 QualType DstTy = GetTypeFromParser(ParsedDestTy);
4617 QualType SrcTy = E->getType();
4618 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4619 return ExprError(Diag(BuiltinLoc,
4620 diag::err_invalid_astype_of_different_size)
4623 << E->getSourceRange());
4624 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4627 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4628 /// provided arguments.
4630 /// __builtin_convertvector( value, dst type )
4632 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4633 SourceLocation BuiltinLoc,
4634 SourceLocation RParenLoc) {
4635 TypeSourceInfo *TInfo;
4636 GetTypeFromParser(ParsedDestTy, &TInfo);
4637 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4640 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4641 /// i.e. an expression not of \p OverloadTy. The expression should
4642 /// unary-convert to an expression of function-pointer or
4643 /// block-pointer type.
4645 /// \param NDecl the declaration being called, if available
4647 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4648 SourceLocation LParenLoc,
4649 ArrayRef<Expr *> Args,
4650 SourceLocation RParenLoc,
4651 Expr *Config, bool IsExecConfig) {
4652 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4653 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4655 // Promote the function operand.
4656 // We special-case function promotion here because we only allow promoting
4657 // builtin functions to function pointers in the callee of a call.
4660 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4661 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4662 CK_BuiltinFnToFnPtr).get();
4664 Result = CallExprUnaryConversions(Fn);
4666 if (Result.isInvalid())
4670 // Make the call expr early, before semantic checks. This guarantees cleanup
4671 // of arguments and function on error.
4674 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4675 cast<CallExpr>(Config), Args,
4676 Context.BoolTy, VK_RValue,
4679 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4680 VK_RValue, RParenLoc);
4682 // Bail out early if calling a builtin with custom typechecking.
4683 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4684 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4687 const FunctionType *FuncT;
4688 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4689 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4690 // have type pointer to function".
4691 FuncT = PT->getPointeeType()->getAs<FunctionType>();
4693 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4694 << Fn->getType() << Fn->getSourceRange());
4695 } else if (const BlockPointerType *BPT =
4696 Fn->getType()->getAs<BlockPointerType>()) {
4697 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4699 // Handle calls to expressions of unknown-any type.
4700 if (Fn->getType() == Context.UnknownAnyTy) {
4701 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4702 if (rewrite.isInvalid()) return ExprError();
4704 TheCall->setCallee(Fn);
4708 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4709 << Fn->getType() << Fn->getSourceRange());
4712 if (getLangOpts().CUDA) {
4714 // CUDA: Kernel calls must be to global functions
4715 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4716 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4717 << FDecl->getName() << Fn->getSourceRange());
4719 // CUDA: Kernel function must have 'void' return type
4720 if (!FuncT->getReturnType()->isVoidType())
4721 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4722 << Fn->getType() << Fn->getSourceRange());
4724 // CUDA: Calls to global functions must be configured
4725 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4726 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4727 << FDecl->getName() << Fn->getSourceRange());
4731 // Check for a valid return type
4732 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4736 // We know the result type of the call, set it.
4737 TheCall->setType(FuncT->getCallResultType(Context));
4738 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4740 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4742 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4746 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4749 // Check if we have too few/too many template arguments, based
4750 // on our knowledge of the function definition.
4751 const FunctionDecl *Def = nullptr;
4752 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4753 Proto = Def->getType()->getAs<FunctionProtoType>();
4754 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4755 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4756 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4759 // If the function we're calling isn't a function prototype, but we have
4760 // a function prototype from a prior declaratiom, use that prototype.
4761 if (!FDecl->hasPrototype())
4762 Proto = FDecl->getType()->getAs<FunctionProtoType>();
4765 // Promote the arguments (C99 6.5.2.2p6).
4766 for (unsigned i = 0, e = Args.size(); i != e; i++) {
4767 Expr *Arg = Args[i];
4769 if (Proto && i < Proto->getNumParams()) {
4770 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4771 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4773 PerformCopyInitialization(Entity, SourceLocation(), Arg);
4774 if (ArgE.isInvalid())
4777 Arg = ArgE.getAs<Expr>();
4780 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4782 if (ArgE.isInvalid())
4785 Arg = ArgE.getAs<Expr>();
4788 if (RequireCompleteType(Arg->getLocStart(),
4790 diag::err_call_incomplete_argument, Arg))
4793 TheCall->setArg(i, Arg);
4797 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4798 if (!Method->isStatic())
4799 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4800 << Fn->getSourceRange());
4802 // Check for sentinels
4804 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4806 // Do special checking on direct calls to functions.
4808 if (CheckFunctionCall(FDecl, TheCall, Proto))
4812 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4814 if (CheckPointerCall(NDecl, TheCall, Proto))
4817 if (CheckOtherCall(TheCall, Proto))
4821 return MaybeBindToTemporary(TheCall);
4825 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4826 SourceLocation RParenLoc, Expr *InitExpr) {
4827 assert(Ty && "ActOnCompoundLiteral(): missing type");
4828 // FIXME: put back this assert when initializers are worked out.
4829 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4831 TypeSourceInfo *TInfo;
4832 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4834 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4836 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4840 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4841 SourceLocation RParenLoc, Expr *LiteralExpr) {
4842 QualType literalType = TInfo->getType();
4844 if (literalType->isArrayType()) {
4845 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4846 diag::err_illegal_decl_array_incomplete_type,
4847 SourceRange(LParenLoc,
4848 LiteralExpr->getSourceRange().getEnd())))
4850 if (literalType->isVariableArrayType())
4851 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4852 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4853 } else if (!literalType->isDependentType() &&
4854 RequireCompleteType(LParenLoc, literalType,
4855 diag::err_typecheck_decl_incomplete_type,
4856 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4859 InitializedEntity Entity
4860 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4861 InitializationKind Kind
4862 = InitializationKind::CreateCStyleCast(LParenLoc,
4863 SourceRange(LParenLoc, RParenLoc),
4865 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4866 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4868 if (Result.isInvalid())
4870 LiteralExpr = Result.get();
4872 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
4874 !LiteralExpr->isTypeDependent() &&
4875 !LiteralExpr->isValueDependent() &&
4876 !literalType->isDependentType()) { // 6.5.2.5p3
4877 if (CheckForConstantInitializer(LiteralExpr, literalType))
4881 // In C, compound literals are l-values for some reason.
4882 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4884 return MaybeBindToTemporary(
4885 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4886 VK, LiteralExpr, isFileScope));
4890 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4891 SourceLocation RBraceLoc) {
4892 // Immediately handle non-overload placeholders. Overloads can be
4893 // resolved contextually, but everything else here can't.
4894 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4895 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4896 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4898 // Ignore failures; dropping the entire initializer list because
4899 // of one failure would be terrible for indexing/etc.
4900 if (result.isInvalid()) continue;
4902 InitArgList[I] = result.get();
4906 // Semantic analysis for initializers is done by ActOnDeclarator() and
4907 // CheckInitializer() - it requires knowledge of the object being intialized.
4909 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4911 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4915 /// Do an explicit extend of the given block pointer if we're in ARC.
4916 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4917 assert(E.get()->getType()->isBlockPointerType());
4918 assert(E.get()->isRValue());
4920 // Only do this in an r-value context.
4921 if (!S.getLangOpts().ObjCAutoRefCount) return;
4923 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4924 CK_ARCExtendBlockObject, E.get(),
4925 /*base path*/ nullptr, VK_RValue);
4926 S.ExprNeedsCleanups = true;
4929 /// Prepare a conversion of the given expression to an ObjC object
4931 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4932 QualType type = E.get()->getType();
4933 if (type->isObjCObjectPointerType()) {
4935 } else if (type->isBlockPointerType()) {
4936 maybeExtendBlockObject(*this, E);
4937 return CK_BlockPointerToObjCPointerCast;
4939 assert(type->isPointerType());
4940 return CK_CPointerToObjCPointerCast;
4944 /// Prepares for a scalar cast, performing all the necessary stages
4945 /// except the final cast and returning the kind required.
4946 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4947 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4948 // Also, callers should have filtered out the invalid cases with
4949 // pointers. Everything else should be possible.
4951 QualType SrcTy = Src.get()->getType();
4952 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4955 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4956 case Type::STK_MemberPointer:
4957 llvm_unreachable("member pointer type in C");
4959 case Type::STK_CPointer:
4960 case Type::STK_BlockPointer:
4961 case Type::STK_ObjCObjectPointer:
4962 switch (DestTy->getScalarTypeKind()) {
4963 case Type::STK_CPointer: {
4964 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4965 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4966 if (SrcAS != DestAS)
4967 return CK_AddressSpaceConversion;
4970 case Type::STK_BlockPointer:
4971 return (SrcKind == Type::STK_BlockPointer
4972 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4973 case Type::STK_ObjCObjectPointer:
4974 if (SrcKind == Type::STK_ObjCObjectPointer)
4976 if (SrcKind == Type::STK_CPointer)
4977 return CK_CPointerToObjCPointerCast;
4978 maybeExtendBlockObject(*this, Src);
4979 return CK_BlockPointerToObjCPointerCast;
4980 case Type::STK_Bool:
4981 return CK_PointerToBoolean;
4982 case Type::STK_Integral:
4983 return CK_PointerToIntegral;
4984 case Type::STK_Floating:
4985 case Type::STK_FloatingComplex:
4986 case Type::STK_IntegralComplex:
4987 case Type::STK_MemberPointer:
4988 llvm_unreachable("illegal cast from pointer");
4990 llvm_unreachable("Should have returned before this");
4992 case Type::STK_Bool: // casting from bool is like casting from an integer
4993 case Type::STK_Integral:
4994 switch (DestTy->getScalarTypeKind()) {
4995 case Type::STK_CPointer:
4996 case Type::STK_ObjCObjectPointer:
4997 case Type::STK_BlockPointer:
4998 if (Src.get()->isNullPointerConstant(Context,
4999 Expr::NPC_ValueDependentIsNull))
5000 return CK_NullToPointer;
5001 return CK_IntegralToPointer;
5002 case Type::STK_Bool:
5003 return CK_IntegralToBoolean;
5004 case Type::STK_Integral:
5005 return CK_IntegralCast;
5006 case Type::STK_Floating:
5007 return CK_IntegralToFloating;
5008 case Type::STK_IntegralComplex:
5009 Src = ImpCastExprToType(Src.get(),
5010 DestTy->castAs<ComplexType>()->getElementType(),
5012 return CK_IntegralRealToComplex;
5013 case Type::STK_FloatingComplex:
5014 Src = ImpCastExprToType(Src.get(),
5015 DestTy->castAs<ComplexType>()->getElementType(),
5016 CK_IntegralToFloating);
5017 return CK_FloatingRealToComplex;
5018 case Type::STK_MemberPointer:
5019 llvm_unreachable("member pointer type in C");
5021 llvm_unreachable("Should have returned before this");
5023 case Type::STK_Floating:
5024 switch (DestTy->getScalarTypeKind()) {
5025 case Type::STK_Floating:
5026 return CK_FloatingCast;
5027 case Type::STK_Bool:
5028 return CK_FloatingToBoolean;
5029 case Type::STK_Integral:
5030 return CK_FloatingToIntegral;
5031 case Type::STK_FloatingComplex:
5032 Src = ImpCastExprToType(Src.get(),
5033 DestTy->castAs<ComplexType>()->getElementType(),
5035 return CK_FloatingRealToComplex;
5036 case Type::STK_IntegralComplex:
5037 Src = ImpCastExprToType(Src.get(),
5038 DestTy->castAs<ComplexType>()->getElementType(),
5039 CK_FloatingToIntegral);
5040 return CK_IntegralRealToComplex;
5041 case Type::STK_CPointer:
5042 case Type::STK_ObjCObjectPointer:
5043 case Type::STK_BlockPointer:
5044 llvm_unreachable("valid float->pointer cast?");
5045 case Type::STK_MemberPointer:
5046 llvm_unreachable("member pointer type in C");
5048 llvm_unreachable("Should have returned before this");
5050 case Type::STK_FloatingComplex:
5051 switch (DestTy->getScalarTypeKind()) {
5052 case Type::STK_FloatingComplex:
5053 return CK_FloatingComplexCast;
5054 case Type::STK_IntegralComplex:
5055 return CK_FloatingComplexToIntegralComplex;
5056 case Type::STK_Floating: {
5057 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5058 if (Context.hasSameType(ET, DestTy))
5059 return CK_FloatingComplexToReal;
5060 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5061 return CK_FloatingCast;
5063 case Type::STK_Bool:
5064 return CK_FloatingComplexToBoolean;
5065 case Type::STK_Integral:
5066 Src = ImpCastExprToType(Src.get(),
5067 SrcTy->castAs<ComplexType>()->getElementType(),
5068 CK_FloatingComplexToReal);
5069 return CK_FloatingToIntegral;
5070 case Type::STK_CPointer:
5071 case Type::STK_ObjCObjectPointer:
5072 case Type::STK_BlockPointer:
5073 llvm_unreachable("valid complex float->pointer cast?");
5074 case Type::STK_MemberPointer:
5075 llvm_unreachable("member pointer type in C");
5077 llvm_unreachable("Should have returned before this");
5079 case Type::STK_IntegralComplex:
5080 switch (DestTy->getScalarTypeKind()) {
5081 case Type::STK_FloatingComplex:
5082 return CK_IntegralComplexToFloatingComplex;
5083 case Type::STK_IntegralComplex:
5084 return CK_IntegralComplexCast;
5085 case Type::STK_Integral: {
5086 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5087 if (Context.hasSameType(ET, DestTy))
5088 return CK_IntegralComplexToReal;
5089 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5090 return CK_IntegralCast;
5092 case Type::STK_Bool:
5093 return CK_IntegralComplexToBoolean;
5094 case Type::STK_Floating:
5095 Src = ImpCastExprToType(Src.get(),
5096 SrcTy->castAs<ComplexType>()->getElementType(),
5097 CK_IntegralComplexToReal);
5098 return CK_IntegralToFloating;
5099 case Type::STK_CPointer:
5100 case Type::STK_ObjCObjectPointer:
5101 case Type::STK_BlockPointer:
5102 llvm_unreachable("valid complex int->pointer cast?");
5103 case Type::STK_MemberPointer:
5104 llvm_unreachable("member pointer type in C");
5106 llvm_unreachable("Should have returned before this");
5109 llvm_unreachable("Unhandled scalar cast");
5112 static bool breakDownVectorType(QualType type, uint64_t &len,
5113 QualType &eltType) {
5114 // Vectors are simple.
5115 if (const VectorType *vecType = type->getAs<VectorType>()) {
5116 len = vecType->getNumElements();
5117 eltType = vecType->getElementType();
5118 assert(eltType->isScalarType());
5122 // We allow lax conversion to and from non-vector types, but only if
5123 // they're real types (i.e. non-complex, non-pointer scalar types).
5124 if (!type->isRealType()) return false;
5131 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5132 uint64_t srcLen, destLen;
5133 QualType srcElt, destElt;
5134 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5135 if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5137 // ASTContext::getTypeSize will return the size rounded up to a
5138 // power of 2, so instead of using that, we need to use the raw
5139 // element size multiplied by the element count.
5140 uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5141 uint64_t destEltSize = S.Context.getTypeSize(destElt);
5143 return (srcLen * srcEltSize == destLen * destEltSize);
5146 /// Is this a legal conversion between two known vector types?
5147 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5148 assert(destTy->isVectorType() || srcTy->isVectorType());
5150 if (!Context.getLangOpts().LaxVectorConversions)
5152 return VectorTypesMatch(*this, srcTy, destTy);
5155 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5157 assert(VectorTy->isVectorType() && "Not a vector type!");
5159 if (Ty->isVectorType() || Ty->isIntegerType()) {
5160 if (!VectorTypesMatch(*this, Ty, VectorTy))
5161 return Diag(R.getBegin(),
5162 Ty->isVectorType() ?
5163 diag::err_invalid_conversion_between_vectors :
5164 diag::err_invalid_conversion_between_vector_and_integer)
5165 << VectorTy << Ty << R;
5167 return Diag(R.getBegin(),
5168 diag::err_invalid_conversion_between_vector_and_scalar)
5169 << VectorTy << Ty << R;
5175 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5176 Expr *CastExpr, CastKind &Kind) {
5177 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5179 QualType SrcTy = CastExpr->getType();
5181 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5182 // an ExtVectorType.
5183 // In OpenCL, casts between vectors of different types are not allowed.
5184 // (See OpenCL 6.2).
5185 if (SrcTy->isVectorType()) {
5186 if (!VectorTypesMatch(*this, SrcTy, DestTy)
5187 || (getLangOpts().OpenCL &&
5188 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5189 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5190 << DestTy << SrcTy << R;
5197 // All non-pointer scalars can be cast to ExtVector type. The appropriate
5198 // conversion will take place first from scalar to elt type, and then
5199 // splat from elt type to vector.
5200 if (SrcTy->isPointerType())
5201 return Diag(R.getBegin(),
5202 diag::err_invalid_conversion_between_vector_and_scalar)
5203 << DestTy << SrcTy << R;
5205 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5206 ExprResult CastExprRes = CastExpr;
5207 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5208 if (CastExprRes.isInvalid())
5210 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5212 Kind = CK_VectorSplat;
5217 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5218 Declarator &D, ParsedType &Ty,
5219 SourceLocation RParenLoc, Expr *CastExpr) {
5220 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5221 "ActOnCastExpr(): missing type or expr");
5223 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5224 if (D.isInvalidType())
5227 if (getLangOpts().CPlusPlus) {
5228 // Check that there are no default arguments (C++ only).
5229 CheckExtraCXXDefaultArguments(D);
5232 checkUnusedDeclAttributes(D);
5234 QualType castType = castTInfo->getType();
5235 Ty = CreateParsedType(castType, castTInfo);
5237 bool isVectorLiteral = false;
5239 // Check for an altivec or OpenCL literal,
5240 // i.e. all the elements are integer constants.
5241 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5242 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5243 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5244 && castType->isVectorType() && (PE || PLE)) {
5245 if (PLE && PLE->getNumExprs() == 0) {
5246 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5249 if (PE || PLE->getNumExprs() == 1) {
5250 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5251 if (!E->getType()->isVectorType())
5252 isVectorLiteral = true;
5255 isVectorLiteral = true;
5258 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5259 // then handle it as such.
5260 if (isVectorLiteral)
5261 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5263 // If the Expr being casted is a ParenListExpr, handle it specially.
5264 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5265 // sequence of BinOp comma operators.
5266 if (isa<ParenListExpr>(CastExpr)) {
5267 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5268 if (Result.isInvalid()) return ExprError();
5269 CastExpr = Result.get();
5272 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5273 !getSourceManager().isInSystemMacro(LParenLoc))
5274 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5276 CheckTollFreeBridgeCast(castType, CastExpr);
5278 CheckObjCBridgeRelatedCast(castType, CastExpr);
5280 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5283 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5284 SourceLocation RParenLoc, Expr *E,
5285 TypeSourceInfo *TInfo) {
5286 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5287 "Expected paren or paren list expression");
5292 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5293 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5294 LiteralLParenLoc = PE->getLParenLoc();
5295 LiteralRParenLoc = PE->getRParenLoc();
5296 exprs = PE->getExprs();
5297 numExprs = PE->getNumExprs();
5298 } else { // isa<ParenExpr> by assertion at function entrance
5299 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5300 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5301 subExpr = cast<ParenExpr>(E)->getSubExpr();
5306 QualType Ty = TInfo->getType();
5307 assert(Ty->isVectorType() && "Expected vector type");
5309 SmallVector<Expr *, 8> initExprs;
5310 const VectorType *VTy = Ty->getAs<VectorType>();
5311 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5313 // '(...)' form of vector initialization in AltiVec: the number of
5314 // initializers must be one or must match the size of the vector.
5315 // If a single value is specified in the initializer then it will be
5316 // replicated to all the components of the vector
5317 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5318 // The number of initializers must be one or must match the size of the
5319 // vector. If a single value is specified in the initializer then it will
5320 // be replicated to all the components of the vector
5321 if (numExprs == 1) {
5322 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5323 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5324 if (Literal.isInvalid())
5326 Literal = ImpCastExprToType(Literal.get(), ElemTy,
5327 PrepareScalarCast(Literal, ElemTy));
5328 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5330 else if (numExprs < numElems) {
5331 Diag(E->getExprLoc(),
5332 diag::err_incorrect_number_of_vector_initializers);
5336 initExprs.append(exprs, exprs + numExprs);
5339 // For OpenCL, when the number of initializers is a single value,
5340 // it will be replicated to all components of the vector.
5341 if (getLangOpts().OpenCL &&
5342 VTy->getVectorKind() == VectorType::GenericVector &&
5344 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5345 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5346 if (Literal.isInvalid())
5348 Literal = ImpCastExprToType(Literal.get(), ElemTy,
5349 PrepareScalarCast(Literal, ElemTy));
5350 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5353 initExprs.append(exprs, exprs + numExprs);
5355 // FIXME: This means that pretty-printing the final AST will produce curly
5356 // braces instead of the original commas.
5357 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5358 initExprs, LiteralRParenLoc);
5360 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5363 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5364 /// the ParenListExpr into a sequence of comma binary operators.
5366 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5367 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5371 ExprResult Result(E->getExpr(0));
5373 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5374 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5377 if (Result.isInvalid()) return ExprError();
5379 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5382 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5385 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5389 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5390 /// constant and the other is not a pointer. Returns true if a diagnostic is
5392 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5393 SourceLocation QuestionLoc) {
5394 Expr *NullExpr = LHSExpr;
5395 Expr *NonPointerExpr = RHSExpr;
5396 Expr::NullPointerConstantKind NullKind =
5397 NullExpr->isNullPointerConstant(Context,
5398 Expr::NPC_ValueDependentIsNotNull);
5400 if (NullKind == Expr::NPCK_NotNull) {
5402 NonPointerExpr = LHSExpr;
5404 NullExpr->isNullPointerConstant(Context,
5405 Expr::NPC_ValueDependentIsNotNull);
5408 if (NullKind == Expr::NPCK_NotNull)
5411 if (NullKind == Expr::NPCK_ZeroExpression)
5414 if (NullKind == Expr::NPCK_ZeroLiteral) {
5415 // In this case, check to make sure that we got here from a "NULL"
5416 // string in the source code.
5417 NullExpr = NullExpr->IgnoreParenImpCasts();
5418 SourceLocation loc = NullExpr->getExprLoc();
5419 if (!findMacroSpelling(loc, "NULL"))
5423 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5424 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5425 << NonPointerExpr->getType() << DiagType
5426 << NonPointerExpr->getSourceRange();
5430 /// \brief Return false if the condition expression is valid, true otherwise.
5431 static bool checkCondition(Sema &S, Expr *Cond) {
5432 QualType CondTy = Cond->getType();
5435 if (CondTy->isScalarType()) return false;
5437 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5438 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5441 // Emit the proper error message.
5442 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5443 diag::err_typecheck_cond_expect_scalar :
5444 diag::err_typecheck_cond_expect_scalar_or_vector)
5449 /// \brief Return false if the two expressions can be converted to a vector,
5451 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5454 // Both operands should be of scalar type.
5455 if (!LHS.get()->getType()->isScalarType()) {
5456 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5460 if (!RHS.get()->getType()->isScalarType()) {
5461 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5466 // Implicity convert these scalars to the type of the condition.
5467 LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
5468 RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
5472 /// \brief Handle when one or both operands are void type.
5473 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5475 Expr *LHSExpr = LHS.get();
5476 Expr *RHSExpr = RHS.get();
5478 if (!LHSExpr->getType()->isVoidType())
5479 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5480 << RHSExpr->getSourceRange();
5481 if (!RHSExpr->getType()->isVoidType())
5482 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5483 << LHSExpr->getSourceRange();
5484 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5485 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5486 return S.Context.VoidTy;
5489 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5491 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5492 QualType PointerTy) {
5493 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5494 !NullExpr.get()->isNullPointerConstant(S.Context,
5495 Expr::NPC_ValueDependentIsNull))
5498 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5502 /// \brief Checks compatibility between two pointers and return the resulting
5504 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5506 SourceLocation Loc) {
5507 QualType LHSTy = LHS.get()->getType();
5508 QualType RHSTy = RHS.get()->getType();
5510 if (S.Context.hasSameType(LHSTy, RHSTy)) {
5511 // Two identical pointers types are always compatible.
5515 QualType lhptee, rhptee;
5517 // Get the pointee types.
5518 bool IsBlockPointer = false;
5519 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5520 lhptee = LHSBTy->getPointeeType();
5521 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5522 IsBlockPointer = true;
5524 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5525 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5528 // C99 6.5.15p6: If both operands are pointers to compatible types or to
5529 // differently qualified versions of compatible types, the result type is
5530 // a pointer to an appropriately qualified version of the composite
5533 // Only CVR-qualifiers exist in the standard, and the differently-qualified
5534 // clause doesn't make sense for our extensions. E.g. address space 2 should
5535 // be incompatible with address space 3: they may live on different devices or
5537 Qualifiers lhQual = lhptee.getQualifiers();
5538 Qualifiers rhQual = rhptee.getQualifiers();
5540 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5541 lhQual.removeCVRQualifiers();
5542 rhQual.removeCVRQualifiers();
5544 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5545 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5547 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5549 if (CompositeTy.isNull()) {
5550 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5551 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5552 << RHS.get()->getSourceRange();
5553 // In this situation, we assume void* type. No especially good
5554 // reason, but this is what gcc does, and we do have to pick
5555 // to get a consistent AST.
5556 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5557 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5558 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5562 // The pointer types are compatible.
5563 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5565 ResultTy = S.Context.getBlockPointerType(ResultTy);
5567 ResultTy = S.Context.getPointerType(ResultTy);
5569 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5570 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5574 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5575 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5576 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5577 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5578 if (QT->isObjCIdType())
5581 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5585 if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5586 if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5589 ObjCProtocolDecl* PNSCopying =
5590 S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5591 ObjCProtocolDecl* PNSObject =
5592 S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5594 for (auto *Proto : OPT->quals()) {
5595 if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5596 (PNSObject && declaresSameEntity(Proto, PNSObject)))
5604 /// \brief Return the resulting type when the operands are both block pointers.
5605 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5608 SourceLocation Loc) {
5609 QualType LHSTy = LHS.get()->getType();
5610 QualType RHSTy = RHS.get()->getType();
5612 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5613 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5614 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5615 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5616 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5619 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5620 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5621 << RHS.get()->getSourceRange();
5625 // We have 2 block pointer types.
5626 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5629 /// \brief Return the resulting type when the operands are both pointers.
5631 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5633 SourceLocation Loc) {
5634 // get the pointer types
5635 QualType LHSTy = LHS.get()->getType();
5636 QualType RHSTy = RHS.get()->getType();
5638 // get the "pointed to" types
5639 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5640 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5642 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5643 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5644 // Figure out necessary qualifiers (C99 6.5.15p6)
5645 QualType destPointee
5646 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5647 QualType destType = S.Context.getPointerType(destPointee);
5648 // Add qualifiers if necessary.
5649 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5650 // Promote to void*.
5651 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5654 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5655 QualType destPointee
5656 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5657 QualType destType = S.Context.getPointerType(destPointee);
5658 // Add qualifiers if necessary.
5659 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5660 // Promote to void*.
5661 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5665 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5668 /// \brief Return false if the first expression is not an integer and the second
5669 /// expression is not a pointer, true otherwise.
5670 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5671 Expr* PointerExpr, SourceLocation Loc,
5672 bool IsIntFirstExpr) {
5673 if (!PointerExpr->getType()->isPointerType() ||
5674 !Int.get()->getType()->isIntegerType())
5677 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5678 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5680 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
5681 << Expr1->getType() << Expr2->getType()
5682 << Expr1->getSourceRange() << Expr2->getSourceRange();
5683 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5684 CK_IntegralToPointer);
5688 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5689 /// In that case, LHS = cond.
5691 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5692 ExprResult &RHS, ExprValueKind &VK,
5694 SourceLocation QuestionLoc) {
5696 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5697 if (!LHSResult.isUsable()) return QualType();
5700 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5701 if (!RHSResult.isUsable()) return QualType();
5704 // C++ is sufficiently different to merit its own checker.
5705 if (getLangOpts().CPlusPlus)
5706 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5711 // First, check the condition.
5712 Cond = UsualUnaryConversions(Cond.get());
5713 if (Cond.isInvalid())
5715 if (checkCondition(*this, Cond.get()))
5718 // Now check the two expressions.
5719 if (LHS.get()->getType()->isVectorType() ||
5720 RHS.get()->getType()->isVectorType())
5721 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5723 UsualArithmeticConversions(LHS, RHS);
5724 if (LHS.isInvalid() || RHS.isInvalid())
5727 QualType CondTy = Cond.get()->getType();
5728 QualType LHSTy = LHS.get()->getType();
5729 QualType RHSTy = RHS.get()->getType();
5731 // If the condition is a vector, and both operands are scalar,
5732 // attempt to implicity convert them to the vector type to act like the
5733 // built in select. (OpenCL v1.1 s6.3.i)
5734 if (getLangOpts().OpenCL && CondTy->isVectorType())
5735 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5738 // If both operands have arithmetic type, do the usual arithmetic conversions
5739 // to find a common type: C99 6.5.15p3,5.
5740 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5741 return LHS.get()->getType();
5743 // If both operands are the same structure or union type, the result is that
5745 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5746 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5747 if (LHSRT->getDecl() == RHSRT->getDecl())
5748 // "If both the operands have structure or union type, the result has
5749 // that type." This implies that CV qualifiers are dropped.
5750 return LHSTy.getUnqualifiedType();
5751 // FIXME: Type of conditional expression must be complete in C mode.
5754 // C99 6.5.15p5: "If both operands have void type, the result has void type."
5755 // The following || allows only one side to be void (a GCC-ism).
5756 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5757 return checkConditionalVoidType(*this, LHS, RHS);
5760 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5761 // the type of the other operand."
5762 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5763 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5765 // All objective-c pointer type analysis is done here.
5766 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5768 if (LHS.isInvalid() || RHS.isInvalid())
5770 if (!compositeType.isNull())
5771 return compositeType;
5774 // Handle block pointer types.
5775 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5776 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5779 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5780 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5781 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5784 // GCC compatibility: soften pointer/integer mismatch. Note that
5785 // null pointers have been filtered out by this point.
5786 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5787 /*isIntFirstExpr=*/true))
5789 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5790 /*isIntFirstExpr=*/false))
5793 // Emit a better diagnostic if one of the expressions is a null pointer
5794 // constant and the other is not a pointer type. In this case, the user most
5795 // likely forgot to take the address of the other expression.
5796 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5799 // Otherwise, the operands are not compatible.
5800 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5801 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5802 << RHS.get()->getSourceRange();
5806 /// FindCompositeObjCPointerType - Helper method to find composite type of
5807 /// two objective-c pointer types of the two input expressions.
5808 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5809 SourceLocation QuestionLoc) {
5810 QualType LHSTy = LHS.get()->getType();
5811 QualType RHSTy = RHS.get()->getType();
5813 // Handle things like Class and struct objc_class*. Here we case the result
5814 // to the pseudo-builtin, because that will be implicitly cast back to the
5815 // redefinition type if an attempt is made to access its fields.
5816 if (LHSTy->isObjCClassType() &&
5817 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5818 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5821 if (RHSTy->isObjCClassType() &&
5822 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5823 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5826 // And the same for struct objc_object* / id
5827 if (LHSTy->isObjCIdType() &&
5828 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5829 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5832 if (RHSTy->isObjCIdType() &&
5833 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5834 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5837 // And the same for struct objc_selector* / SEL
5838 if (Context.isObjCSelType(LHSTy) &&
5839 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5840 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
5843 if (Context.isObjCSelType(RHSTy) &&
5844 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5845 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
5848 // Check constraints for Objective-C object pointers types.
5849 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5851 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5852 // Two identical object pointer types are always compatible.
5855 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5856 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5857 QualType compositeType = LHSTy;
5859 // If both operands are interfaces and either operand can be
5860 // assigned to the other, use that type as the composite
5861 // type. This allows
5862 // xxx ? (A*) a : (B*) b
5863 // where B is a subclass of A.
5865 // Additionally, as for assignment, if either type is 'id'
5866 // allow silent coercion. Finally, if the types are
5867 // incompatible then make sure to use 'id' as the composite
5868 // type so the result is acceptable for sending messages to.
5870 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5871 // It could return the composite type.
5872 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5873 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5874 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5875 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5876 } else if ((LHSTy->isObjCQualifiedIdType() ||
5877 RHSTy->isObjCQualifiedIdType()) &&
5878 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5879 // Need to handle "id<xx>" explicitly.
5880 // GCC allows qualified id and any Objective-C type to devolve to
5881 // id. Currently localizing to here until clear this should be
5882 // part of ObjCQualifiedIdTypesAreCompatible.
5883 compositeType = Context.getObjCIdType();
5884 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5885 compositeType = Context.getObjCIdType();
5886 } else if (!(compositeType =
5887 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5890 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5892 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5893 QualType incompatTy = Context.getObjCIdType();
5894 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5895 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5898 // The object pointer types are compatible.
5899 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
5900 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
5901 return compositeType;
5903 // Check Objective-C object pointer types and 'void *'
5904 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5905 if (getLangOpts().ObjCAutoRefCount) {
5906 // ARC forbids the implicit conversion of object pointers to 'void *',
5907 // so these types are not compatible.
5908 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5909 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5913 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5914 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5915 QualType destPointee
5916 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5917 QualType destType = Context.getPointerType(destPointee);
5918 // Add qualifiers if necessary.
5919 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5920 // Promote to void*.
5921 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5924 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5925 if (getLangOpts().ObjCAutoRefCount) {
5926 // ARC forbids the implicit conversion of object pointers to 'void *',
5927 // so these types are not compatible.
5928 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5929 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5933 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5934 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5935 QualType destPointee
5936 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5937 QualType destType = Context.getPointerType(destPointee);
5938 // Add qualifiers if necessary.
5939 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5940 // Promote to void*.
5941 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5947 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5948 /// ParenRange in parentheses.
5949 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5950 const PartialDiagnostic &Note,
5951 SourceRange ParenRange) {
5952 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5953 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5955 Self.Diag(Loc, Note)
5956 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5957 << FixItHint::CreateInsertion(EndLoc, ")");
5959 // We can't display the parentheses, so just show the bare note.
5960 Self.Diag(Loc, Note) << ParenRange;
5964 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5965 return Opc >= BO_Mul && Opc <= BO_Shr;
5968 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5969 /// expression, either using a built-in or overloaded operator,
5970 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5972 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5974 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5975 E = E->IgnoreImpCasts();
5976 E = E->IgnoreConversionOperator();
5977 E = E->IgnoreImpCasts();
5979 // Built-in binary operator.
5980 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5981 if (IsArithmeticOp(OP->getOpcode())) {
5982 *Opcode = OP->getOpcode();
5983 *RHSExprs = OP->getRHS();
5988 // Overloaded operator.
5989 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5990 if (Call->getNumArgs() != 2)
5993 // Make sure this is really a binary operator that is safe to pass into
5994 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5995 OverloadedOperatorKind OO = Call->getOperator();
5996 if (OO < OO_Plus || OO > OO_Arrow ||
5997 OO == OO_PlusPlus || OO == OO_MinusMinus)
6000 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6001 if (IsArithmeticOp(OpKind)) {
6003 *RHSExprs = Call->getArg(1);
6011 static bool IsLogicOp(BinaryOperatorKind Opc) {
6012 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6015 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6016 /// or is a logical expression such as (x==y) which has int type, but is
6017 /// commonly interpreted as boolean.
6018 static bool ExprLooksBoolean(Expr *E) {
6019 E = E->IgnoreParenImpCasts();
6021 if (E->getType()->isBooleanType())
6023 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6024 return IsLogicOp(OP->getOpcode());
6025 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6026 return OP->getOpcode() == UO_LNot;
6031 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6032 /// and binary operator are mixed in a way that suggests the programmer assumed
6033 /// the conditional operator has higher precedence, for example:
6034 /// "int x = a + someBinaryCondition ? 1 : 2".
6035 static void DiagnoseConditionalPrecedence(Sema &Self,
6036 SourceLocation OpLoc,
6040 BinaryOperatorKind CondOpcode;
6043 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6045 if (!ExprLooksBoolean(CondRHS))
6048 // The condition is an arithmetic binary expression, with a right-
6049 // hand side that looks boolean, so warn.
6051 Self.Diag(OpLoc, diag::warn_precedence_conditional)
6052 << Condition->getSourceRange()
6053 << BinaryOperator::getOpcodeStr(CondOpcode);
6055 SuggestParentheses(Self, OpLoc,
6056 Self.PDiag(diag::note_precedence_silence)
6057 << BinaryOperator::getOpcodeStr(CondOpcode),
6058 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6060 SuggestParentheses(Self, OpLoc,
6061 Self.PDiag(diag::note_precedence_conditional_first),
6062 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6065 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
6066 /// in the case of a the GNU conditional expr extension.
6067 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6068 SourceLocation ColonLoc,
6069 Expr *CondExpr, Expr *LHSExpr,
6071 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6072 // was the condition.
6073 OpaqueValueExpr *opaqueValue = nullptr;
6074 Expr *commonExpr = nullptr;
6076 commonExpr = CondExpr;
6077 // Lower out placeholder types first. This is important so that we don't
6078 // try to capture a placeholder. This happens in few cases in C++; such
6079 // as Objective-C++'s dictionary subscripting syntax.
6080 if (commonExpr->hasPlaceholderType()) {
6081 ExprResult result = CheckPlaceholderExpr(commonExpr);
6082 if (!result.isUsable()) return ExprError();
6083 commonExpr = result.get();
6085 // We usually want to apply unary conversions *before* saving, except
6086 // in the special case of a C++ l-value conditional.
6087 if (!(getLangOpts().CPlusPlus
6088 && !commonExpr->isTypeDependent()
6089 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6090 && commonExpr->isGLValue()
6091 && commonExpr->isOrdinaryOrBitFieldObject()
6092 && RHSExpr->isOrdinaryOrBitFieldObject()
6093 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6094 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6095 if (commonRes.isInvalid())
6097 commonExpr = commonRes.get();
6100 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6101 commonExpr->getType(),
6102 commonExpr->getValueKind(),
6103 commonExpr->getObjectKind(),
6105 LHSExpr = CondExpr = opaqueValue;
6108 ExprValueKind VK = VK_RValue;
6109 ExprObjectKind OK = OK_Ordinary;
6110 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6111 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6112 VK, OK, QuestionLoc);
6113 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6117 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6121 return new (Context)
6122 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6123 RHS.get(), result, VK, OK);
6125 return new (Context) BinaryConditionalOperator(
6126 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6127 ColonLoc, result, VK, OK);
6130 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6131 // being closely modeled after the C99 spec:-). The odd characteristic of this
6132 // routine is it effectively iqnores the qualifiers on the top level pointee.
6133 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6134 // FIXME: add a couple examples in this comment.
6135 static Sema::AssignConvertType
6136 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6137 assert(LHSType.isCanonical() && "LHS not canonicalized!");
6138 assert(RHSType.isCanonical() && "RHS not canonicalized!");
6140 // get the "pointed to" type (ignoring qualifiers at the top level)
6141 const Type *lhptee, *rhptee;
6142 Qualifiers lhq, rhq;
6143 std::tie(lhptee, lhq) =
6144 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6145 std::tie(rhptee, rhq) =
6146 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6148 Sema::AssignConvertType ConvTy = Sema::Compatible;
6150 // C99 6.5.16.1p1: This following citation is common to constraints
6151 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6152 // qualifiers of the type *pointed to* by the right;
6154 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6155 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6156 lhq.compatiblyIncludesObjCLifetime(rhq)) {
6157 // Ignore lifetime for further calculation.
6158 lhq.removeObjCLifetime();
6159 rhq.removeObjCLifetime();
6162 if (!lhq.compatiblyIncludes(rhq)) {
6163 // Treat address-space mismatches as fatal. TODO: address subspaces
6164 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6165 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6167 // It's okay to add or remove GC or lifetime qualifiers when converting to
6169 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6170 .compatiblyIncludes(
6171 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6172 && (lhptee->isVoidType() || rhptee->isVoidType()))
6175 // Treat lifetime mismatches as fatal.
6176 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6177 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6179 // For GCC compatibility, other qualifier mismatches are treated
6180 // as still compatible in C.
6181 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6184 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6185 // incomplete type and the other is a pointer to a qualified or unqualified
6186 // version of void...
6187 if (lhptee->isVoidType()) {
6188 if (rhptee->isIncompleteOrObjectType())
6191 // As an extension, we allow cast to/from void* to function pointer.
6192 assert(rhptee->isFunctionType());
6193 return Sema::FunctionVoidPointer;
6196 if (rhptee->isVoidType()) {
6197 if (lhptee->isIncompleteOrObjectType())
6200 // As an extension, we allow cast to/from void* to function pointer.
6201 assert(lhptee->isFunctionType());
6202 return Sema::FunctionVoidPointer;
6205 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6206 // unqualified versions of compatible types, ...
6207 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6208 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6209 // Check if the pointee types are compatible ignoring the sign.
6210 // We explicitly check for char so that we catch "char" vs
6211 // "unsigned char" on systems where "char" is unsigned.
6212 if (lhptee->isCharType())
6213 ltrans = S.Context.UnsignedCharTy;
6214 else if (lhptee->hasSignedIntegerRepresentation())
6215 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6217 if (rhptee->isCharType())
6218 rtrans = S.Context.UnsignedCharTy;
6219 else if (rhptee->hasSignedIntegerRepresentation())
6220 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6222 if (ltrans == rtrans) {
6223 // Types are compatible ignoring the sign. Qualifier incompatibility
6224 // takes priority over sign incompatibility because the sign
6225 // warning can be disabled.
6226 if (ConvTy != Sema::Compatible)
6229 return Sema::IncompatiblePointerSign;
6232 // If we are a multi-level pointer, it's possible that our issue is simply
6233 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6234 // the eventual target type is the same and the pointers have the same
6235 // level of indirection, this must be the issue.
6236 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6238 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6239 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6240 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6242 if (lhptee == rhptee)
6243 return Sema::IncompatibleNestedPointerQualifiers;
6246 // General pointer incompatibility takes priority over qualifiers.
6247 return Sema::IncompatiblePointer;
6249 if (!S.getLangOpts().CPlusPlus &&
6250 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6251 return Sema::IncompatiblePointer;
6255 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6256 /// block pointer types are compatible or whether a block and normal pointer
6257 /// are compatible. It is more restrict than comparing two function pointer
6259 static Sema::AssignConvertType
6260 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6262 assert(LHSType.isCanonical() && "LHS not canonicalized!");
6263 assert(RHSType.isCanonical() && "RHS not canonicalized!");
6265 QualType lhptee, rhptee;
6267 // get the "pointed to" type (ignoring qualifiers at the top level)
6268 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6269 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6271 // In C++, the types have to match exactly.
6272 if (S.getLangOpts().CPlusPlus)
6273 return Sema::IncompatibleBlockPointer;
6275 Sema::AssignConvertType ConvTy = Sema::Compatible;
6277 // For blocks we enforce that qualifiers are identical.
6278 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6279 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6281 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6282 return Sema::IncompatibleBlockPointer;
6287 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6288 /// for assignment compatibility.
6289 static Sema::AssignConvertType
6290 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6292 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6293 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6295 if (LHSType->isObjCBuiltinType()) {
6296 // Class is not compatible with ObjC object pointers.
6297 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6298 !RHSType->isObjCQualifiedClassType())
6299 return Sema::IncompatiblePointer;
6300 return Sema::Compatible;
6302 if (RHSType->isObjCBuiltinType()) {
6303 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6304 !LHSType->isObjCQualifiedClassType())
6305 return Sema::IncompatiblePointer;
6306 return Sema::Compatible;
6308 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6309 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6311 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6312 // make an exception for id<P>
6313 !LHSType->isObjCQualifiedIdType())
6314 return Sema::CompatiblePointerDiscardsQualifiers;
6316 if (S.Context.typesAreCompatible(LHSType, RHSType))
6317 return Sema::Compatible;
6318 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6319 return Sema::IncompatibleObjCQualifiedId;
6320 return Sema::IncompatiblePointer;
6323 Sema::AssignConvertType
6324 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6325 QualType LHSType, QualType RHSType) {
6326 // Fake up an opaque expression. We don't actually care about what
6327 // cast operations are required, so if CheckAssignmentConstraints
6328 // adds casts to this they'll be wasted, but fortunately that doesn't
6329 // usually happen on valid code.
6330 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6331 ExprResult RHSPtr = &RHSExpr;
6332 CastKind K = CK_Invalid;
6334 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6337 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6338 /// has code to accommodate several GCC extensions when type checking
6339 /// pointers. Here are some objectionable examples that GCC considers warnings:
6343 /// struct foo *pfoo;
6345 /// pint = pshort; // warning: assignment from incompatible pointer type
6346 /// a = pint; // warning: assignment makes integer from pointer without a cast
6347 /// pint = a; // warning: assignment makes pointer from integer without a cast
6348 /// pint = pfoo; // warning: assignment from incompatible pointer type
6350 /// As a result, the code for dealing with pointers is more complex than the
6351 /// C99 spec dictates.
6353 /// Sets 'Kind' for any result kind except Incompatible.
6354 Sema::AssignConvertType
6355 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6357 QualType RHSType = RHS.get()->getType();
6358 QualType OrigLHSType = LHSType;
6360 // Get canonical types. We're not formatting these types, just comparing
6362 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6363 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6365 // Common case: no conversion required.
6366 if (LHSType == RHSType) {
6371 // If we have an atomic type, try a non-atomic assignment, then just add an
6372 // atomic qualification step.
6373 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6374 Sema::AssignConvertType result =
6375 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6376 if (result != Compatible)
6378 if (Kind != CK_NoOp)
6379 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6380 Kind = CK_NonAtomicToAtomic;
6384 // If the left-hand side is a reference type, then we are in a
6385 // (rare!) case where we've allowed the use of references in C,
6386 // e.g., as a parameter type in a built-in function. In this case,
6387 // just make sure that the type referenced is compatible with the
6388 // right-hand side type. The caller is responsible for adjusting
6389 // LHSType so that the resulting expression does not have reference
6391 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6392 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6393 Kind = CK_LValueBitCast;
6396 return Incompatible;
6399 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6400 // to the same ExtVector type.
6401 if (LHSType->isExtVectorType()) {
6402 if (RHSType->isExtVectorType())
6403 return Incompatible;
6404 if (RHSType->isArithmeticType()) {
6405 // CK_VectorSplat does T -> vector T, so first cast to the
6407 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6408 if (elType != RHSType) {
6409 Kind = PrepareScalarCast(RHS, elType);
6410 RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6412 Kind = CK_VectorSplat;
6417 // Conversions to or from vector type.
6418 if (LHSType->isVectorType() || RHSType->isVectorType()) {
6419 if (LHSType->isVectorType() && RHSType->isVectorType()) {
6420 // Allow assignments of an AltiVec vector type to an equivalent GCC
6421 // vector type and vice versa
6422 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6427 // If we are allowing lax vector conversions, and LHS and RHS are both
6428 // vectors, the total size only needs to be the same. This is a bitcast;
6429 // no bits are changed but the result type is different.
6430 if (isLaxVectorConversion(RHSType, LHSType)) {
6432 return IncompatibleVectors;
6435 return Incompatible;
6438 // Arithmetic conversions.
6439 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6440 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6441 Kind = PrepareScalarCast(RHS, LHSType);
6445 // Conversions to normal pointers.
6446 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6448 if (isa<PointerType>(RHSType)) {
6450 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6454 if (RHSType->isIntegerType()) {
6455 Kind = CK_IntegralToPointer; // FIXME: null?
6456 return IntToPointer;
6459 // C pointers are not compatible with ObjC object pointers,
6460 // with two exceptions:
6461 if (isa<ObjCObjectPointerType>(RHSType)) {
6462 // - conversions to void*
6463 if (LHSPointer->getPointeeType()->isVoidType()) {
6468 // - conversions from 'Class' to the redefinition type
6469 if (RHSType->isObjCClassType() &&
6470 Context.hasSameType(LHSType,
6471 Context.getObjCClassRedefinitionType())) {
6477 return IncompatiblePointer;
6481 if (RHSType->getAs<BlockPointerType>()) {
6482 if (LHSPointer->getPointeeType()->isVoidType()) {
6488 return Incompatible;
6491 // Conversions to block pointers.
6492 if (isa<BlockPointerType>(LHSType)) {
6494 if (RHSType->isBlockPointerType()) {
6496 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6499 // int or null -> T^
6500 if (RHSType->isIntegerType()) {
6501 Kind = CK_IntegralToPointer; // FIXME: null
6502 return IntToBlockPointer;
6506 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6507 Kind = CK_AnyPointerToBlockPointerCast;
6512 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6513 if (RHSPT->getPointeeType()->isVoidType()) {
6514 Kind = CK_AnyPointerToBlockPointerCast;
6518 return Incompatible;
6521 // Conversions to Objective-C pointers.
6522 if (isa<ObjCObjectPointerType>(LHSType)) {
6524 if (RHSType->isObjCObjectPointerType()) {
6526 Sema::AssignConvertType result =
6527 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6528 if (getLangOpts().ObjCAutoRefCount &&
6529 result == Compatible &&
6530 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6531 result = IncompatibleObjCWeakRef;
6535 // int or null -> A*
6536 if (RHSType->isIntegerType()) {
6537 Kind = CK_IntegralToPointer; // FIXME: null
6538 return IntToPointer;
6541 // In general, C pointers are not compatible with ObjC object pointers,
6542 // with two exceptions:
6543 if (isa<PointerType>(RHSType)) {
6544 Kind = CK_CPointerToObjCPointerCast;
6546 // - conversions from 'void*'
6547 if (RHSType->isVoidPointerType()) {
6551 // - conversions to 'Class' from its redefinition type
6552 if (LHSType->isObjCClassType() &&
6553 Context.hasSameType(RHSType,
6554 Context.getObjCClassRedefinitionType())) {
6558 return IncompatiblePointer;
6561 // Only under strict condition T^ is compatible with an Objective-C pointer.
6562 if (RHSType->isBlockPointerType() &&
6563 isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6564 maybeExtendBlockObject(*this, RHS);
6565 Kind = CK_BlockPointerToObjCPointerCast;
6569 return Incompatible;
6572 // Conversions from pointers that are not covered by the above.
6573 if (isa<PointerType>(RHSType)) {
6575 if (LHSType == Context.BoolTy) {
6576 Kind = CK_PointerToBoolean;
6581 if (LHSType->isIntegerType()) {
6582 Kind = CK_PointerToIntegral;
6583 return PointerToInt;
6586 return Incompatible;
6589 // Conversions from Objective-C pointers that are not covered by the above.
6590 if (isa<ObjCObjectPointerType>(RHSType)) {
6592 if (LHSType == Context.BoolTy) {
6593 Kind = CK_PointerToBoolean;
6598 if (LHSType->isIntegerType()) {
6599 Kind = CK_PointerToIntegral;
6600 return PointerToInt;
6603 return Incompatible;
6606 // struct A -> struct B
6607 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6608 if (Context.typesAreCompatible(LHSType, RHSType)) {
6614 return Incompatible;
6617 /// \brief Constructs a transparent union from an expression that is
6618 /// used to initialize the transparent union.
6619 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6620 ExprResult &EResult, QualType UnionType,
6622 // Build an initializer list that designates the appropriate member
6623 // of the transparent union.
6624 Expr *E = EResult.get();
6625 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6626 E, SourceLocation());
6627 Initializer->setType(UnionType);
6628 Initializer->setInitializedFieldInUnion(Field);
6630 // Build a compound literal constructing a value of the transparent
6631 // union type from this initializer list.
6632 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6633 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6634 VK_RValue, Initializer, false);
6637 Sema::AssignConvertType
6638 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6640 QualType RHSType = RHS.get()->getType();
6642 // If the ArgType is a Union type, we want to handle a potential
6643 // transparent_union GCC extension.
6644 const RecordType *UT = ArgType->getAsUnionType();
6645 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6646 return Incompatible;
6648 // The field to initialize within the transparent union.
6649 RecordDecl *UD = UT->getDecl();
6650 FieldDecl *InitField = nullptr;
6651 // It's compatible if the expression matches any of the fields.
6652 for (auto *it : UD->fields()) {
6653 if (it->getType()->isPointerType()) {
6654 // If the transparent union contains a pointer type, we allow:
6656 // 2) null pointer constant
6657 if (RHSType->isPointerType())
6658 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6659 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
6664 if (RHS.get()->isNullPointerConstant(Context,
6665 Expr::NPC_ValueDependentIsNull)) {
6666 RHS = ImpCastExprToType(RHS.get(), it->getType(),
6673 CastKind Kind = CK_Invalid;
6674 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6676 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
6683 return Incompatible;
6685 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6689 Sema::AssignConvertType
6690 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6692 bool DiagnoseCFAudited) {
6693 if (getLangOpts().CPlusPlus) {
6694 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6695 // C++ 5.17p3: If the left operand is not of class type, the
6696 // expression is implicitly converted (C++ 4) to the
6697 // cv-unqualified type of the left operand.
6700 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6703 ImplicitConversionSequence ICS =
6704 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6705 /*SuppressUserConversions=*/false,
6706 /*AllowExplicit=*/false,
6707 /*InOverloadResolution=*/false,
6709 /*AllowObjCWritebackConversion=*/false);
6710 if (ICS.isFailure())
6711 return Incompatible;
6712 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6715 if (Res.isInvalid())
6716 return Incompatible;
6717 Sema::AssignConvertType result = Compatible;
6718 if (getLangOpts().ObjCAutoRefCount &&
6719 !CheckObjCARCUnavailableWeakConversion(LHSType,
6720 RHS.get()->getType()))
6721 result = IncompatibleObjCWeakRef;
6726 // FIXME: Currently, we fall through and treat C++ classes like C
6728 // FIXME: We also fall through for atomics; not sure what should
6729 // happen there, though.
6732 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6733 // a null pointer constant.
6734 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6735 LHSType->isBlockPointerType()) &&
6736 RHS.get()->isNullPointerConstant(Context,
6737 Expr::NPC_ValueDependentIsNull)) {
6740 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6741 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
6745 // This check seems unnatural, however it is necessary to ensure the proper
6746 // conversion of functions/arrays. If the conversion were done for all
6747 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6748 // expressions that suppress this implicit conversion (&, sizeof).
6750 // Suppress this for references: C++ 8.5.3p5.
6751 if (!LHSType->isReferenceType()) {
6752 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6753 if (RHS.isInvalid())
6754 return Incompatible;
6757 CastKind Kind = CK_Invalid;
6758 Sema::AssignConvertType result =
6759 CheckAssignmentConstraints(LHSType, RHS, Kind);
6761 // C99 6.5.16.1p2: The value of the right operand is converted to the
6762 // type of the assignment expression.
6763 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6764 // so that we can use references in built-in functions even in C.
6765 // The getNonReferenceType() call makes sure that the resulting expression
6766 // does not have reference type.
6767 if (result != Incompatible && RHS.get()->getType() != LHSType) {
6768 QualType Ty = LHSType.getNonLValueExprType(Context);
6769 Expr *E = RHS.get();
6770 if (getLangOpts().ObjCAutoRefCount)
6771 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6773 if (getLangOpts().ObjC1 &&
6774 (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6775 LHSType, E->getType(), E) ||
6776 ConversionToObjCStringLiteralCheck(LHSType, E))) {
6781 RHS = ImpCastExprToType(E, Ty, Kind);
6786 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6788 Diag(Loc, diag::err_typecheck_invalid_operands)
6789 << LHS.get()->getType() << RHS.get()->getType()
6790 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6794 /// Try to convert a value of non-vector type to a vector type by converting
6795 /// the type to the element type of the vector and then performing a splat.
6796 /// If the language is OpenCL, we only use conversions that promote scalar
6797 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
6800 /// \param scalar - if non-null, actually perform the conversions
6801 /// \return true if the operation fails (but without diagnosing the failure)
6802 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
6804 QualType vectorEltTy,
6805 QualType vectorTy) {
6806 // The conversion to apply to the scalar before splatting it,
6808 CastKind scalarCast = CK_Invalid;
6810 if (vectorEltTy->isIntegralType(S.Context)) {
6811 if (!scalarTy->isIntegralType(S.Context))
6813 if (S.getLangOpts().OpenCL &&
6814 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
6816 scalarCast = CK_IntegralCast;
6817 } else if (vectorEltTy->isRealFloatingType()) {
6818 if (scalarTy->isRealFloatingType()) {
6819 if (S.getLangOpts().OpenCL &&
6820 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
6822 scalarCast = CK_FloatingCast;
6824 else if (scalarTy->isIntegralType(S.Context))
6825 scalarCast = CK_IntegralToFloating;
6832 // Adjust scalar if desired.
6834 if (scalarCast != CK_Invalid)
6835 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
6836 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
6841 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6842 SourceLocation Loc, bool IsCompAssign) {
6843 if (!IsCompAssign) {
6844 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6845 if (LHS.isInvalid())
6848 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6849 if (RHS.isInvalid())
6852 // For conversion purposes, we ignore any qualifiers.
6853 // For example, "const float" and "float" are equivalent.
6854 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6855 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6857 // If the vector types are identical, return.
6858 if (Context.hasSameType(LHSType, RHSType))
6861 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6862 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6863 assert(LHSVecType || RHSVecType);
6865 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6866 if (LHSVecType && RHSVecType &&
6867 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6868 if (isa<ExtVectorType>(LHSVecType)) {
6869 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
6874 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
6878 // If there's an ext-vector type and a scalar, try to convert the scalar to
6879 // the vector element type and splat.
6880 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6881 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
6882 LHSVecType->getElementType(), LHSType))
6885 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6886 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
6887 LHSType, RHSVecType->getElementType(),
6892 // If we're allowing lax vector conversions, only the total (data) size
6893 // needs to be the same.
6894 // FIXME: Should we really be allowing this?
6895 // FIXME: We really just pick the LHS type arbitrarily?
6896 if (isLaxVectorConversion(RHSType, LHSType)) {
6897 QualType resultType = LHSType;
6898 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
6902 // Okay, the expression is invalid.
6904 // If there's a non-vector, non-real operand, diagnose that.
6905 if ((!RHSVecType && !RHSType->isRealType()) ||
6906 (!LHSVecType && !LHSType->isRealType())) {
6907 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6908 << LHSType << RHSType
6909 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6913 // Otherwise, use the generic diagnostic.
6914 Diag(Loc, diag::err_typecheck_vector_not_convertable)
6915 << LHSType << RHSType
6916 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6920 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6921 // expression. These are mainly cases where the null pointer is used as an
6922 // integer instead of a pointer.
6923 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6924 SourceLocation Loc, bool IsCompare) {
6925 // The canonical way to check for a GNU null is with isNullPointerConstant,
6926 // but we use a bit of a hack here for speed; this is a relatively
6927 // hot path, and isNullPointerConstant is slow.
6928 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6929 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6931 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6933 // Avoid analyzing cases where the result will either be invalid (and
6934 // diagnosed as such) or entirely valid and not something to warn about.
6935 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6936 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6939 // Comparison operations would not make sense with a null pointer no matter
6940 // what the other expression is.
6942 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6943 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6944 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6948 // The rest of the operations only make sense with a null pointer
6949 // if the other expression is a pointer.
6950 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6951 NonNullType->canDecayToPointerType())
6954 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6955 << LHSNull /* LHS is NULL */ << NonNullType
6956 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6959 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6961 bool IsCompAssign, bool IsDiv) {
6962 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6964 if (LHS.get()->getType()->isVectorType() ||
6965 RHS.get()->getType()->isVectorType())
6966 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6968 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6969 if (LHS.isInvalid() || RHS.isInvalid())
6973 if (compType.isNull() || !compType->isArithmeticType())
6974 return InvalidOperands(Loc, LHS, RHS);
6976 // Check for division by zero.
6977 llvm::APSInt RHSValue;
6978 if (IsDiv && !RHS.get()->isValueDependent() &&
6979 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6980 DiagRuntimeBehavior(Loc, RHS.get(),
6981 PDiag(diag::warn_division_by_zero)
6982 << RHS.get()->getSourceRange());
6987 QualType Sema::CheckRemainderOperands(
6988 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6989 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6991 if (LHS.get()->getType()->isVectorType() ||
6992 RHS.get()->getType()->isVectorType()) {
6993 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6994 RHS.get()->getType()->hasIntegerRepresentation())
6995 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6996 return InvalidOperands(Loc, LHS, RHS);
6999 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7000 if (LHS.isInvalid() || RHS.isInvalid())
7003 if (compType.isNull() || !compType->isIntegerType())
7004 return InvalidOperands(Loc, LHS, RHS);
7006 // Check for remainder by zero.
7007 llvm::APSInt RHSValue;
7008 if (!RHS.get()->isValueDependent() &&
7009 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7010 DiagRuntimeBehavior(Loc, RHS.get(),
7011 PDiag(diag::warn_remainder_by_zero)
7012 << RHS.get()->getSourceRange());
7017 /// \brief Diagnose invalid arithmetic on two void pointers.
7018 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7019 Expr *LHSExpr, Expr *RHSExpr) {
7020 S.Diag(Loc, S.getLangOpts().CPlusPlus
7021 ? diag::err_typecheck_pointer_arith_void_type
7022 : diag::ext_gnu_void_ptr)
7023 << 1 /* two pointers */ << LHSExpr->getSourceRange()
7024 << RHSExpr->getSourceRange();
7027 /// \brief Diagnose invalid arithmetic on a void pointer.
7028 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7030 S.Diag(Loc, S.getLangOpts().CPlusPlus
7031 ? diag::err_typecheck_pointer_arith_void_type
7032 : diag::ext_gnu_void_ptr)
7033 << 0 /* one pointer */ << Pointer->getSourceRange();
7036 /// \brief Diagnose invalid arithmetic on two function pointers.
7037 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7038 Expr *LHS, Expr *RHS) {
7039 assert(LHS->getType()->isAnyPointerType());
7040 assert(RHS->getType()->isAnyPointerType());
7041 S.Diag(Loc, S.getLangOpts().CPlusPlus
7042 ? diag::err_typecheck_pointer_arith_function_type
7043 : diag::ext_gnu_ptr_func_arith)
7044 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7045 // We only show the second type if it differs from the first.
7046 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7048 << RHS->getType()->getPointeeType()
7049 << LHS->getSourceRange() << RHS->getSourceRange();
7052 /// \brief Diagnose invalid arithmetic on a function pointer.
7053 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7055 assert(Pointer->getType()->isAnyPointerType());
7056 S.Diag(Loc, S.getLangOpts().CPlusPlus
7057 ? diag::err_typecheck_pointer_arith_function_type
7058 : diag::ext_gnu_ptr_func_arith)
7059 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7060 << 0 /* one pointer, so only one type */
7061 << Pointer->getSourceRange();
7064 /// \brief Emit error if Operand is incomplete pointer type
7066 /// \returns True if pointer has incomplete type
7067 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7069 assert(Operand->getType()->isAnyPointerType() &&
7070 !Operand->getType()->isDependentType());
7071 QualType PointeeTy = Operand->getType()->getPointeeType();
7072 return S.RequireCompleteType(Loc, PointeeTy,
7073 diag::err_typecheck_arithmetic_incomplete_type,
7074 PointeeTy, Operand->getSourceRange());
7077 /// \brief Check the validity of an arithmetic pointer operand.
7079 /// If the operand has pointer type, this code will check for pointer types
7080 /// which are invalid in arithmetic operations. These will be diagnosed
7081 /// appropriately, including whether or not the use is supported as an
7084 /// \returns True when the operand is valid to use (even if as an extension).
7085 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7087 if (!Operand->getType()->isAnyPointerType()) return true;
7089 QualType PointeeTy = Operand->getType()->getPointeeType();
7090 if (PointeeTy->isVoidType()) {
7091 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7092 return !S.getLangOpts().CPlusPlus;
7094 if (PointeeTy->isFunctionType()) {
7095 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7096 return !S.getLangOpts().CPlusPlus;
7099 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7104 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7107 /// This routine will diagnose any invalid arithmetic on pointer operands much
7108 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7109 /// for emitting a single diagnostic even for operations where both LHS and RHS
7110 /// are (potentially problematic) pointers.
7112 /// \returns True when the operand is valid to use (even if as an extension).
7113 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7114 Expr *LHSExpr, Expr *RHSExpr) {
7115 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7116 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7117 if (!isLHSPointer && !isRHSPointer) return true;
7119 QualType LHSPointeeTy, RHSPointeeTy;
7120 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7121 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7123 // Check for arithmetic on pointers to incomplete types.
7124 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7125 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7126 if (isLHSVoidPtr || isRHSVoidPtr) {
7127 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7128 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7129 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7131 return !S.getLangOpts().CPlusPlus;
7134 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7135 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7136 if (isLHSFuncPtr || isRHSFuncPtr) {
7137 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7138 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7140 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7142 return !S.getLangOpts().CPlusPlus;
7145 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7147 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7153 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7155 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7156 Expr *LHSExpr, Expr *RHSExpr) {
7157 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7158 Expr* IndexExpr = RHSExpr;
7160 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7161 IndexExpr = LHSExpr;
7164 bool IsStringPlusInt = StrExpr &&
7165 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7166 if (!IsStringPlusInt)
7170 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7171 unsigned StrLenWithNull = StrExpr->getLength() + 1;
7172 if (index.isNonNegative() &&
7173 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7174 index.isUnsigned()))
7178 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7179 Self.Diag(OpLoc, diag::warn_string_plus_int)
7180 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7182 // Only print a fixit for "str" + int, not for int + "str".
7183 if (IndexExpr == RHSExpr) {
7184 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7185 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7186 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7187 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7188 << FixItHint::CreateInsertion(EndLoc, "]");
7190 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7193 /// \brief Emit a warning when adding a char literal to a string.
7194 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7195 Expr *LHSExpr, Expr *RHSExpr) {
7196 const DeclRefExpr *StringRefExpr =
7197 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7198 const CharacterLiteral *CharExpr =
7199 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7200 if (!StringRefExpr) {
7201 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7202 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7205 if (!CharExpr || !StringRefExpr)
7208 const QualType StringType = StringRefExpr->getType();
7210 // Return if not a PointerType.
7211 if (!StringType->isAnyPointerType())
7214 // Return if not a CharacterType.
7215 if (!StringType->getPointeeType()->isAnyCharacterType())
7218 ASTContext &Ctx = Self.getASTContext();
7219 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7221 const QualType CharType = CharExpr->getType();
7222 if (!CharType->isAnyCharacterType() &&
7223 CharType->isIntegerType() &&
7224 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7225 Self.Diag(OpLoc, diag::warn_string_plus_char)
7226 << DiagRange << Ctx.CharTy;
7228 Self.Diag(OpLoc, diag::warn_string_plus_char)
7229 << DiagRange << CharExpr->getType();
7232 // Only print a fixit for str + char, not for char + str.
7233 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7234 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7235 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7236 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7237 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7238 << FixItHint::CreateInsertion(EndLoc, "]");
7240 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7244 /// \brief Emit error when two pointers are incompatible.
7245 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7246 Expr *LHSExpr, Expr *RHSExpr) {
7247 assert(LHSExpr->getType()->isAnyPointerType());
7248 assert(RHSExpr->getType()->isAnyPointerType());
7249 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7250 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7251 << RHSExpr->getSourceRange();
7254 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7255 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7256 QualType* CompLHSTy) {
7257 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7259 if (LHS.get()->getType()->isVectorType() ||
7260 RHS.get()->getType()->isVectorType()) {
7261 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7262 if (CompLHSTy) *CompLHSTy = compType;
7266 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7267 if (LHS.isInvalid() || RHS.isInvalid())
7270 // Diagnose "string literal" '+' int and string '+' "char literal".
7271 if (Opc == BO_Add) {
7272 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7273 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7276 // handle the common case first (both operands are arithmetic).
7277 if (!compType.isNull() && compType->isArithmeticType()) {
7278 if (CompLHSTy) *CompLHSTy = compType;
7282 // Type-checking. Ultimately the pointer's going to be in PExp;
7283 // note that we bias towards the LHS being the pointer.
7284 Expr *PExp = LHS.get(), *IExp = RHS.get();
7287 if (PExp->getType()->isPointerType()) {
7288 isObjCPointer = false;
7289 } else if (PExp->getType()->isObjCObjectPointerType()) {
7290 isObjCPointer = true;
7292 std::swap(PExp, IExp);
7293 if (PExp->getType()->isPointerType()) {
7294 isObjCPointer = false;
7295 } else if (PExp->getType()->isObjCObjectPointerType()) {
7296 isObjCPointer = true;
7298 return InvalidOperands(Loc, LHS, RHS);
7301 assert(PExp->getType()->isAnyPointerType());
7303 if (!IExp->getType()->isIntegerType())
7304 return InvalidOperands(Loc, LHS, RHS);
7306 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7309 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7312 // Check array bounds for pointer arithemtic
7313 CheckArrayAccess(PExp, IExp);
7316 QualType LHSTy = Context.isPromotableBitField(LHS.get());
7317 if (LHSTy.isNull()) {
7318 LHSTy = LHS.get()->getType();
7319 if (LHSTy->isPromotableIntegerType())
7320 LHSTy = Context.getPromotedIntegerType(LHSTy);
7325 return PExp->getType();
7329 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7331 QualType* CompLHSTy) {
7332 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7334 if (LHS.get()->getType()->isVectorType() ||
7335 RHS.get()->getType()->isVectorType()) {
7336 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7337 if (CompLHSTy) *CompLHSTy = compType;
7341 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7342 if (LHS.isInvalid() || RHS.isInvalid())
7345 // Enforce type constraints: C99 6.5.6p3.
7347 // Handle the common case first (both operands are arithmetic).
7348 if (!compType.isNull() && compType->isArithmeticType()) {
7349 if (CompLHSTy) *CompLHSTy = compType;
7353 // Either ptr - int or ptr - ptr.
7354 if (LHS.get()->getType()->isAnyPointerType()) {
7355 QualType lpointee = LHS.get()->getType()->getPointeeType();
7357 // Diagnose bad cases where we step over interface counts.
7358 if (LHS.get()->getType()->isObjCObjectPointerType() &&
7359 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7362 // The result type of a pointer-int computation is the pointer type.
7363 if (RHS.get()->getType()->isIntegerType()) {
7364 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7367 // Check array bounds for pointer arithemtic
7368 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7369 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7371 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7372 return LHS.get()->getType();
7375 // Handle pointer-pointer subtractions.
7376 if (const PointerType *RHSPTy
7377 = RHS.get()->getType()->getAs<PointerType>()) {
7378 QualType rpointee = RHSPTy->getPointeeType();
7380 if (getLangOpts().CPlusPlus) {
7381 // Pointee types must be the same: C++ [expr.add]
7382 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7383 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7386 // Pointee types must be compatible C99 6.5.6p3
7387 if (!Context.typesAreCompatible(
7388 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7389 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7390 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7395 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7396 LHS.get(), RHS.get()))
7399 // The pointee type may have zero size. As an extension, a structure or
7400 // union may have zero size or an array may have zero length. In this
7401 // case subtraction does not make sense.
7402 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7403 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7404 if (ElementSize.isZero()) {
7405 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7406 << rpointee.getUnqualifiedType()
7407 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7411 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7412 return Context.getPointerDiffType();
7416 return InvalidOperands(Loc, LHS, RHS);
7419 static bool isScopedEnumerationType(QualType T) {
7420 if (const EnumType *ET = dyn_cast<EnumType>(T))
7421 return ET->getDecl()->isScoped();
7425 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7426 SourceLocation Loc, unsigned Opc,
7428 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7429 // so skip remaining warnings as we don't want to modify values within Sema.
7430 if (S.getLangOpts().OpenCL)
7434 // Check right/shifter operand
7435 if (RHS.get()->isValueDependent() ||
7436 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7439 if (Right.isNegative()) {
7440 S.DiagRuntimeBehavior(Loc, RHS.get(),
7441 S.PDiag(diag::warn_shift_negative)
7442 << RHS.get()->getSourceRange());
7445 llvm::APInt LeftBits(Right.getBitWidth(),
7446 S.Context.getTypeSize(LHS.get()->getType()));
7447 if (Right.uge(LeftBits)) {
7448 S.DiagRuntimeBehavior(Loc, RHS.get(),
7449 S.PDiag(diag::warn_shift_gt_typewidth)
7450 << RHS.get()->getSourceRange());
7456 // When left shifting an ICE which is signed, we can check for overflow which
7457 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7458 // integers have defined behavior modulo one more than the maximum value
7459 // representable in the result type, so never warn for those.
7461 if (LHS.get()->isValueDependent() ||
7462 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7463 LHSType->hasUnsignedIntegerRepresentation())
7465 llvm::APInt ResultBits =
7466 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7467 if (LeftBits.uge(ResultBits))
7469 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7470 Result = Result.shl(Right);
7472 // Print the bit representation of the signed integer as an unsigned
7473 // hexadecimal number.
7474 SmallString<40> HexResult;
7475 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7477 // If we are only missing a sign bit, this is less likely to result in actual
7478 // bugs -- if the result is cast back to an unsigned type, it will have the
7479 // expected value. Thus we place this behind a different warning that can be
7480 // turned off separately if needed.
7481 if (LeftBits == ResultBits - 1) {
7482 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7483 << HexResult.str() << LHSType
7484 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7488 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7489 << HexResult.str() << Result.getMinSignedBits() << LHSType
7490 << Left.getBitWidth() << LHS.get()->getSourceRange()
7491 << RHS.get()->getSourceRange();
7495 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7496 SourceLocation Loc, unsigned Opc,
7497 bool IsCompAssign) {
7498 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7500 // Vector shifts promote their scalar inputs to vector type.
7501 if (LHS.get()->getType()->isVectorType() ||
7502 RHS.get()->getType()->isVectorType())
7503 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7505 // Shifts don't perform usual arithmetic conversions, they just do integer
7506 // promotions on each operand. C99 6.5.7p3
7508 // For the LHS, do usual unary conversions, but then reset them away
7509 // if this is a compound assignment.
7510 ExprResult OldLHS = LHS;
7511 LHS = UsualUnaryConversions(LHS.get());
7512 if (LHS.isInvalid())
7514 QualType LHSType = LHS.get()->getType();
7515 if (IsCompAssign) LHS = OldLHS;
7517 // The RHS is simpler.
7518 RHS = UsualUnaryConversions(RHS.get());
7519 if (RHS.isInvalid())
7521 QualType RHSType = RHS.get()->getType();
7523 // C99 6.5.7p2: Each of the operands shall have integer type.
7524 if (!LHSType->hasIntegerRepresentation() ||
7525 !RHSType->hasIntegerRepresentation())
7526 return InvalidOperands(Loc, LHS, RHS);
7528 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7529 // hasIntegerRepresentation() above instead of this.
7530 if (isScopedEnumerationType(LHSType) ||
7531 isScopedEnumerationType(RHSType)) {
7532 return InvalidOperands(Loc, LHS, RHS);
7534 // Sanity-check shift operands
7535 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7537 // "The type of the result is that of the promoted left operand."
7541 static bool IsWithinTemplateSpecialization(Decl *D) {
7542 if (DeclContext *DC = D->getDeclContext()) {
7543 if (isa<ClassTemplateSpecializationDecl>(DC))
7545 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7546 return FD->isFunctionTemplateSpecialization();
7551 /// If two different enums are compared, raise a warning.
7552 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7554 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7555 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7557 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7560 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7564 // Ignore anonymous enums.
7565 if (!LHSEnumType->getDecl()->getIdentifier())
7567 if (!RHSEnumType->getDecl()->getIdentifier())
7570 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7573 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7574 << LHSStrippedType << RHSStrippedType
7575 << LHS->getSourceRange() << RHS->getSourceRange();
7578 /// \brief Diagnose bad pointer comparisons.
7579 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7580 ExprResult &LHS, ExprResult &RHS,
7582 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7583 : diag::ext_typecheck_comparison_of_distinct_pointers)
7584 << LHS.get()->getType() << RHS.get()->getType()
7585 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7588 /// \brief Returns false if the pointers are converted to a composite type,
7590 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7591 ExprResult &LHS, ExprResult &RHS) {
7592 // C++ [expr.rel]p2:
7593 // [...] Pointer conversions (4.10) and qualification
7594 // conversions (4.4) are performed on pointer operands (or on
7595 // a pointer operand and a null pointer constant) to bring
7596 // them to their composite pointer type. [...]
7598 // C++ [expr.eq]p1 uses the same notion for (in)equality
7599 // comparisons of pointers.
7602 // In addition, pointers to members can be compared, or a pointer to
7603 // member and a null pointer constant. Pointer to member conversions
7604 // (4.11) and qualification conversions (4.4) are performed to bring
7605 // them to a common type. If one operand is a null pointer constant,
7606 // the common type is the type of the other operand. Otherwise, the
7607 // common type is a pointer to member type similar (4.4) to the type
7608 // of one of the operands, with a cv-qualification signature (4.4)
7609 // that is the union of the cv-qualification signatures of the operand
7612 QualType LHSType = LHS.get()->getType();
7613 QualType RHSType = RHS.get()->getType();
7614 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7615 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7617 bool NonStandardCompositeType = false;
7618 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
7619 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7621 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7625 if (NonStandardCompositeType)
7626 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7627 << LHSType << RHSType << T << LHS.get()->getSourceRange()
7628 << RHS.get()->getSourceRange();
7630 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
7631 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
7635 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7639 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7640 : diag::ext_typecheck_comparison_of_fptr_to_void)
7641 << LHS.get()->getType() << RHS.get()->getType()
7642 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7645 static bool isObjCObjectLiteral(ExprResult &E) {
7646 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7647 case Stmt::ObjCArrayLiteralClass:
7648 case Stmt::ObjCDictionaryLiteralClass:
7649 case Stmt::ObjCStringLiteralClass:
7650 case Stmt::ObjCBoxedExprClass:
7653 // Note that ObjCBoolLiteral is NOT an object literal!
7658 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7659 const ObjCObjectPointerType *Type =
7660 LHS->getType()->getAs<ObjCObjectPointerType>();
7662 // If this is not actually an Objective-C object, bail out.
7666 // Get the LHS object's interface type.
7667 QualType InterfaceType = Type->getPointeeType();
7668 if (const ObjCObjectType *iQFaceTy =
7669 InterfaceType->getAsObjCQualifiedInterfaceType())
7670 InterfaceType = iQFaceTy->getBaseType();
7672 // If the RHS isn't an Objective-C object, bail out.
7673 if (!RHS->getType()->isObjCObjectPointerType())
7676 // Try to find the -isEqual: method.
7677 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7678 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7682 if (Type->isObjCIdType()) {
7683 // For 'id', just check the global pool.
7684 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7685 /*receiverId=*/true,
7689 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7697 QualType T = Method->parameters()[0]->getType();
7698 if (!T->isObjCObjectPointerType())
7701 QualType R = Method->getReturnType();
7702 if (!R->isScalarType())
7708 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7709 FromE = FromE->IgnoreParenImpCasts();
7710 switch (FromE->getStmtClass()) {
7713 case Stmt::ObjCStringLiteralClass:
7716 case Stmt::ObjCArrayLiteralClass:
7719 case Stmt::ObjCDictionaryLiteralClass:
7720 // "dictionary literal"
7721 return LK_Dictionary;
7722 case Stmt::BlockExprClass:
7724 case Stmt::ObjCBoxedExprClass: {
7725 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7726 switch (Inner->getStmtClass()) {
7727 case Stmt::IntegerLiteralClass:
7728 case Stmt::FloatingLiteralClass:
7729 case Stmt::CharacterLiteralClass:
7730 case Stmt::ObjCBoolLiteralExprClass:
7731 case Stmt::CXXBoolLiteralExprClass:
7732 // "numeric literal"
7734 case Stmt::ImplicitCastExprClass: {
7735 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7736 // Boolean literals can be represented by implicit casts.
7737 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7750 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7751 ExprResult &LHS, ExprResult &RHS,
7752 BinaryOperator::Opcode Opc){
7755 if (isObjCObjectLiteral(LHS)) {
7756 Literal = LHS.get();
7759 Literal = RHS.get();
7763 // Don't warn on comparisons against nil.
7764 Other = Other->IgnoreParenCasts();
7765 if (Other->isNullPointerConstant(S.getASTContext(),
7766 Expr::NPC_ValueDependentIsNotNull))
7769 // This should be kept in sync with warn_objc_literal_comparison.
7770 // LK_String should always be after the other literals, since it has its own
7772 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7773 assert(LiteralKind != Sema::LK_Block);
7774 if (LiteralKind == Sema::LK_None) {
7775 llvm_unreachable("Unknown Objective-C object literal kind");
7778 if (LiteralKind == Sema::LK_String)
7779 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7780 << Literal->getSourceRange();
7782 S.Diag(Loc, diag::warn_objc_literal_comparison)
7783 << LiteralKind << Literal->getSourceRange();
7785 if (BinaryOperator::isEqualityOp(Opc) &&
7786 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7787 SourceLocation Start = LHS.get()->getLocStart();
7788 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7789 CharSourceRange OpRange =
7790 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7792 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7793 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7794 << FixItHint::CreateReplacement(OpRange, " isEqual:")
7795 << FixItHint::CreateInsertion(End, "]");
7799 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7802 unsigned OpaqueOpc) {
7803 // This checking requires bools.
7804 if (!S.getLangOpts().Bool) return;
7806 // Check that left hand side is !something.
7807 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7808 if (!UO || UO->getOpcode() != UO_LNot) return;
7810 // Only check if the right hand side is non-bool arithmetic type.
7811 if (RHS.get()->getType()->isBooleanType()) return;
7813 // Make sure that the something in !something is not bool.
7814 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7815 if (SubExpr->getType()->isBooleanType()) return;
7818 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7821 // First note suggest !(x < y)
7822 SourceLocation FirstOpen = SubExpr->getLocStart();
7823 SourceLocation FirstClose = RHS.get()->getLocEnd();
7824 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7825 if (FirstClose.isInvalid())
7826 FirstOpen = SourceLocation();
7827 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7828 << FixItHint::CreateInsertion(FirstOpen, "(")
7829 << FixItHint::CreateInsertion(FirstClose, ")");
7831 // Second note suggests (!x) < y
7832 SourceLocation SecondOpen = LHS.get()->getLocStart();
7833 SourceLocation SecondClose = LHS.get()->getLocEnd();
7834 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7835 if (SecondClose.isInvalid())
7836 SecondOpen = SourceLocation();
7837 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7838 << FixItHint::CreateInsertion(SecondOpen, "(")
7839 << FixItHint::CreateInsertion(SecondClose, ")");
7842 // Get the decl for a simple expression: a reference to a variable,
7843 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7844 static ValueDecl *getCompareDecl(Expr *E) {
7845 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7846 return DR->getDecl();
7847 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7848 if (Ivar->isFreeIvar())
7849 return Ivar->getDecl();
7851 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7852 if (Mem->isImplicitAccess())
7853 return Mem->getMemberDecl();
7858 // C99 6.5.8, C++ [expr.rel]
7859 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7860 SourceLocation Loc, unsigned OpaqueOpc,
7861 bool IsRelational) {
7862 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7864 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7866 // Handle vector comparisons separately.
7867 if (LHS.get()->getType()->isVectorType() ||
7868 RHS.get()->getType()->isVectorType())
7869 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7871 QualType LHSType = LHS.get()->getType();
7872 QualType RHSType = RHS.get()->getType();
7874 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7875 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7877 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7878 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7880 if (!LHSType->hasFloatingRepresentation() &&
7881 !(LHSType->isBlockPointerType() && IsRelational) &&
7882 !LHS.get()->getLocStart().isMacroID() &&
7883 !RHS.get()->getLocStart().isMacroID() &&
7884 ActiveTemplateInstantiations.empty()) {
7885 // For non-floating point types, check for self-comparisons of the form
7886 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7887 // often indicate logic errors in the program.
7889 // NOTE: Don't warn about comparison expressions resulting from macro
7890 // expansion. Also don't warn about comparisons which are only self
7891 // comparisons within a template specialization. The warnings should catch
7892 // obvious cases in the definition of the template anyways. The idea is to
7893 // warn when the typed comparison operator will always evaluate to the same
7895 ValueDecl *DL = getCompareDecl(LHSStripped);
7896 ValueDecl *DR = getCompareDecl(RHSStripped);
7897 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7898 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7903 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7904 !DL->getType()->isReferenceType() &&
7905 !DR->getType()->isReferenceType()) {
7906 // what is it always going to eval to?
7907 char always_evals_to;
7909 case BO_EQ: // e.g. array1 == array2
7910 always_evals_to = 0; // false
7912 case BO_NE: // e.g. array1 != array2
7913 always_evals_to = 1; // true
7916 // best we can say is 'a constant'
7917 always_evals_to = 2; // e.g. array1 <= array2
7920 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7922 << always_evals_to);
7925 if (isa<CastExpr>(LHSStripped))
7926 LHSStripped = LHSStripped->IgnoreParenCasts();
7927 if (isa<CastExpr>(RHSStripped))
7928 RHSStripped = RHSStripped->IgnoreParenCasts();
7930 // Warn about comparisons against a string constant (unless the other
7931 // operand is null), the user probably wants strcmp.
7932 Expr *literalString = nullptr;
7933 Expr *literalStringStripped = nullptr;
7934 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7935 !RHSStripped->isNullPointerConstant(Context,
7936 Expr::NPC_ValueDependentIsNull)) {
7937 literalString = LHS.get();
7938 literalStringStripped = LHSStripped;
7939 } else if ((isa<StringLiteral>(RHSStripped) ||
7940 isa<ObjCEncodeExpr>(RHSStripped)) &&
7941 !LHSStripped->isNullPointerConstant(Context,
7942 Expr::NPC_ValueDependentIsNull)) {
7943 literalString = RHS.get();
7944 literalStringStripped = RHSStripped;
7947 if (literalString) {
7948 DiagRuntimeBehavior(Loc, nullptr,
7949 PDiag(diag::warn_stringcompare)
7950 << isa<ObjCEncodeExpr>(literalStringStripped)
7951 << literalString->getSourceRange());
7955 // C99 6.5.8p3 / C99 6.5.9p4
7956 UsualArithmeticConversions(LHS, RHS);
7957 if (LHS.isInvalid() || RHS.isInvalid())
7960 LHSType = LHS.get()->getType();
7961 RHSType = RHS.get()->getType();
7963 // The result of comparisons is 'bool' in C++, 'int' in C.
7964 QualType ResultTy = Context.getLogicalOperationType();
7967 if (LHSType->isRealType() && RHSType->isRealType())
7970 // Check for comparisons of floating point operands using != and ==.
7971 if (LHSType->hasFloatingRepresentation())
7972 CheckFloatComparison(Loc, LHS.get(), RHS.get());
7974 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7978 const Expr::NullPointerConstantKind LHSNullKind =
7979 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7980 const Expr::NullPointerConstantKind RHSNullKind =
7981 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7982 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
7983 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
7985 if (!IsRelational && LHSIsNull != RHSIsNull) {
7986 bool IsEquality = Opc == BO_EQ;
7988 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
7989 RHS.get()->getSourceRange());
7991 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
7992 LHS.get()->getSourceRange());
7995 // All of the following pointer-related warnings are GCC extensions, except
7996 // when handling null pointer constants.
7997 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7998 QualType LCanPointeeTy =
7999 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8000 QualType RCanPointeeTy =
8001 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8003 if (getLangOpts().CPlusPlus) {
8004 if (LCanPointeeTy == RCanPointeeTy)
8006 if (!IsRelational &&
8007 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8008 // Valid unless comparison between non-null pointer and function pointer
8009 // This is a gcc extension compatibility comparison.
8010 // In a SFINAE context, we treat this as a hard error to maintain
8011 // conformance with the C++ standard.
8012 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8013 && !LHSIsNull && !RHSIsNull) {
8014 diagnoseFunctionPointerToVoidComparison(
8015 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8017 if (isSFINAEContext())
8020 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8025 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8030 // C99 6.5.9p2 and C99 6.5.8p2
8031 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8032 RCanPointeeTy.getUnqualifiedType())) {
8033 // Valid unless a relational comparison of function pointers
8034 if (IsRelational && LCanPointeeTy->isFunctionType()) {
8035 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8036 << LHSType << RHSType << LHS.get()->getSourceRange()
8037 << RHS.get()->getSourceRange();
8039 } else if (!IsRelational &&
8040 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8041 // Valid unless comparison between non-null pointer and function pointer
8042 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8043 && !LHSIsNull && !RHSIsNull)
8044 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8048 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8050 if (LCanPointeeTy != RCanPointeeTy) {
8051 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8052 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8053 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8055 if (LHSIsNull && !RHSIsNull)
8056 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8058 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8063 if (getLangOpts().CPlusPlus) {
8064 // Comparison of nullptr_t with itself.
8065 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8068 // Comparison of pointers with null pointer constants and equality
8069 // comparisons of member pointers to null pointer constants.
8071 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8073 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8074 RHS = ImpCastExprToType(RHS.get(), LHSType,
8075 LHSType->isMemberPointerType()
8076 ? CK_NullToMemberPointer
8077 : CK_NullToPointer);
8081 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8083 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8084 LHS = ImpCastExprToType(LHS.get(), RHSType,
8085 RHSType->isMemberPointerType()
8086 ? CK_NullToMemberPointer
8087 : CK_NullToPointer);
8091 // Comparison of member pointers.
8092 if (!IsRelational &&
8093 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8094 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8100 // Handle scoped enumeration types specifically, since they don't promote
8102 if (LHS.get()->getType()->isEnumeralType() &&
8103 Context.hasSameUnqualifiedType(LHS.get()->getType(),
8104 RHS.get()->getType()))
8108 // Handle block pointer types.
8109 if (!IsRelational && LHSType->isBlockPointerType() &&
8110 RHSType->isBlockPointerType()) {
8111 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8112 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8114 if (!LHSIsNull && !RHSIsNull &&
8115 !Context.typesAreCompatible(lpointee, rpointee)) {
8116 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8117 << LHSType << RHSType << LHS.get()->getSourceRange()
8118 << RHS.get()->getSourceRange();
8120 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8124 // Allow block pointers to be compared with null pointer constants.
8126 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8127 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8128 if (!LHSIsNull && !RHSIsNull) {
8129 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8130 ->getPointeeType()->isVoidType())
8131 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8132 ->getPointeeType()->isVoidType())))
8133 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8134 << LHSType << RHSType << LHS.get()->getSourceRange()
8135 << RHS.get()->getSourceRange();
8137 if (LHSIsNull && !RHSIsNull)
8138 LHS = ImpCastExprToType(LHS.get(), RHSType,
8139 RHSType->isPointerType() ? CK_BitCast
8140 : CK_AnyPointerToBlockPointerCast);
8142 RHS = ImpCastExprToType(RHS.get(), LHSType,
8143 LHSType->isPointerType() ? CK_BitCast
8144 : CK_AnyPointerToBlockPointerCast);
8148 if (LHSType->isObjCObjectPointerType() ||
8149 RHSType->isObjCObjectPointerType()) {
8150 const PointerType *LPT = LHSType->getAs<PointerType>();
8151 const PointerType *RPT = RHSType->getAs<PointerType>();
8153 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8154 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8156 if (!LPtrToVoid && !RPtrToVoid &&
8157 !Context.typesAreCompatible(LHSType, RHSType)) {
8158 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8161 if (LHSIsNull && !RHSIsNull) {
8162 Expr *E = LHS.get();
8163 if (getLangOpts().ObjCAutoRefCount)
8164 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8165 LHS = ImpCastExprToType(E, RHSType,
8166 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8169 Expr *E = RHS.get();
8170 if (getLangOpts().ObjCAutoRefCount)
8171 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8173 RHS = ImpCastExprToType(E, LHSType,
8174 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8178 if (LHSType->isObjCObjectPointerType() &&
8179 RHSType->isObjCObjectPointerType()) {
8180 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8181 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8183 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8184 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8186 if (LHSIsNull && !RHSIsNull)
8187 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8189 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8193 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8194 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8195 unsigned DiagID = 0;
8196 bool isError = false;
8197 if (LangOpts.DebuggerSupport) {
8198 // Under a debugger, allow the comparison of pointers to integers,
8199 // since users tend to want to compare addresses.
8200 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8201 (RHSIsNull && RHSType->isIntegerType())) {
8202 if (IsRelational && !getLangOpts().CPlusPlus)
8203 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8204 } else if (IsRelational && !getLangOpts().CPlusPlus)
8205 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8206 else if (getLangOpts().CPlusPlus) {
8207 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8210 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8214 << LHSType << RHSType << LHS.get()->getSourceRange()
8215 << RHS.get()->getSourceRange();
8220 if (LHSType->isIntegerType())
8221 LHS = ImpCastExprToType(LHS.get(), RHSType,
8222 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8224 RHS = ImpCastExprToType(RHS.get(), LHSType,
8225 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8229 // Handle block pointers.
8230 if (!IsRelational && RHSIsNull
8231 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8232 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8235 if (!IsRelational && LHSIsNull
8236 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8237 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8241 return InvalidOperands(Loc, LHS, RHS);
8245 // Return a signed type that is of identical size and number of elements.
8246 // For floating point vectors, return an integer type of identical size
8247 // and number of elements.
8248 QualType Sema::GetSignedVectorType(QualType V) {
8249 const VectorType *VTy = V->getAs<VectorType>();
8250 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8251 if (TypeSize == Context.getTypeSize(Context.CharTy))
8252 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8253 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8254 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8255 else if (TypeSize == Context.getTypeSize(Context.IntTy))
8256 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8257 else if (TypeSize == Context.getTypeSize(Context.LongTy))
8258 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8259 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8260 "Unhandled vector element size in vector compare");
8261 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8264 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8265 /// operates on extended vector types. Instead of producing an IntTy result,
8266 /// like a scalar comparison, a vector comparison produces a vector of integer
8268 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8270 bool IsRelational) {
8271 // Check to make sure we're operating on vectors of the same type and width,
8272 // Allowing one side to be a scalar of element type.
8273 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8277 QualType LHSType = LHS.get()->getType();
8279 // If AltiVec, the comparison results in a numeric type, i.e.
8280 // bool for C++, int for C
8281 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8282 return Context.getLogicalOperationType();
8284 // For non-floating point types, check for self-comparisons of the form
8285 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
8286 // often indicate logic errors in the program.
8287 if (!LHSType->hasFloatingRepresentation() &&
8288 ActiveTemplateInstantiations.empty()) {
8289 if (DeclRefExpr* DRL
8290 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8291 if (DeclRefExpr* DRR
8292 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8293 if (DRL->getDecl() == DRR->getDecl())
8294 DiagRuntimeBehavior(Loc, nullptr,
8295 PDiag(diag::warn_comparison_always)
8297 << 2 // "a constant"
8301 // Check for comparisons of floating point operands using != and ==.
8302 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8303 assert (RHS.get()->getType()->hasFloatingRepresentation());
8304 CheckFloatComparison(Loc, LHS.get(), RHS.get());
8307 // Return a signed type for the vector.
8308 return GetSignedVectorType(LHSType);
8311 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8312 SourceLocation Loc) {
8313 // Ensure that either both operands are of the same vector type, or
8314 // one operand is of a vector type and the other is of its element type.
8315 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8317 return InvalidOperands(Loc, LHS, RHS);
8318 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8319 vType->hasFloatingRepresentation())
8320 return InvalidOperands(Loc, LHS, RHS);
8322 return GetSignedVectorType(LHS.get()->getType());
8325 inline QualType Sema::CheckBitwiseOperands(
8326 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8327 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8329 if (LHS.get()->getType()->isVectorType() ||
8330 RHS.get()->getType()->isVectorType()) {
8331 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8332 RHS.get()->getType()->hasIntegerRepresentation())
8333 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8335 return InvalidOperands(Loc, LHS, RHS);
8338 ExprResult LHSResult = LHS, RHSResult = RHS;
8339 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8341 if (LHSResult.isInvalid() || RHSResult.isInvalid())
8343 LHS = LHSResult.get();
8344 RHS = RHSResult.get();
8346 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8348 return InvalidOperands(Loc, LHS, RHS);
8351 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8352 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8354 // Check vector operands differently.
8355 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8356 return CheckVectorLogicalOperands(LHS, RHS, Loc);
8358 // Diagnose cases where the user write a logical and/or but probably meant a
8359 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
8361 if (LHS.get()->getType()->isIntegerType() &&
8362 !LHS.get()->getType()->isBooleanType() &&
8363 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8364 // Don't warn in macros or template instantiations.
8365 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8366 // If the RHS can be constant folded, and if it constant folds to something
8367 // that isn't 0 or 1 (which indicate a potential logical operation that
8368 // happened to fold to true/false) then warn.
8369 // Parens on the RHS are ignored.
8370 llvm::APSInt Result;
8371 if (RHS.get()->EvaluateAsInt(Result, Context))
8372 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8373 !RHS.get()->getExprLoc().isMacroID()) ||
8374 (Result != 0 && Result != 1)) {
8375 Diag(Loc, diag::warn_logical_instead_of_bitwise)
8376 << RHS.get()->getSourceRange()
8377 << (Opc == BO_LAnd ? "&&" : "||");
8378 // Suggest replacing the logical operator with the bitwise version
8379 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8380 << (Opc == BO_LAnd ? "&" : "|")
8381 << FixItHint::CreateReplacement(SourceRange(
8382 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8384 Opc == BO_LAnd ? "&" : "|");
8386 // Suggest replacing "Foo() && kNonZero" with "Foo()"
8387 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8388 << FixItHint::CreateRemoval(
8390 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8391 0, getSourceManager(),
8393 RHS.get()->getLocEnd()));
8397 if (!Context.getLangOpts().CPlusPlus) {
8398 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8399 // not operate on the built-in scalar and vector float types.
8400 if (Context.getLangOpts().OpenCL &&
8401 Context.getLangOpts().OpenCLVersion < 120) {
8402 if (LHS.get()->getType()->isFloatingType() ||
8403 RHS.get()->getType()->isFloatingType())
8404 return InvalidOperands(Loc, LHS, RHS);
8407 LHS = UsualUnaryConversions(LHS.get());
8408 if (LHS.isInvalid())
8411 RHS = UsualUnaryConversions(RHS.get());
8412 if (RHS.isInvalid())
8415 if (!LHS.get()->getType()->isScalarType() ||
8416 !RHS.get()->getType()->isScalarType())
8417 return InvalidOperands(Loc, LHS, RHS);
8419 return Context.IntTy;
8422 // The following is safe because we only use this method for
8423 // non-overloadable operands.
8425 // C++ [expr.log.and]p1
8426 // C++ [expr.log.or]p1
8427 // The operands are both contextually converted to type bool.
8428 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8429 if (LHSRes.isInvalid())
8430 return InvalidOperands(Loc, LHS, RHS);
8433 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8434 if (RHSRes.isInvalid())
8435 return InvalidOperands(Loc, LHS, RHS);
8438 // C++ [expr.log.and]p2
8439 // C++ [expr.log.or]p2
8440 // The result is a bool.
8441 return Context.BoolTy;
8444 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8445 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8446 if (!ME) return false;
8447 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8448 ObjCMessageExpr *Base =
8449 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8450 if (!Base) return false;
8451 return Base->getMethodDecl() != nullptr;
8454 /// Is the given expression (which must be 'const') a reference to a
8455 /// variable which was originally non-const, but which has become
8456 /// 'const' due to being captured within a block?
8457 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8458 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8459 assert(E->isLValue() && E->getType().isConstQualified());
8460 E = E->IgnoreParens();
8462 // Must be a reference to a declaration from an enclosing scope.
8463 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8464 if (!DRE) return NCCK_None;
8465 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8467 // The declaration must be a variable which is not declared 'const'.
8468 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8469 if (!var) return NCCK_None;
8470 if (var->getType().isConstQualified()) return NCCK_None;
8471 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8473 // Decide whether the first capture was for a block or a lambda.
8474 DeclContext *DC = S.CurContext, *Prev = nullptr;
8475 while (DC != var->getDeclContext()) {
8477 DC = DC->getParent();
8479 // Unless we have an init-capture, we've gone one step too far.
8480 if (!var->isInitCapture())
8482 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8485 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
8486 /// emit an error and return true. If so, return false.
8487 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8488 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8489 SourceLocation OrigLoc = Loc;
8490 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8492 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8493 IsLV = Expr::MLV_InvalidMessageExpression;
8494 if (IsLV == Expr::MLV_Valid)
8498 bool NeedType = false;
8499 switch (IsLV) { // C99 6.5.16p2
8500 case Expr::MLV_ConstQualified:
8501 Diag = diag::err_typecheck_assign_const;
8503 // Use a specialized diagnostic when we're assigning to an object
8504 // from an enclosing function or block.
8505 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8506 if (NCCK == NCCK_Block)
8507 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8509 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8513 // In ARC, use some specialized diagnostics for occasions where we
8514 // infer 'const'. These are always pseudo-strong variables.
8515 if (S.getLangOpts().ObjCAutoRefCount) {
8516 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8517 if (declRef && isa<VarDecl>(declRef->getDecl())) {
8518 VarDecl *var = cast<VarDecl>(declRef->getDecl());
8520 // Use the normal diagnostic if it's pseudo-__strong but the
8521 // user actually wrote 'const'.
8522 if (var->isARCPseudoStrong() &&
8523 (!var->getTypeSourceInfo() ||
8524 !var->getTypeSourceInfo()->getType().isConstQualified())) {
8525 // There are two pseudo-strong cases:
8527 ObjCMethodDecl *method = S.getCurMethodDecl();
8528 if (method && var == method->getSelfDecl())
8529 Diag = method->isClassMethod()
8530 ? diag::err_typecheck_arc_assign_self_class_method
8531 : diag::err_typecheck_arc_assign_self;
8533 // - fast enumeration variables
8535 Diag = diag::err_typecheck_arr_assign_enumeration;
8539 Assign = SourceRange(OrigLoc, OrigLoc);
8540 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8541 // We need to preserve the AST regardless, so migration tool
8549 case Expr::MLV_ArrayType:
8550 case Expr::MLV_ArrayTemporary:
8551 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8554 case Expr::MLV_NotObjectType:
8555 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8558 case Expr::MLV_LValueCast:
8559 Diag = diag::err_typecheck_lvalue_casts_not_supported;
8561 case Expr::MLV_Valid:
8562 llvm_unreachable("did not take early return for MLV_Valid");
8563 case Expr::MLV_InvalidExpression:
8564 case Expr::MLV_MemberFunction:
8565 case Expr::MLV_ClassTemporary:
8566 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8568 case Expr::MLV_IncompleteType:
8569 case Expr::MLV_IncompleteVoidType:
8570 return S.RequireCompleteType(Loc, E->getType(),
8571 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8572 case Expr::MLV_DuplicateVectorComponents:
8573 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8575 case Expr::MLV_NoSetterProperty:
8576 llvm_unreachable("readonly properties should be processed differently");
8577 case Expr::MLV_InvalidMessageExpression:
8578 Diag = diag::error_readonly_message_assignment;
8580 case Expr::MLV_SubObjCPropertySetting:
8581 Diag = diag::error_no_subobject_property_setting;
8587 Assign = SourceRange(OrigLoc, OrigLoc);
8589 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8591 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8595 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8599 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8600 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8601 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8602 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8603 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8606 // Objective-C instance variables
8607 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8608 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8609 if (OL && OR && OL->getDecl() == OR->getDecl()) {
8610 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8611 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8612 if (RL && RR && RL->getDecl() == RR->getDecl())
8613 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8618 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8620 QualType CompoundType) {
8621 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8623 // Verify that LHS is a modifiable lvalue, and emit error if not.
8624 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8627 QualType LHSType = LHSExpr->getType();
8628 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8630 AssignConvertType ConvTy;
8631 if (CompoundType.isNull()) {
8632 Expr *RHSCheck = RHS.get();
8634 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8636 QualType LHSTy(LHSType);
8637 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8638 if (RHS.isInvalid())
8640 // Special case of NSObject attributes on c-style pointer types.
8641 if (ConvTy == IncompatiblePointer &&
8642 ((Context.isObjCNSObjectType(LHSType) &&
8643 RHSType->isObjCObjectPointerType()) ||
8644 (Context.isObjCNSObjectType(RHSType) &&
8645 LHSType->isObjCObjectPointerType())))
8646 ConvTy = Compatible;
8648 if (ConvTy == Compatible &&
8649 LHSType->isObjCObjectType())
8650 Diag(Loc, diag::err_objc_object_assignment)
8653 // If the RHS is a unary plus or minus, check to see if they = and + are
8654 // right next to each other. If so, the user may have typo'd "x =+ 4"
8655 // instead of "x += 4".
8656 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8657 RHSCheck = ICE->getSubExpr();
8658 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8659 if ((UO->getOpcode() == UO_Plus ||
8660 UO->getOpcode() == UO_Minus) &&
8661 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8662 // Only if the two operators are exactly adjacent.
8663 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8664 // And there is a space or other character before the subexpr of the
8665 // unary +/-. We don't want to warn on "x=-1".
8666 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8667 UO->getSubExpr()->getLocStart().isFileID()) {
8668 Diag(Loc, diag::warn_not_compound_assign)
8669 << (UO->getOpcode() == UO_Plus ? "+" : "-")
8670 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8674 if (ConvTy == Compatible) {
8675 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8676 // Warn about retain cycles where a block captures the LHS, but
8677 // not if the LHS is a simple variable into which the block is
8678 // being stored...unless that variable can be captured by reference!
8679 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8680 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8681 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8682 checkRetainCycles(LHSExpr, RHS.get());
8684 // It is safe to assign a weak reference into a strong variable.
8685 // Although this code can still have problems:
8686 // id x = self.weakProp;
8687 // id y = self.weakProp;
8688 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8689 // paths through the function. This should be revisited if
8690 // -Wrepeated-use-of-weak is made flow-sensitive.
8691 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8692 RHS.get()->getLocStart()))
8693 getCurFunction()->markSafeWeakUse(RHS.get());
8695 } else if (getLangOpts().ObjCAutoRefCount) {
8696 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8700 // Compound assignment "x += y"
8701 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8704 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8705 RHS.get(), AA_Assigning))
8708 CheckForNullPointerDereference(*this, LHSExpr);
8710 // C99 6.5.16p3: The type of an assignment expression is the type of the
8711 // left operand unless the left operand has qualified type, in which case
8712 // it is the unqualified version of the type of the left operand.
8713 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8714 // is converted to the type of the assignment expression (above).
8715 // C++ 5.17p1: the type of the assignment expression is that of its left
8717 return (getLangOpts().CPlusPlus
8718 ? LHSType : LHSType.getUnqualifiedType());
8722 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8723 SourceLocation Loc) {
8724 LHS = S.CheckPlaceholderExpr(LHS.get());
8725 RHS = S.CheckPlaceholderExpr(RHS.get());
8726 if (LHS.isInvalid() || RHS.isInvalid())
8729 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8730 // operands, but not unary promotions.
8731 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8733 // So we treat the LHS as a ignored value, and in C++ we allow the
8734 // containing site to determine what should be done with the RHS.
8735 LHS = S.IgnoredValueConversions(LHS.get());
8736 if (LHS.isInvalid())
8739 S.DiagnoseUnusedExprResult(LHS.get());
8741 if (!S.getLangOpts().CPlusPlus) {
8742 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8743 if (RHS.isInvalid())
8745 if (!RHS.get()->getType()->isVoidType())
8746 S.RequireCompleteType(Loc, RHS.get()->getType(),
8747 diag::err_incomplete_type);
8750 return RHS.get()->getType();
8753 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8754 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8755 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8757 SourceLocation OpLoc,
8758 bool IsInc, bool IsPrefix) {
8759 if (Op->isTypeDependent())
8760 return S.Context.DependentTy;
8762 QualType ResType = Op->getType();
8763 // Atomic types can be used for increment / decrement where the non-atomic
8764 // versions can, so ignore the _Atomic() specifier for the purpose of
8766 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8767 ResType = ResAtomicType->getValueType();
8769 assert(!ResType.isNull() && "no type for increment/decrement expression");
8771 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8772 // Decrement of bool is not allowed.
8774 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8777 // Increment of bool sets it to true, but is deprecated.
8778 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8779 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8780 // Error on enum increments and decrements in C++ mode
8781 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8783 } else if (ResType->isRealType()) {
8785 } else if (ResType->isPointerType()) {
8786 // C99 6.5.2.4p2, 6.5.6p2
8787 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8789 } else if (ResType->isObjCObjectPointerType()) {
8790 // On modern runtimes, ObjC pointer arithmetic is forbidden.
8791 // Otherwise, we just need a complete type.
8792 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8793 checkArithmeticOnObjCPointer(S, OpLoc, Op))
8795 } else if (ResType->isAnyComplexType()) {
8796 // C99 does not support ++/-- on complex types, we allow as an extension.
8797 S.Diag(OpLoc, diag::ext_integer_increment_complex)
8798 << ResType << Op->getSourceRange();
8799 } else if (ResType->isPlaceholderType()) {
8800 ExprResult PR = S.CheckPlaceholderExpr(Op);
8801 if (PR.isInvalid()) return QualType();
8802 return CheckIncrementDecrementOperand(S, PR.get(), VK, OpLoc,
8804 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8805 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8806 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8807 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8808 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8810 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8811 << ResType << int(IsInc) << Op->getSourceRange();
8814 // At this point, we know we have a real, complex or pointer type.
8815 // Now make sure the operand is a modifiable lvalue.
8816 if (CheckForModifiableLvalue(Op, OpLoc, S))
8818 // In C++, a prefix increment is the same type as the operand. Otherwise
8819 // (in C or with postfix), the increment is the unqualified type of the
8821 if (IsPrefix && S.getLangOpts().CPlusPlus) {
8826 return ResType.getUnqualifiedType();
8831 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8832 /// This routine allows us to typecheck complex/recursive expressions
8833 /// where the declaration is needed for type checking. We only need to
8834 /// handle cases when the expression references a function designator
8835 /// or is an lvalue. Here are some examples:
8837 /// - &*****f => f for f a function designator.
8839 /// - &s.zz[1].yy -> s, if zz is an array
8840 /// - *(x + 1) -> x, if x is an array
8841 /// - &"123"[2] -> 0
8842 /// - & __real__ x -> x
8843 static ValueDecl *getPrimaryDecl(Expr *E) {
8844 switch (E->getStmtClass()) {
8845 case Stmt::DeclRefExprClass:
8846 return cast<DeclRefExpr>(E)->getDecl();
8847 case Stmt::MemberExprClass:
8848 // If this is an arrow operator, the address is an offset from
8849 // the base's value, so the object the base refers to is
8851 if (cast<MemberExpr>(E)->isArrow())
8853 // Otherwise, the expression refers to a part of the base
8854 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8855 case Stmt::ArraySubscriptExprClass: {
8856 // FIXME: This code shouldn't be necessary! We should catch the implicit
8857 // promotion of register arrays earlier.
8858 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8859 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8860 if (ICE->getSubExpr()->getType()->isArrayType())
8861 return getPrimaryDecl(ICE->getSubExpr());
8865 case Stmt::UnaryOperatorClass: {
8866 UnaryOperator *UO = cast<UnaryOperator>(E);
8868 switch(UO->getOpcode()) {
8872 return getPrimaryDecl(UO->getSubExpr());
8877 case Stmt::ParenExprClass:
8878 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8879 case Stmt::ImplicitCastExprClass:
8880 // If the result of an implicit cast is an l-value, we care about
8881 // the sub-expression; otherwise, the result here doesn't matter.
8882 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8891 AO_Vector_Element = 1,
8892 AO_Property_Expansion = 2,
8893 AO_Register_Variable = 3,
8897 /// \brief Diagnose invalid operand for address of operations.
8899 /// \param Type The type of operand which cannot have its address taken.
8900 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8901 Expr *E, unsigned Type) {
8902 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8905 /// CheckAddressOfOperand - The operand of & must be either a function
8906 /// designator or an lvalue designating an object. If it is an lvalue, the
8907 /// object cannot be declared with storage class register or be a bit field.
8908 /// Note: The usual conversions are *not* applied to the operand of the &
8909 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8910 /// In C++, the operand might be an overloaded function name, in which case
8911 /// we allow the '&' but retain the overloaded-function type.
8912 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8913 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8914 if (PTy->getKind() == BuiltinType::Overload) {
8915 Expr *E = OrigOp.get()->IgnoreParens();
8916 if (!isa<OverloadExpr>(E)) {
8917 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8918 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8919 << OrigOp.get()->getSourceRange();
8923 OverloadExpr *Ovl = cast<OverloadExpr>(E);
8924 if (isa<UnresolvedMemberExpr>(Ovl))
8925 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8926 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8927 << OrigOp.get()->getSourceRange();
8931 return Context.OverloadTy;
8934 if (PTy->getKind() == BuiltinType::UnknownAny)
8935 return Context.UnknownAnyTy;
8937 if (PTy->getKind() == BuiltinType::BoundMember) {
8938 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8939 << OrigOp.get()->getSourceRange();
8943 OrigOp = CheckPlaceholderExpr(OrigOp.get());
8944 if (OrigOp.isInvalid()) return QualType();
8947 if (OrigOp.get()->isTypeDependent())
8948 return Context.DependentTy;
8950 assert(!OrigOp.get()->getType()->isPlaceholderType());
8952 // Make sure to ignore parentheses in subsequent checks
8953 Expr *op = OrigOp.get()->IgnoreParens();
8955 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
8956 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
8957 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
8961 if (getLangOpts().C99) {
8962 // Implement C99-only parts of addressof rules.
8963 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8964 if (uOp->getOpcode() == UO_Deref)
8965 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8966 // (assuming the deref expression is valid).
8967 return uOp->getSubExpr()->getType();
8969 // Technically, there should be a check for array subscript
8970 // expressions here, but the result of one is always an lvalue anyway.
8972 ValueDecl *dcl = getPrimaryDecl(op);
8973 Expr::LValueClassification lval = op->ClassifyLValue(Context);
8974 unsigned AddressOfError = AO_No_Error;
8976 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8977 bool sfinae = (bool)isSFINAEContext();
8978 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8979 : diag::ext_typecheck_addrof_temporary)
8980 << op->getType() << op->getSourceRange();
8983 // Materialize the temporary as an lvalue so that we can take its address.
8984 OrigOp = op = new (Context)
8985 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
8986 } else if (isa<ObjCSelectorExpr>(op)) {
8987 return Context.getPointerType(op->getType());
8988 } else if (lval == Expr::LV_MemberFunction) {
8989 // If it's an instance method, make a member pointer.
8990 // The expression must have exactly the form &A::foo.
8992 // If the underlying expression isn't a decl ref, give up.
8993 if (!isa<DeclRefExpr>(op)) {
8994 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8995 << OrigOp.get()->getSourceRange();
8998 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8999 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9001 // The id-expression was parenthesized.
9002 if (OrigOp.get() != DRE) {
9003 Diag(OpLoc, diag::err_parens_pointer_member_function)
9004 << OrigOp.get()->getSourceRange();
9006 // The method was named without a qualifier.
9007 } else if (!DRE->getQualifier()) {
9008 if (MD->getParent()->getName().empty())
9009 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9010 << op->getSourceRange();
9012 SmallString<32> Str;
9013 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9014 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9015 << op->getSourceRange()
9016 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9020 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9021 if (isa<CXXDestructorDecl>(MD))
9022 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9024 QualType MPTy = Context.getMemberPointerType(
9025 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9026 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9027 RequireCompleteType(OpLoc, MPTy, 0);
9029 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9031 // The operand must be either an l-value or a function designator
9032 if (!op->getType()->isFunctionType()) {
9033 // Use a special diagnostic for loads from property references.
9034 if (isa<PseudoObjectExpr>(op)) {
9035 AddressOfError = AO_Property_Expansion;
9037 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9038 << op->getType() << op->getSourceRange();
9042 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9043 // The operand cannot be a bit-field
9044 AddressOfError = AO_Bit_Field;
9045 } else if (op->getObjectKind() == OK_VectorComponent) {
9046 // The operand cannot be an element of a vector
9047 AddressOfError = AO_Vector_Element;
9048 } else if (dcl) { // C99 6.5.3.2p1
9049 // We have an lvalue with a decl. Make sure the decl is not declared
9050 // with the register storage-class specifier.
9051 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9052 // in C++ it is not error to take address of a register
9053 // variable (c++03 7.1.1P3)
9054 if (vd->getStorageClass() == SC_Register &&
9055 !getLangOpts().CPlusPlus) {
9056 AddressOfError = AO_Register_Variable;
9058 } else if (isa<FunctionTemplateDecl>(dcl)) {
9059 return Context.OverloadTy;
9060 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9061 // Okay: we can take the address of a field.
9062 // Could be a pointer to member, though, if there is an explicit
9063 // scope qualifier for the class.
9064 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9065 DeclContext *Ctx = dcl->getDeclContext();
9066 if (Ctx && Ctx->isRecord()) {
9067 if (dcl->getType()->isReferenceType()) {
9069 diag::err_cannot_form_pointer_to_member_of_reference_type)
9070 << dcl->getDeclName() << dcl->getType();
9074 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9075 Ctx = Ctx->getParent();
9077 QualType MPTy = Context.getMemberPointerType(
9079 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9080 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9081 RequireCompleteType(OpLoc, MPTy, 0);
9085 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9086 llvm_unreachable("Unknown/unexpected decl type");
9089 if (AddressOfError != AO_No_Error) {
9090 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9094 if (lval == Expr::LV_IncompleteVoidType) {
9095 // Taking the address of a void variable is technically illegal, but we
9096 // allow it in cases which are otherwise valid.
9097 // Example: "extern void x; void* y = &x;".
9098 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9101 // If the operand has type "type", the result has type "pointer to type".
9102 if (op->getType()->isObjCObjectType())
9103 return Context.getObjCObjectPointerType(op->getType());
9104 return Context.getPointerType(op->getType());
9107 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9108 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9109 SourceLocation OpLoc) {
9110 if (Op->isTypeDependent())
9111 return S.Context.DependentTy;
9113 ExprResult ConvResult = S.UsualUnaryConversions(Op);
9114 if (ConvResult.isInvalid())
9116 Op = ConvResult.get();
9117 QualType OpTy = Op->getType();
9120 if (isa<CXXReinterpretCastExpr>(Op)) {
9121 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9122 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9123 Op->getSourceRange());
9126 if (const PointerType *PT = OpTy->getAs<PointerType>())
9127 Result = PT->getPointeeType();
9128 else if (const ObjCObjectPointerType *OPT =
9129 OpTy->getAs<ObjCObjectPointerType>())
9130 Result = OPT->getPointeeType();
9132 ExprResult PR = S.CheckPlaceholderExpr(Op);
9133 if (PR.isInvalid()) return QualType();
9135 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9138 if (Result.isNull()) {
9139 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9140 << OpTy << Op->getSourceRange();
9144 // Note that per both C89 and C99, indirection is always legal, even if Result
9145 // is an incomplete type or void. It would be possible to warn about
9146 // dereferencing a void pointer, but it's completely well-defined, and such a
9147 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9148 // for pointers to 'void' but is fine for any other pointer type:
9150 // C++ [expr.unary.op]p1:
9151 // [...] the expression to which [the unary * operator] is applied shall
9152 // be a pointer to an object type, or a pointer to a function type
9153 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9154 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9155 << OpTy << Op->getSourceRange();
9157 // Dereferences are usually l-values...
9160 // ...except that certain expressions are never l-values in C.
9161 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9167 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
9168 tok::TokenKind Kind) {
9169 BinaryOperatorKind Opc;
9171 default: llvm_unreachable("Unknown binop!");
9172 case tok::periodstar: Opc = BO_PtrMemD; break;
9173 case tok::arrowstar: Opc = BO_PtrMemI; break;
9174 case tok::star: Opc = BO_Mul; break;
9175 case tok::slash: Opc = BO_Div; break;
9176 case tok::percent: Opc = BO_Rem; break;
9177 case tok::plus: Opc = BO_Add; break;
9178 case tok::minus: Opc = BO_Sub; break;
9179 case tok::lessless: Opc = BO_Shl; break;
9180 case tok::greatergreater: Opc = BO_Shr; break;
9181 case tok::lessequal: Opc = BO_LE; break;
9182 case tok::less: Opc = BO_LT; break;
9183 case tok::greaterequal: Opc = BO_GE; break;
9184 case tok::greater: Opc = BO_GT; break;
9185 case tok::exclaimequal: Opc = BO_NE; break;
9186 case tok::equalequal: Opc = BO_EQ; break;
9187 case tok::amp: Opc = BO_And; break;
9188 case tok::caret: Opc = BO_Xor; break;
9189 case tok::pipe: Opc = BO_Or; break;
9190 case tok::ampamp: Opc = BO_LAnd; break;
9191 case tok::pipepipe: Opc = BO_LOr; break;
9192 case tok::equal: Opc = BO_Assign; break;
9193 case tok::starequal: Opc = BO_MulAssign; break;
9194 case tok::slashequal: Opc = BO_DivAssign; break;
9195 case tok::percentequal: Opc = BO_RemAssign; break;
9196 case tok::plusequal: Opc = BO_AddAssign; break;
9197 case tok::minusequal: Opc = BO_SubAssign; break;
9198 case tok::lesslessequal: Opc = BO_ShlAssign; break;
9199 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
9200 case tok::ampequal: Opc = BO_AndAssign; break;
9201 case tok::caretequal: Opc = BO_XorAssign; break;
9202 case tok::pipeequal: Opc = BO_OrAssign; break;
9203 case tok::comma: Opc = BO_Comma; break;
9208 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9209 tok::TokenKind Kind) {
9210 UnaryOperatorKind Opc;
9212 default: llvm_unreachable("Unknown unary op!");
9213 case tok::plusplus: Opc = UO_PreInc; break;
9214 case tok::minusminus: Opc = UO_PreDec; break;
9215 case tok::amp: Opc = UO_AddrOf; break;
9216 case tok::star: Opc = UO_Deref; break;
9217 case tok::plus: Opc = UO_Plus; break;
9218 case tok::minus: Opc = UO_Minus; break;
9219 case tok::tilde: Opc = UO_Not; break;
9220 case tok::exclaim: Opc = UO_LNot; break;
9221 case tok::kw___real: Opc = UO_Real; break;
9222 case tok::kw___imag: Opc = UO_Imag; break;
9223 case tok::kw___extension__: Opc = UO_Extension; break;
9228 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9229 /// This warning is only emitted for builtin assignment operations. It is also
9230 /// suppressed in the event of macro expansions.
9231 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9232 SourceLocation OpLoc) {
9233 if (!S.ActiveTemplateInstantiations.empty())
9235 if (OpLoc.isInvalid() || OpLoc.isMacroID())
9237 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9238 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9239 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9240 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9241 if (!LHSDeclRef || !RHSDeclRef ||
9242 LHSDeclRef->getLocation().isMacroID() ||
9243 RHSDeclRef->getLocation().isMacroID())
9245 const ValueDecl *LHSDecl =
9246 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9247 const ValueDecl *RHSDecl =
9248 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9249 if (LHSDecl != RHSDecl)
9251 if (LHSDecl->getType().isVolatileQualified())
9253 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9254 if (RefTy->getPointeeType().isVolatileQualified())
9257 S.Diag(OpLoc, diag::warn_self_assignment)
9258 << LHSDeclRef->getType()
9259 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9262 /// Check if a bitwise-& is performed on an Objective-C pointer. This
9263 /// is usually indicative of introspection within the Objective-C pointer.
9264 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9265 SourceLocation OpLoc) {
9266 if (!S.getLangOpts().ObjC1)
9269 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9270 const Expr *LHS = L.get();
9271 const Expr *RHS = R.get();
9273 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9274 ObjCPointerExpr = LHS;
9277 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9278 ObjCPointerExpr = RHS;
9282 // This warning is deliberately made very specific to reduce false
9283 // positives with logic that uses '&' for hashing. This logic mainly
9284 // looks for code trying to introspect into tagged pointers, which
9285 // code should generally never do.
9286 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9287 unsigned Diag = diag::warn_objc_pointer_masking;
9288 // Determine if we are introspecting the result of performSelectorXXX.
9289 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9290 // Special case messages to -performSelector and friends, which
9291 // can return non-pointer values boxed in a pointer value.
9292 // Some clients may wish to silence warnings in this subcase.
9293 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9294 Selector S = ME->getSelector();
9295 StringRef SelArg0 = S.getNameForSlot(0);
9296 if (SelArg0.startswith("performSelector"))
9297 Diag = diag::warn_objc_pointer_masking_performSelector;
9301 << ObjCPointerExpr->getSourceRange();
9305 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9306 /// operator @p Opc at location @c TokLoc. This routine only supports
9307 /// built-in operations; ActOnBinOp handles overloaded operators.
9308 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9309 BinaryOperatorKind Opc,
9310 Expr *LHSExpr, Expr *RHSExpr) {
9311 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9312 // The syntax only allows initializer lists on the RHS of assignment,
9313 // so we don't need to worry about accepting invalid code for
9314 // non-assignment operators.
9316 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9317 // of x = {} is x = T().
9318 InitializationKind Kind =
9319 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9320 InitializedEntity Entity =
9321 InitializedEntity::InitializeTemporary(LHSExpr->getType());
9322 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9323 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9324 if (Init.isInvalid())
9326 RHSExpr = Init.get();
9329 ExprResult LHS = LHSExpr, RHS = RHSExpr;
9330 QualType ResultTy; // Result type of the binary operator.
9331 // The following two variables are used for compound assignment operators
9332 QualType CompLHSTy; // Type of LHS after promotions for computation
9333 QualType CompResultTy; // Type of computation result
9334 ExprValueKind VK = VK_RValue;
9335 ExprObjectKind OK = OK_Ordinary;
9339 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9340 if (getLangOpts().CPlusPlus &&
9341 LHS.get()->getObjectKind() != OK_ObjCProperty) {
9342 VK = LHS.get()->getValueKind();
9343 OK = LHS.get()->getObjectKind();
9345 if (!ResultTy.isNull())
9346 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9350 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9355 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9359 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9362 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9365 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9369 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9375 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9379 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9382 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9385 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9389 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9393 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9394 Opc == BO_DivAssign);
9395 CompLHSTy = CompResultTy;
9396 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9397 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9400 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9401 CompLHSTy = CompResultTy;
9402 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9403 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9406 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9407 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9408 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9411 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9412 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9413 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9417 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9418 CompLHSTy = CompResultTy;
9419 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9420 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9423 case BO_OrAssign: // fallthrough
9424 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9426 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9427 CompLHSTy = CompResultTy;
9428 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9429 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9432 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9433 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9434 VK = RHS.get()->getValueKind();
9435 OK = RHS.get()->getObjectKind();
9439 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9442 // Check for array bounds violations for both sides of the BinaryOperator
9443 CheckArrayAccess(LHS.get());
9444 CheckArrayAccess(RHS.get());
9446 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9447 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9448 &Context.Idents.get("object_setClass"),
9449 SourceLocation(), LookupOrdinaryName);
9450 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9451 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9452 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9453 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9454 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9455 FixItHint::CreateInsertion(RHSLocEnd, ")");
9458 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9460 else if (const ObjCIvarRefExpr *OIRE =
9461 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9462 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9464 if (CompResultTy.isNull())
9465 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
9466 OK, OpLoc, FPFeatures.fp_contract);
9467 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9470 OK = LHS.get()->getObjectKind();
9472 return new (Context) CompoundAssignOperator(
9473 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
9474 OpLoc, FPFeatures.fp_contract);
9477 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9478 /// operators are mixed in a way that suggests that the programmer forgot that
9479 /// comparison operators have higher precedence. The most typical example of
9480 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9481 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9482 SourceLocation OpLoc, Expr *LHSExpr,
9484 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9485 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9487 // Check that one of the sides is a comparison operator.
9488 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9489 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9490 if (!isLeftComp && !isRightComp)
9493 // Bitwise operations are sometimes used as eager logical ops.
9494 // Don't diagnose this.
9495 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9496 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9497 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9500 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9502 : SourceRange(OpLoc, RHSExpr->getLocEnd());
9503 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9504 SourceRange ParensRange = isLeftComp ?
9505 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9506 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9508 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9509 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9510 SuggestParentheses(Self, OpLoc,
9511 Self.PDiag(diag::note_precedence_silence) << OpStr,
9512 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9513 SuggestParentheses(Self, OpLoc,
9514 Self.PDiag(diag::note_precedence_bitwise_first)
9515 << BinaryOperator::getOpcodeStr(Opc),
9519 /// \brief It accepts a '&' expr that is inside a '|' one.
9520 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9523 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9524 BinaryOperator *Bop) {
9525 assert(Bop->getOpcode() == BO_And);
9526 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9527 << Bop->getSourceRange() << OpLoc;
9528 SuggestParentheses(Self, Bop->getOperatorLoc(),
9529 Self.PDiag(diag::note_precedence_silence)
9530 << Bop->getOpcodeStr(),
9531 Bop->getSourceRange());
9534 /// \brief It accepts a '&&' expr that is inside a '||' one.
9535 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9538 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9539 BinaryOperator *Bop) {
9540 assert(Bop->getOpcode() == BO_LAnd);
9541 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9542 << Bop->getSourceRange() << OpLoc;
9543 SuggestParentheses(Self, Bop->getOperatorLoc(),
9544 Self.PDiag(diag::note_precedence_silence)
9545 << Bop->getOpcodeStr(),
9546 Bop->getSourceRange());
9549 /// \brief Returns true if the given expression can be evaluated as a constant
9551 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9553 return !E->isValueDependent() &&
9554 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9557 /// \brief Returns true if the given expression can be evaluated as a constant
9559 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9561 return !E->isValueDependent() &&
9562 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9565 /// \brief Look for '&&' in the left hand of a '||' expr.
9566 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9567 Expr *LHSExpr, Expr *RHSExpr) {
9568 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9569 if (Bop->getOpcode() == BO_LAnd) {
9570 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9571 if (EvaluatesAsFalse(S, RHSExpr))
9573 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9574 if (!EvaluatesAsTrue(S, Bop->getLHS()))
9575 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9576 } else if (Bop->getOpcode() == BO_LOr) {
9577 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9578 // If it's "a || b && 1 || c" we didn't warn earlier for
9579 // "a || b && 1", but warn now.
9580 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9581 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9587 /// \brief Look for '&&' in the right hand of a '||' expr.
9588 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9589 Expr *LHSExpr, Expr *RHSExpr) {
9590 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9591 if (Bop->getOpcode() == BO_LAnd) {
9592 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9593 if (EvaluatesAsFalse(S, LHSExpr))
9595 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9596 if (!EvaluatesAsTrue(S, Bop->getRHS()))
9597 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9602 /// \brief Look for '&' in the left or right hand of a '|' expr.
9603 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9605 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9606 if (Bop->getOpcode() == BO_And)
9607 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9611 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9612 Expr *SubExpr, StringRef Shift) {
9613 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9614 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9615 StringRef Op = Bop->getOpcodeStr();
9616 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9617 << Bop->getSourceRange() << OpLoc << Shift << Op;
9618 SuggestParentheses(S, Bop->getOperatorLoc(),
9619 S.PDiag(diag::note_precedence_silence) << Op,
9620 Bop->getSourceRange());
9625 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9626 Expr *LHSExpr, Expr *RHSExpr) {
9627 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9631 FunctionDecl *FD = OCE->getDirectCallee();
9632 if (!FD || !FD->isOverloadedOperator())
9635 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9636 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9639 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9640 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9641 << (Kind == OO_LessLess);
9642 SuggestParentheses(S, OCE->getOperatorLoc(),
9643 S.PDiag(diag::note_precedence_silence)
9644 << (Kind == OO_LessLess ? "<<" : ">>"),
9645 OCE->getSourceRange());
9646 SuggestParentheses(S, OpLoc,
9647 S.PDiag(diag::note_evaluate_comparison_first),
9648 SourceRange(OCE->getArg(1)->getLocStart(),
9649 RHSExpr->getLocEnd()));
9652 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9654 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9655 SourceLocation OpLoc, Expr *LHSExpr,
9657 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9658 if (BinaryOperator::isBitwiseOp(Opc))
9659 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9661 // Diagnose "arg1 & arg2 | arg3"
9662 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9663 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9664 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9667 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9668 // We don't warn for 'assert(a || b && "bad")' since this is safe.
9669 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9670 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9671 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9674 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9676 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9677 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9678 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9681 // Warn on overloaded shift operators and comparisons, such as:
9683 if (BinaryOperator::isComparisonOp(Opc))
9684 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9687 // Binary Operators. 'Tok' is the token for the operator.
9688 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9689 tok::TokenKind Kind,
9690 Expr *LHSExpr, Expr *RHSExpr) {
9691 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9692 assert(LHSExpr && "ActOnBinOp(): missing left expression");
9693 assert(RHSExpr && "ActOnBinOp(): missing right expression");
9695 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9696 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9698 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9701 /// Build an overloaded binary operator expression in the given scope.
9702 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9703 BinaryOperatorKind Opc,
9704 Expr *LHS, Expr *RHS) {
9705 // Find all of the overloaded operators visible from this
9706 // point. We perform both an operator-name lookup from the local
9707 // scope and an argument-dependent lookup based on the types of
9709 UnresolvedSet<16> Functions;
9710 OverloadedOperatorKind OverOp
9711 = BinaryOperator::getOverloadedOperator(Opc);
9712 if (Sc && OverOp != OO_None)
9713 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9714 RHS->getType(), Functions);
9716 // Build the (potentially-overloaded, potentially-dependent)
9717 // binary operation.
9718 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9721 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9722 BinaryOperatorKind Opc,
9723 Expr *LHSExpr, Expr *RHSExpr) {
9724 // We want to end up calling one of checkPseudoObjectAssignment
9725 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9726 // both expressions are overloadable or either is type-dependent),
9727 // or CreateBuiltinBinOp (in any other case). We also want to get
9728 // any placeholder types out of the way.
9730 // Handle pseudo-objects in the LHS.
9731 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9732 // Assignments with a pseudo-object l-value need special analysis.
9733 if (pty->getKind() == BuiltinType::PseudoObject &&
9734 BinaryOperator::isAssignmentOp(Opc))
9735 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9737 // Don't resolve overloads if the other type is overloadable.
9738 if (pty->getKind() == BuiltinType::Overload) {
9739 // We can't actually test that if we still have a placeholder,
9740 // though. Fortunately, none of the exceptions we see in that
9741 // code below are valid when the LHS is an overload set. Note
9742 // that an overload set can be dependently-typed, but it never
9743 // instantiates to having an overloadable type.
9744 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9745 if (resolvedRHS.isInvalid()) return ExprError();
9746 RHSExpr = resolvedRHS.get();
9748 if (RHSExpr->isTypeDependent() ||
9749 RHSExpr->getType()->isOverloadableType())
9750 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9753 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9754 if (LHS.isInvalid()) return ExprError();
9755 LHSExpr = LHS.get();
9758 // Handle pseudo-objects in the RHS.
9759 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9760 // An overload in the RHS can potentially be resolved by the type
9761 // being assigned to.
9762 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9763 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9764 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9766 if (LHSExpr->getType()->isOverloadableType())
9767 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9769 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9772 // Don't resolve overloads if the other type is overloadable.
9773 if (pty->getKind() == BuiltinType::Overload &&
9774 LHSExpr->getType()->isOverloadableType())
9775 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9777 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9778 if (!resolvedRHS.isUsable()) return ExprError();
9779 RHSExpr = resolvedRHS.get();
9782 if (getLangOpts().CPlusPlus) {
9783 // If either expression is type-dependent, always build an
9785 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9786 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9788 // Otherwise, build an overloaded op if either expression has an
9789 // overloadable type.
9790 if (LHSExpr->getType()->isOverloadableType() ||
9791 RHSExpr->getType()->isOverloadableType())
9792 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9795 // Build a built-in binary operation.
9796 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9799 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9800 UnaryOperatorKind Opc,
9802 ExprResult Input = InputExpr;
9803 ExprValueKind VK = VK_RValue;
9804 ExprObjectKind OK = OK_Ordinary;
9805 QualType resultType;
9811 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9818 resultType = CheckAddressOfOperand(Input, OpLoc);
9821 Input = DefaultFunctionArrayLvalueConversion(Input.get());
9822 if (Input.isInvalid()) return ExprError();
9823 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9828 Input = UsualUnaryConversions(Input.get());
9829 if (Input.isInvalid()) return ExprError();
9830 resultType = Input.get()->getType();
9831 if (resultType->isDependentType())
9833 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9834 resultType->isVectorType())
9836 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9838 resultType->isPointerType())
9841 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9842 << resultType << Input.get()->getSourceRange());
9844 case UO_Not: // bitwise complement
9845 Input = UsualUnaryConversions(Input.get());
9846 if (Input.isInvalid())
9848 resultType = Input.get()->getType();
9849 if (resultType->isDependentType())
9851 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9852 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9853 // C99 does not support '~' for complex conjugation.
9854 Diag(OpLoc, diag::ext_integer_complement_complex)
9855 << resultType << Input.get()->getSourceRange();
9856 else if (resultType->hasIntegerRepresentation())
9858 else if (resultType->isExtVectorType()) {
9859 if (Context.getLangOpts().OpenCL) {
9860 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9861 // on vector float types.
9862 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9863 if (!T->isIntegerType())
9864 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9865 << resultType << Input.get()->getSourceRange());
9869 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9870 << resultType << Input.get()->getSourceRange());
9874 case UO_LNot: // logical negation
9875 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9876 Input = DefaultFunctionArrayLvalueConversion(Input.get());
9877 if (Input.isInvalid()) return ExprError();
9878 resultType = Input.get()->getType();
9880 // Though we still have to promote half FP to float...
9881 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9882 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
9883 resultType = Context.FloatTy;
9886 if (resultType->isDependentType())
9888 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9889 // C99 6.5.3.3p1: ok, fallthrough;
9890 if (Context.getLangOpts().CPlusPlus) {
9891 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9892 // operand contextually converted to bool.
9893 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
9894 ScalarTypeToBooleanCastKind(resultType));
9895 } else if (Context.getLangOpts().OpenCL &&
9896 Context.getLangOpts().OpenCLVersion < 120) {
9897 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9898 // operate on scalar float types.
9899 if (!resultType->isIntegerType())
9900 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9901 << resultType << Input.get()->getSourceRange());
9903 } else if (resultType->isExtVectorType()) {
9904 if (Context.getLangOpts().OpenCL &&
9905 Context.getLangOpts().OpenCLVersion < 120) {
9906 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9907 // operate on vector float types.
9908 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9909 if (!T->isIntegerType())
9910 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9911 << resultType << Input.get()->getSourceRange());
9913 // Vector logical not returns the signed variant of the operand type.
9914 resultType = GetSignedVectorType(resultType);
9917 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9918 << resultType << Input.get()->getSourceRange());
9921 // LNot always has type int. C99 6.5.3.3p5.
9922 // In C++, it's bool. C++ 5.3.1p8
9923 resultType = Context.getLogicalOperationType();
9927 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9928 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9929 // complex l-values to ordinary l-values and all other values to r-values.
9930 if (Input.isInvalid()) return ExprError();
9931 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9932 if (Input.get()->getValueKind() != VK_RValue &&
9933 Input.get()->getObjectKind() == OK_Ordinary)
9934 VK = Input.get()->getValueKind();
9935 } else if (!getLangOpts().CPlusPlus) {
9936 // In C, a volatile scalar is read by __imag. In C++, it is not.
9937 Input = DefaultLvalueConversion(Input.get());
9941 resultType = Input.get()->getType();
9942 VK = Input.get()->getValueKind();
9943 OK = Input.get()->getObjectKind();
9946 if (resultType.isNull() || Input.isInvalid())
9949 // Check for array bounds violations in the operand of the UnaryOperator,
9950 // except for the '*' and '&' operators that have to be handled specially
9951 // by CheckArrayAccess (as there are special cases like &array[arraysize]
9952 // that are explicitly defined as valid by the standard).
9953 if (Opc != UO_AddrOf && Opc != UO_Deref)
9954 CheckArrayAccess(Input.get());
9956 return new (Context)
9957 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
9960 /// \brief Determine whether the given expression is a qualified member
9961 /// access expression, of a form that could be turned into a pointer to member
9962 /// with the address-of operator.
9963 static bool isQualifiedMemberAccess(Expr *E) {
9964 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9965 if (!DRE->getQualifier())
9968 ValueDecl *VD = DRE->getDecl();
9969 if (!VD->isCXXClassMember())
9972 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9974 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9975 return Method->isInstance();
9980 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9981 if (!ULE->getQualifier())
9984 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9985 DEnd = ULE->decls_end();
9987 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9988 if (Method->isInstance())
9991 // Overload set does not contain methods.
10002 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10003 UnaryOperatorKind Opc, Expr *Input) {
10004 // First things first: handle placeholders so that the
10005 // overloaded-operator check considers the right type.
10006 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10007 // Increment and decrement of pseudo-object references.
10008 if (pty->getKind() == BuiltinType::PseudoObject &&
10009 UnaryOperator::isIncrementDecrementOp(Opc))
10010 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10012 // extension is always a builtin operator.
10013 if (Opc == UO_Extension)
10014 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10016 // & gets special logic for several kinds of placeholder.
10017 // The builtin code knows what to do.
10018 if (Opc == UO_AddrOf &&
10019 (pty->getKind() == BuiltinType::Overload ||
10020 pty->getKind() == BuiltinType::UnknownAny ||
10021 pty->getKind() == BuiltinType::BoundMember))
10022 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10024 // Anything else needs to be handled now.
10025 ExprResult Result = CheckPlaceholderExpr(Input);
10026 if (Result.isInvalid()) return ExprError();
10027 Input = Result.get();
10030 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10031 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10032 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10033 // Find all of the overloaded operators visible from this
10034 // point. We perform both an operator-name lookup from the local
10035 // scope and an argument-dependent lookup based on the types of
10037 UnresolvedSet<16> Functions;
10038 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10039 if (S && OverOp != OO_None)
10040 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10043 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10046 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10049 // Unary Operators. 'Tok' is the token for the operator.
10050 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10051 tok::TokenKind Op, Expr *Input) {
10052 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10055 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
10056 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10057 LabelDecl *TheDecl) {
10058 TheDecl->markUsed(Context);
10059 // Create the AST node. The address of a label always has type 'void*'.
10060 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10061 Context.getPointerType(Context.VoidTy));
10064 /// Given the last statement in a statement-expression, check whether
10065 /// the result is a producing expression (like a call to an
10066 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10067 /// release out of the full-expression. Otherwise, return null.
10069 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10070 // Should always be wrapped with one of these.
10071 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10072 if (!cleanups) return nullptr;
10074 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10075 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10078 // Splice out the cast. This shouldn't modify any interesting
10079 // features of the statement.
10080 Expr *producer = cast->getSubExpr();
10081 assert(producer->getType() == cast->getType());
10082 assert(producer->getValueKind() == cast->getValueKind());
10083 cleanups->setSubExpr(producer);
10087 void Sema::ActOnStartStmtExpr() {
10088 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10091 void Sema::ActOnStmtExprError() {
10092 // Note that function is also called by TreeTransform when leaving a
10093 // StmtExpr scope without rebuilding anything.
10095 DiscardCleanupsInEvaluationContext();
10096 PopExpressionEvaluationContext();
10100 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10101 SourceLocation RPLoc) { // "({..})"
10102 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10103 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10105 if (hasAnyUnrecoverableErrorsInThisFunction())
10106 DiscardCleanupsInEvaluationContext();
10107 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10108 PopExpressionEvaluationContext();
10111 = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10113 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10115 // FIXME: there are a variety of strange constraints to enforce here, for
10116 // example, it is not possible to goto into a stmt expression apparently.
10117 // More semantic analysis is needed.
10119 // If there are sub-stmts in the compound stmt, take the type of the last one
10120 // as the type of the stmtexpr.
10121 QualType Ty = Context.VoidTy;
10122 bool StmtExprMayBindToTemp = false;
10123 if (!Compound->body_empty()) {
10124 Stmt *LastStmt = Compound->body_back();
10125 LabelStmt *LastLabelStmt = nullptr;
10126 // If LastStmt is a label, skip down through into the body.
10127 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10128 LastLabelStmt = Label;
10129 LastStmt = Label->getSubStmt();
10132 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10133 // Do function/array conversion on the last expression, but not
10134 // lvalue-to-rvalue. However, initialize an unqualified type.
10135 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10136 if (LastExpr.isInvalid())
10137 return ExprError();
10138 Ty = LastExpr.get()->getType().getUnqualifiedType();
10140 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10141 // In ARC, if the final expression ends in a consume, splice
10142 // the consume out and bind it later. In the alternate case
10143 // (when dealing with a retainable type), the result
10144 // initialization will create a produce. In both cases the
10145 // result will be +1, and we'll need to balance that out with
10147 if (Expr *rebuiltLastStmt
10148 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10149 LastExpr = rebuiltLastStmt;
10151 LastExpr = PerformCopyInitialization(
10152 InitializedEntity::InitializeResult(LPLoc,
10159 if (LastExpr.isInvalid())
10160 return ExprError();
10161 if (LastExpr.get() != nullptr) {
10162 if (!LastLabelStmt)
10163 Compound->setLastStmt(LastExpr.get());
10165 LastLabelStmt->setSubStmt(LastExpr.get());
10166 StmtExprMayBindToTemp = true;
10172 // FIXME: Check that expression type is complete/non-abstract; statement
10173 // expressions are not lvalues.
10174 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10175 if (StmtExprMayBindToTemp)
10176 return MaybeBindToTemporary(ResStmtExpr);
10177 return ResStmtExpr;
10180 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10181 TypeSourceInfo *TInfo,
10182 OffsetOfComponent *CompPtr,
10183 unsigned NumComponents,
10184 SourceLocation RParenLoc) {
10185 QualType ArgTy = TInfo->getType();
10186 bool Dependent = ArgTy->isDependentType();
10187 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10189 // We must have at least one component that refers to the type, and the first
10190 // one is known to be a field designator. Verify that the ArgTy represents
10191 // a struct/union/class.
10192 if (!Dependent && !ArgTy->isRecordType())
10193 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10194 << ArgTy << TypeRange);
10196 // Type must be complete per C99 7.17p3 because a declaring a variable
10197 // with an incomplete type would be ill-formed.
10199 && RequireCompleteType(BuiltinLoc, ArgTy,
10200 diag::err_offsetof_incomplete_type, TypeRange))
10201 return ExprError();
10203 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10204 // GCC extension, diagnose them.
10205 // FIXME: This diagnostic isn't actually visible because the location is in
10206 // a system header!
10207 if (NumComponents != 1)
10208 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10209 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10211 bool DidWarnAboutNonPOD = false;
10212 QualType CurrentType = ArgTy;
10213 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10214 SmallVector<OffsetOfNode, 4> Comps;
10215 SmallVector<Expr*, 4> Exprs;
10216 for (unsigned i = 0; i != NumComponents; ++i) {
10217 const OffsetOfComponent &OC = CompPtr[i];
10218 if (OC.isBrackets) {
10219 // Offset of an array sub-field. TODO: Should we allow vector elements?
10220 if (!CurrentType->isDependentType()) {
10221 const ArrayType *AT = Context.getAsArrayType(CurrentType);
10223 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10225 CurrentType = AT->getElementType();
10227 CurrentType = Context.DependentTy;
10229 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10230 if (IdxRval.isInvalid())
10231 return ExprError();
10232 Expr *Idx = IdxRval.get();
10234 // The expression must be an integral expression.
10235 // FIXME: An integral constant expression?
10236 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10237 !Idx->getType()->isIntegerType())
10238 return ExprError(Diag(Idx->getLocStart(),
10239 diag::err_typecheck_subscript_not_integer)
10240 << Idx->getSourceRange());
10242 // Record this array index.
10243 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10244 Exprs.push_back(Idx);
10248 // Offset of a field.
10249 if (CurrentType->isDependentType()) {
10250 // We have the offset of a field, but we can't look into the dependent
10251 // type. Just record the identifier of the field.
10252 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10253 CurrentType = Context.DependentTy;
10257 // We need to have a complete type to look into.
10258 if (RequireCompleteType(OC.LocStart, CurrentType,
10259 diag::err_offsetof_incomplete_type))
10260 return ExprError();
10262 // Look for the designated field.
10263 const RecordType *RC = CurrentType->getAs<RecordType>();
10265 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10267 RecordDecl *RD = RC->getDecl();
10269 // C++ [lib.support.types]p5:
10270 // The macro offsetof accepts a restricted set of type arguments in this
10271 // International Standard. type shall be a POD structure or a POD union
10273 // C++11 [support.types]p4:
10274 // If type is not a standard-layout class (Clause 9), the results are
10276 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10277 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10279 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
10280 : diag::ext_offsetof_non_pod_type;
10282 if (!IsSafe && !DidWarnAboutNonPOD &&
10283 DiagRuntimeBehavior(BuiltinLoc, nullptr,
10285 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10287 DidWarnAboutNonPOD = true;
10290 // Look for the field.
10291 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10292 LookupQualifiedName(R, RD);
10293 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10294 IndirectFieldDecl *IndirectMemberDecl = nullptr;
10296 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10297 MemberDecl = IndirectMemberDecl->getAnonField();
10301 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10302 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10306 // (If the specified member is a bit-field, the behavior is undefined.)
10308 // We diagnose this as an error.
10309 if (MemberDecl->isBitField()) {
10310 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10311 << MemberDecl->getDeclName()
10312 << SourceRange(BuiltinLoc, RParenLoc);
10313 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10314 return ExprError();
10317 RecordDecl *Parent = MemberDecl->getParent();
10318 if (IndirectMemberDecl)
10319 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10321 // If the member was found in a base class, introduce OffsetOfNodes for
10322 // the base class indirections.
10323 CXXBasePaths Paths;
10324 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10325 if (Paths.getDetectedVirtual()) {
10326 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10327 << MemberDecl->getDeclName()
10328 << SourceRange(BuiltinLoc, RParenLoc);
10329 return ExprError();
10332 CXXBasePath &Path = Paths.front();
10333 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10335 Comps.push_back(OffsetOfNode(B->Base));
10338 if (IndirectMemberDecl) {
10339 for (auto *FI : IndirectMemberDecl->chain()) {
10340 assert(isa<FieldDecl>(FI));
10341 Comps.push_back(OffsetOfNode(OC.LocStart,
10342 cast<FieldDecl>(FI), OC.LocEnd));
10345 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10347 CurrentType = MemberDecl->getType().getNonReferenceType();
10350 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10351 Comps, Exprs, RParenLoc);
10354 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10355 SourceLocation BuiltinLoc,
10356 SourceLocation TypeLoc,
10357 ParsedType ParsedArgTy,
10358 OffsetOfComponent *CompPtr,
10359 unsigned NumComponents,
10360 SourceLocation RParenLoc) {
10362 TypeSourceInfo *ArgTInfo;
10363 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10364 if (ArgTy.isNull())
10365 return ExprError();
10368 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10370 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10375 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10377 Expr *LHSExpr, Expr *RHSExpr,
10378 SourceLocation RPLoc) {
10379 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10381 ExprValueKind VK = VK_RValue;
10382 ExprObjectKind OK = OK_Ordinary;
10384 bool ValueDependent = false;
10385 bool CondIsTrue = false;
10386 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10387 resType = Context.DependentTy;
10388 ValueDependent = true;
10390 // The conditional expression is required to be a constant expression.
10391 llvm::APSInt condEval(32);
10393 = VerifyIntegerConstantExpression(CondExpr, &condEval,
10394 diag::err_typecheck_choose_expr_requires_constant, false);
10395 if (CondICE.isInvalid())
10396 return ExprError();
10397 CondExpr = CondICE.get();
10398 CondIsTrue = condEval.getZExtValue();
10400 // If the condition is > zero, then the AST type is the same as the LSHExpr.
10401 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10403 resType = ActiveExpr->getType();
10404 ValueDependent = ActiveExpr->isValueDependent();
10405 VK = ActiveExpr->getValueKind();
10406 OK = ActiveExpr->getObjectKind();
10409 return new (Context)
10410 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10411 CondIsTrue, resType->isDependentType(), ValueDependent);
10414 //===----------------------------------------------------------------------===//
10415 // Clang Extensions.
10416 //===----------------------------------------------------------------------===//
10418 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10419 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10420 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10422 if (LangOpts.CPlusPlus) {
10423 Decl *ManglingContextDecl;
10424 if (MangleNumberingContext *MCtx =
10425 getCurrentMangleNumberContext(Block->getDeclContext(),
10426 ManglingContextDecl)) {
10427 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10428 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10432 PushBlockScope(CurScope, Block);
10433 CurContext->addDecl(Block);
10435 PushDeclContext(CurScope, Block);
10437 CurContext = Block;
10439 getCurBlock()->HasImplicitReturnType = true;
10441 // Enter a new evaluation context to insulate the block from any
10442 // cleanups from the enclosing full-expression.
10443 PushExpressionEvaluationContext(PotentiallyEvaluated);
10446 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10448 assert(ParamInfo.getIdentifier() == nullptr &&
10449 "block-id should have no identifier!");
10450 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10451 BlockScopeInfo *CurBlock = getCurBlock();
10453 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10454 QualType T = Sig->getType();
10456 // FIXME: We should allow unexpanded parameter packs here, but that would,
10457 // in turn, make the block expression contain unexpanded parameter packs.
10458 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10459 // Drop the parameters.
10460 FunctionProtoType::ExtProtoInfo EPI;
10461 EPI.HasTrailingReturn = false;
10462 EPI.TypeQuals |= DeclSpec::TQ_const;
10463 T = Context.getFunctionType(Context.DependentTy, None, EPI);
10464 Sig = Context.getTrivialTypeSourceInfo(T);
10467 // GetTypeForDeclarator always produces a function type for a block
10468 // literal signature. Furthermore, it is always a FunctionProtoType
10469 // unless the function was written with a typedef.
10470 assert(T->isFunctionType() &&
10471 "GetTypeForDeclarator made a non-function block signature");
10473 // Look for an explicit signature in that function type.
10474 FunctionProtoTypeLoc ExplicitSignature;
10476 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10477 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10479 // Check whether that explicit signature was synthesized by
10480 // GetTypeForDeclarator. If so, don't save that as part of the
10481 // written signature.
10482 if (ExplicitSignature.getLocalRangeBegin() ==
10483 ExplicitSignature.getLocalRangeEnd()) {
10484 // This would be much cheaper if we stored TypeLocs instead of
10485 // TypeSourceInfos.
10486 TypeLoc Result = ExplicitSignature.getReturnLoc();
10487 unsigned Size = Result.getFullDataSize();
10488 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10489 Sig->getTypeLoc().initializeFullCopy(Result, Size);
10491 ExplicitSignature = FunctionProtoTypeLoc();
10495 CurBlock->TheDecl->setSignatureAsWritten(Sig);
10496 CurBlock->FunctionType = T;
10498 const FunctionType *Fn = T->getAs<FunctionType>();
10499 QualType RetTy = Fn->getReturnType();
10501 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10503 CurBlock->TheDecl->setIsVariadic(isVariadic);
10505 // Context.DependentTy is used as a placeholder for a missing block
10506 // return type. TODO: what should we do with declarators like:
10508 // If the answer is "apply template argument deduction"....
10509 if (RetTy != Context.DependentTy) {
10510 CurBlock->ReturnType = RetTy;
10511 CurBlock->TheDecl->setBlockMissingReturnType(false);
10512 CurBlock->HasImplicitReturnType = false;
10515 // Push block parameters from the declarator if we had them.
10516 SmallVector<ParmVarDecl*, 8> Params;
10517 if (ExplicitSignature) {
10518 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10519 ParmVarDecl *Param = ExplicitSignature.getParam(I);
10520 if (Param->getIdentifier() == nullptr &&
10521 !Param->isImplicit() &&
10522 !Param->isInvalidDecl() &&
10523 !getLangOpts().CPlusPlus)
10524 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10525 Params.push_back(Param);
10528 // Fake up parameter variables if we have a typedef, like
10529 // ^ fntype { ... }
10530 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10531 for (const auto &I : Fn->param_types()) {
10532 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10533 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10534 Params.push_back(Param);
10538 // Set the parameters on the block decl.
10539 if (!Params.empty()) {
10540 CurBlock->TheDecl->setParams(Params);
10541 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10542 CurBlock->TheDecl->param_end(),
10543 /*CheckParameterNames=*/false);
10546 // Finally we can process decl attributes.
10547 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10549 // Put the parameter variables in scope.
10550 for (auto AI : CurBlock->TheDecl->params()) {
10551 AI->setOwningFunction(CurBlock->TheDecl);
10553 // If this has an identifier, add it to the scope stack.
10554 if (AI->getIdentifier()) {
10555 CheckShadow(CurBlock->TheScope, AI);
10557 PushOnScopeChains(AI, CurBlock->TheScope);
10562 /// ActOnBlockError - If there is an error parsing a block, this callback
10563 /// is invoked to pop the information about the block from the action impl.
10564 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10565 // Leave the expression-evaluation context.
10566 DiscardCleanupsInEvaluationContext();
10567 PopExpressionEvaluationContext();
10569 // Pop off CurBlock, handle nested blocks.
10571 PopFunctionScopeInfo();
10574 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10575 /// literal was successfully completed. ^(int x){...}
10576 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10577 Stmt *Body, Scope *CurScope) {
10578 // If blocks are disabled, emit an error.
10579 if (!LangOpts.Blocks)
10580 Diag(CaretLoc, diag::err_blocks_disable);
10582 // Leave the expression-evaluation context.
10583 if (hasAnyUnrecoverableErrorsInThisFunction())
10584 DiscardCleanupsInEvaluationContext();
10585 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10586 PopExpressionEvaluationContext();
10588 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10590 if (BSI->HasImplicitReturnType)
10591 deduceClosureReturnType(*BSI);
10595 QualType RetTy = Context.VoidTy;
10596 if (!BSI->ReturnType.isNull())
10597 RetTy = BSI->ReturnType;
10599 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10602 // Set the captured variables on the block.
10603 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10604 SmallVector<BlockDecl::Capture, 4> Captures;
10605 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10606 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10607 if (Cap.isThisCapture())
10609 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10610 Cap.isNested(), Cap.getInitExpr());
10611 Captures.push_back(NewCap);
10613 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10614 BSI->CXXThisCaptureIndex != 0);
10616 // If the user wrote a function type in some form, try to use that.
10617 if (!BSI->FunctionType.isNull()) {
10618 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10620 FunctionType::ExtInfo Ext = FTy->getExtInfo();
10621 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10623 // Turn protoless block types into nullary block types.
10624 if (isa<FunctionNoProtoType>(FTy)) {
10625 FunctionProtoType::ExtProtoInfo EPI;
10627 BlockTy = Context.getFunctionType(RetTy, None, EPI);
10629 // Otherwise, if we don't need to change anything about the function type,
10630 // preserve its sugar structure.
10631 } else if (FTy->getReturnType() == RetTy &&
10632 (!NoReturn || FTy->getNoReturnAttr())) {
10633 BlockTy = BSI->FunctionType;
10635 // Otherwise, make the minimal modifications to the function type.
10637 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10638 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10639 EPI.TypeQuals = 0; // FIXME: silently?
10641 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10644 // If we don't have a function type, just build one from nothing.
10646 FunctionProtoType::ExtProtoInfo EPI;
10647 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10648 BlockTy = Context.getFunctionType(RetTy, None, EPI);
10651 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10652 BSI->TheDecl->param_end());
10653 BlockTy = Context.getBlockPointerType(BlockTy);
10655 // If needed, diagnose invalid gotos and switches in the block.
10656 if (getCurFunction()->NeedsScopeChecking() &&
10657 !PP.isCodeCompletionEnabled())
10658 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10660 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10662 // Try to apply the named return value optimization. We have to check again
10663 // if we can do this, though, because blocks keep return statements around
10664 // to deduce an implicit return type.
10665 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10666 !BSI->TheDecl->isDependentContext())
10667 computeNRVO(Body, BSI);
10669 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10670 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10671 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10673 // If the block isn't obviously global, i.e. it captures anything at
10674 // all, then we need to do a few things in the surrounding context:
10675 if (Result->getBlockDecl()->hasCaptures()) {
10676 // First, this expression has a new cleanup object.
10677 ExprCleanupObjects.push_back(Result->getBlockDecl());
10678 ExprNeedsCleanups = true;
10680 // It also gets a branch-protected scope if any of the captured
10681 // variables needs destruction.
10682 for (const auto &CI : Result->getBlockDecl()->captures()) {
10683 const VarDecl *var = CI.getVariable();
10684 if (var->getType().isDestructedType() != QualType::DK_none) {
10685 getCurFunction()->setHasBranchProtectedScope();
10694 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10695 Expr *E, ParsedType Ty,
10696 SourceLocation RPLoc) {
10697 TypeSourceInfo *TInfo;
10698 GetTypeFromParser(Ty, &TInfo);
10699 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10702 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10703 Expr *E, TypeSourceInfo *TInfo,
10704 SourceLocation RPLoc) {
10705 Expr *OrigExpr = E;
10707 // Get the va_list type
10708 QualType VaListType = Context.getBuiltinVaListType();
10709 if (VaListType->isArrayType()) {
10710 // Deal with implicit array decay; for example, on x86-64,
10711 // va_list is an array, but it's supposed to decay to
10712 // a pointer for va_arg.
10713 VaListType = Context.getArrayDecayedType(VaListType);
10714 // Make sure the input expression also decays appropriately.
10715 ExprResult Result = UsualUnaryConversions(E);
10716 if (Result.isInvalid())
10717 return ExprError();
10719 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10720 // If va_list is a record type and we are compiling in C++ mode,
10721 // check the argument using reference binding.
10722 InitializedEntity Entity
10723 = InitializedEntity::InitializeParameter(Context,
10724 Context.getLValueReferenceType(VaListType), false);
10725 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10726 if (Init.isInvalid())
10727 return ExprError();
10728 E = Init.getAs<Expr>();
10730 // Otherwise, the va_list argument must be an l-value because
10731 // it is modified by va_arg.
10732 if (!E->isTypeDependent() &&
10733 CheckForModifiableLvalue(E, BuiltinLoc, *this))
10734 return ExprError();
10737 if (!E->isTypeDependent() &&
10738 !Context.hasSameType(VaListType, E->getType())) {
10739 return ExprError(Diag(E->getLocStart(),
10740 diag::err_first_argument_to_va_arg_not_of_type_va_list)
10741 << OrigExpr->getType() << E->getSourceRange());
10744 if (!TInfo->getType()->isDependentType()) {
10745 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10746 diag::err_second_parameter_to_va_arg_incomplete,
10747 TInfo->getTypeLoc()))
10748 return ExprError();
10750 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10752 diag::err_second_parameter_to_va_arg_abstract,
10753 TInfo->getTypeLoc()))
10754 return ExprError();
10756 if (!TInfo->getType().isPODType(Context)) {
10757 Diag(TInfo->getTypeLoc().getBeginLoc(),
10758 TInfo->getType()->isObjCLifetimeType()
10759 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10760 : diag::warn_second_parameter_to_va_arg_not_pod)
10761 << TInfo->getType()
10762 << TInfo->getTypeLoc().getSourceRange();
10765 // Check for va_arg where arguments of the given type will be promoted
10766 // (i.e. this va_arg is guaranteed to have undefined behavior).
10767 QualType PromoteType;
10768 if (TInfo->getType()->isPromotableIntegerType()) {
10769 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10770 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10771 PromoteType = QualType();
10773 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10774 PromoteType = Context.DoubleTy;
10775 if (!PromoteType.isNull())
10776 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10777 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10778 << TInfo->getType()
10780 << TInfo->getTypeLoc().getSourceRange());
10783 QualType T = TInfo->getType().getNonLValueExprType(Context);
10784 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10787 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10788 // The type of __null will be int or long, depending on the size of
10789 // pointers on the target.
10791 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10792 if (pw == Context.getTargetInfo().getIntWidth())
10793 Ty = Context.IntTy;
10794 else if (pw == Context.getTargetInfo().getLongWidth())
10795 Ty = Context.LongTy;
10796 else if (pw == Context.getTargetInfo().getLongLongWidth())
10797 Ty = Context.LongLongTy;
10799 llvm_unreachable("I don't know size of pointer!");
10802 return new (Context) GNUNullExpr(Ty, TokenLoc);
10806 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10807 if (!getLangOpts().ObjC1)
10810 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10814 if (!PT->isObjCIdType()) {
10815 // Check if the destination is the 'NSString' interface.
10816 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10817 if (!ID || !ID->getIdentifier()->isStr("NSString"))
10821 // Ignore any parens, implicit casts (should only be
10822 // array-to-pointer decays), and not-so-opaque values. The last is
10823 // important for making this trigger for property assignments.
10824 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10825 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10826 if (OV->getSourceExpr())
10827 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10829 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10830 if (!SL || !SL->isAscii())
10832 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10833 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10834 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10838 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10839 SourceLocation Loc,
10840 QualType DstType, QualType SrcType,
10841 Expr *SrcExpr, AssignmentAction Action,
10842 bool *Complained) {
10844 *Complained = false;
10846 // Decode the result (notice that AST's are still created for extensions).
10847 bool CheckInferredResultType = false;
10848 bool isInvalid = false;
10849 unsigned DiagKind = 0;
10851 ConversionFixItGenerator ConvHints;
10852 bool MayHaveConvFixit = false;
10853 bool MayHaveFunctionDiff = false;
10854 const ObjCInterfaceDecl *IFace = nullptr;
10855 const ObjCProtocolDecl *PDecl = nullptr;
10859 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10863 DiagKind = diag::ext_typecheck_convert_pointer_int;
10864 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10865 MayHaveConvFixit = true;
10868 DiagKind = diag::ext_typecheck_convert_int_pointer;
10869 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10870 MayHaveConvFixit = true;
10872 case IncompatiblePointer:
10874 (Action == AA_Passing_CFAudited ?
10875 diag::err_arc_typecheck_convert_incompatible_pointer :
10876 diag::ext_typecheck_convert_incompatible_pointer);
10877 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10878 SrcType->isObjCObjectPointerType();
10879 if (Hint.isNull() && !CheckInferredResultType) {
10880 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10882 else if (CheckInferredResultType) {
10883 SrcType = SrcType.getUnqualifiedType();
10884 DstType = DstType.getUnqualifiedType();
10886 MayHaveConvFixit = true;
10888 case IncompatiblePointerSign:
10889 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10891 case FunctionVoidPointer:
10892 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10894 case IncompatiblePointerDiscardsQualifiers: {
10895 // Perform array-to-pointer decay if necessary.
10896 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10898 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10899 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10900 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10901 DiagKind = diag::err_typecheck_incompatible_address_space;
10905 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10906 DiagKind = diag::err_typecheck_incompatible_ownership;
10910 llvm_unreachable("unknown error case for discarding qualifiers!");
10913 case CompatiblePointerDiscardsQualifiers:
10914 // If the qualifiers lost were because we were applying the
10915 // (deprecated) C++ conversion from a string literal to a char*
10916 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
10917 // Ideally, this check would be performed in
10918 // checkPointerTypesForAssignment. However, that would require a
10919 // bit of refactoring (so that the second argument is an
10920 // expression, rather than a type), which should be done as part
10921 // of a larger effort to fix checkPointerTypesForAssignment for
10923 if (getLangOpts().CPlusPlus &&
10924 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10926 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10928 case IncompatibleNestedPointerQualifiers:
10929 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10931 case IntToBlockPointer:
10932 DiagKind = diag::err_int_to_block_pointer;
10934 case IncompatibleBlockPointer:
10935 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10937 case IncompatibleObjCQualifiedId: {
10938 if (SrcType->isObjCQualifiedIdType()) {
10939 const ObjCObjectPointerType *srcOPT =
10940 SrcType->getAs<ObjCObjectPointerType>();
10941 for (auto *srcProto : srcOPT->quals()) {
10945 if (const ObjCInterfaceType *IFaceT =
10946 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10947 IFace = IFaceT->getDecl();
10949 else if (DstType->isObjCQualifiedIdType()) {
10950 const ObjCObjectPointerType *dstOPT =
10951 DstType->getAs<ObjCObjectPointerType>();
10952 for (auto *dstProto : dstOPT->quals()) {
10956 if (const ObjCInterfaceType *IFaceT =
10957 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10958 IFace = IFaceT->getDecl();
10960 DiagKind = diag::warn_incompatible_qualified_id;
10963 case IncompatibleVectors:
10964 DiagKind = diag::warn_incompatible_vectors;
10966 case IncompatibleObjCWeakRef:
10967 DiagKind = diag::err_arc_weak_unavailable_assign;
10970 DiagKind = diag::err_typecheck_convert_incompatible;
10971 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10972 MayHaveConvFixit = true;
10974 MayHaveFunctionDiff = true;
10978 QualType FirstType, SecondType;
10981 case AA_Initializing:
10982 // The destination type comes first.
10983 FirstType = DstType;
10984 SecondType = SrcType;
10989 case AA_Passing_CFAudited:
10990 case AA_Converting:
10993 // The source type comes first.
10994 FirstType = SrcType;
10995 SecondType = DstType;
10999 PartialDiagnostic FDiag = PDiag(DiagKind);
11000 if (Action == AA_Passing_CFAudited)
11001 FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
11003 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11005 // If we can fix the conversion, suggest the FixIts.
11006 assert(ConvHints.isNull() || Hint.isNull());
11007 if (!ConvHints.isNull()) {
11008 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11009 HE = ConvHints.Hints.end(); HI != HE; ++HI)
11014 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11016 if (MayHaveFunctionDiff)
11017 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11020 if (DiagKind == diag::warn_incompatible_qualified_id &&
11021 PDecl && IFace && !IFace->hasDefinition())
11022 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11023 << IFace->getName() << PDecl->getName();
11025 if (SecondType == Context.OverloadTy)
11026 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11029 if (CheckInferredResultType)
11030 EmitRelatedResultTypeNote(SrcExpr);
11032 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11033 EmitRelatedResultTypeNoteForReturn(DstType);
11036 *Complained = true;
11040 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11041 llvm::APSInt *Result) {
11042 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11044 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11045 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11049 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11052 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11053 llvm::APSInt *Result,
11056 class IDDiagnoser : public VerifyICEDiagnoser {
11060 IDDiagnoser(unsigned DiagID)
11061 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11063 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11064 S.Diag(Loc, DiagID) << SR;
11066 } Diagnoser(DiagID);
11068 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11071 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11073 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11077 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11078 VerifyICEDiagnoser &Diagnoser,
11080 SourceLocation DiagLoc = E->getLocStart();
11082 if (getLangOpts().CPlusPlus11) {
11083 // C++11 [expr.const]p5:
11084 // If an expression of literal class type is used in a context where an
11085 // integral constant expression is required, then that class type shall
11086 // have a single non-explicit conversion function to an integral or
11087 // unscoped enumeration type
11088 ExprResult Converted;
11089 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11091 CXX11ConvertDiagnoser(bool Silent)
11092 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11095 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11096 QualType T) override {
11097 return S.Diag(Loc, diag::err_ice_not_integral) << T;
11100 SemaDiagnosticBuilder diagnoseIncomplete(
11101 Sema &S, SourceLocation Loc, QualType T) override {
11102 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11105 SemaDiagnosticBuilder diagnoseExplicitConv(
11106 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11107 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11110 SemaDiagnosticBuilder noteExplicitConv(
11111 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11112 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11113 << ConvTy->isEnumeralType() << ConvTy;
11116 SemaDiagnosticBuilder diagnoseAmbiguous(
11117 Sema &S, SourceLocation Loc, QualType T) override {
11118 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11121 SemaDiagnosticBuilder noteAmbiguous(
11122 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11123 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11124 << ConvTy->isEnumeralType() << ConvTy;
11127 SemaDiagnosticBuilder diagnoseConversion(
11128 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11129 llvm_unreachable("conversion functions are permitted");
11131 } ConvertDiagnoser(Diagnoser.Suppress);
11133 Converted = PerformContextualImplicitConversion(DiagLoc, E,
11135 if (Converted.isInvalid())
11137 E = Converted.get();
11138 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11139 return ExprError();
11140 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11141 // An ICE must be of integral or unscoped enumeration type.
11142 if (!Diagnoser.Suppress)
11143 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11144 return ExprError();
11147 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11148 // in the non-ICE case.
11149 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11151 *Result = E->EvaluateKnownConstInt(Context);
11155 Expr::EvalResult EvalResult;
11156 SmallVector<PartialDiagnosticAt, 8> Notes;
11157 EvalResult.Diag = &Notes;
11159 // Try to evaluate the expression, and produce diagnostics explaining why it's
11160 // not a constant expression as a side-effect.
11161 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11162 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11164 // In C++11, we can rely on diagnostics being produced for any expression
11165 // which is not a constant expression. If no diagnostics were produced, then
11166 // this is a constant expression.
11167 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11169 *Result = EvalResult.Val.getInt();
11173 // If our only note is the usual "invalid subexpression" note, just point
11174 // the caret at its location rather than producing an essentially
11176 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11177 diag::note_invalid_subexpr_in_const_expr) {
11178 DiagLoc = Notes[0].first;
11182 if (!Folded || !AllowFold) {
11183 if (!Diagnoser.Suppress) {
11184 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11185 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11186 Diag(Notes[I].first, Notes[I].second);
11189 return ExprError();
11192 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11193 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11194 Diag(Notes[I].first, Notes[I].second);
11197 *Result = EvalResult.Val.getInt();
11202 // Handle the case where we conclude a expression which we speculatively
11203 // considered to be unevaluated is actually evaluated.
11204 class TransformToPE : public TreeTransform<TransformToPE> {
11205 typedef TreeTransform<TransformToPE> BaseTransform;
11208 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11210 // Make sure we redo semantic analysis
11211 bool AlwaysRebuild() { return true; }
11213 // Make sure we handle LabelStmts correctly.
11214 // FIXME: This does the right thing, but maybe we need a more general
11215 // fix to TreeTransform?
11216 StmtResult TransformLabelStmt(LabelStmt *S) {
11217 S->getDecl()->setStmt(nullptr);
11218 return BaseTransform::TransformLabelStmt(S);
11221 // We need to special-case DeclRefExprs referring to FieldDecls which
11222 // are not part of a member pointer formation; normal TreeTransforming
11223 // doesn't catch this case because of the way we represent them in the AST.
11224 // FIXME: This is a bit ugly; is it really the best way to handle this
11227 // Error on DeclRefExprs referring to FieldDecls.
11228 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11229 if (isa<FieldDecl>(E->getDecl()) &&
11230 !SemaRef.isUnevaluatedContext())
11231 return SemaRef.Diag(E->getLocation(),
11232 diag::err_invalid_non_static_member_use)
11233 << E->getDecl() << E->getSourceRange();
11235 return BaseTransform::TransformDeclRefExpr(E);
11238 // Exception: filter out member pointer formation
11239 ExprResult TransformUnaryOperator(UnaryOperator *E) {
11240 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11243 return BaseTransform::TransformUnaryOperator(E);
11246 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11247 // Lambdas never need to be transformed.
11253 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11254 assert(isUnevaluatedContext() &&
11255 "Should only transform unevaluated expressions");
11256 ExprEvalContexts.back().Context =
11257 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11258 if (isUnevaluatedContext())
11260 return TransformToPE(*this).TransformExpr(E);
11264 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11265 Decl *LambdaContextDecl,
11267 ExprEvalContexts.push_back(
11268 ExpressionEvaluationContextRecord(NewContext,
11269 ExprCleanupObjects.size(),
11273 ExprNeedsCleanups = false;
11274 if (!MaybeODRUseExprs.empty())
11275 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11279 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11280 ReuseLambdaContextDecl_t,
11282 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11283 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11286 void Sema::PopExpressionEvaluationContext() {
11287 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11289 if (!Rec.Lambdas.empty()) {
11290 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11292 if (Rec.isUnevaluated()) {
11293 // C++11 [expr.prim.lambda]p2:
11294 // A lambda-expression shall not appear in an unevaluated operand
11296 D = diag::err_lambda_unevaluated_operand;
11298 // C++1y [expr.const]p2:
11299 // A conditional-expression e is a core constant expression unless the
11300 // evaluation of e, following the rules of the abstract machine, would
11301 // evaluate [...] a lambda-expression.
11302 D = diag::err_lambda_in_constant_expression;
11304 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11305 Diag(Rec.Lambdas[I]->getLocStart(), D);
11307 // Mark the capture expressions odr-used. This was deferred
11308 // during lambda expression creation.
11309 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11310 LambdaExpr *Lambda = Rec.Lambdas[I];
11311 for (LambdaExpr::capture_init_iterator
11312 C = Lambda->capture_init_begin(),
11313 CEnd = Lambda->capture_init_end();
11315 MarkDeclarationsReferencedInExpr(*C);
11321 // When are coming out of an unevaluated context, clear out any
11322 // temporaries that we may have created as part of the evaluation of
11323 // the expression in that context: they aren't relevant because they
11324 // will never be constructed.
11325 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11326 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11327 ExprCleanupObjects.end());
11328 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11329 CleanupVarDeclMarking();
11330 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11331 // Otherwise, merge the contexts together.
11333 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11334 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11335 Rec.SavedMaybeODRUseExprs.end());
11338 // Pop the current expression evaluation context off the stack.
11339 ExprEvalContexts.pop_back();
11342 void Sema::DiscardCleanupsInEvaluationContext() {
11343 ExprCleanupObjects.erase(
11344 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11345 ExprCleanupObjects.end());
11346 ExprNeedsCleanups = false;
11347 MaybeODRUseExprs.clear();
11350 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11351 if (!E->getType()->isVariablyModifiedType())
11353 return TransformToPotentiallyEvaluated(E);
11356 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11357 // Do not mark anything as "used" within a dependent context; wait for
11358 // an instantiation.
11359 if (SemaRef.CurContext->isDependentContext())
11362 switch (SemaRef.ExprEvalContexts.back().Context) {
11363 case Sema::Unevaluated:
11364 case Sema::UnevaluatedAbstract:
11365 // We are in an expression that is not potentially evaluated; do nothing.
11366 // (Depending on how you read the standard, we actually do need to do
11367 // something here for null pointer constants, but the standard's
11368 // definition of a null pointer constant is completely crazy.)
11371 case Sema::ConstantEvaluated:
11372 case Sema::PotentiallyEvaluated:
11373 // We are in a potentially evaluated expression (or a constant-expression
11374 // in C++03); we need to do implicit template instantiation, implicitly
11375 // define class members, and mark most declarations as used.
11378 case Sema::PotentiallyEvaluatedIfUsed:
11379 // Referenced declarations will only be used if the construct in the
11380 // containing expression is used.
11383 llvm_unreachable("Invalid context");
11386 /// \brief Mark a function referenced, and check whether it is odr-used
11387 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11388 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11389 assert(Func && "No function?");
11391 Func->setReferenced();
11393 // C++11 [basic.def.odr]p3:
11394 // A function whose name appears as a potentially-evaluated expression is
11395 // odr-used if it is the unique lookup result or the selected member of a
11396 // set of overloaded functions [...].
11398 // We (incorrectly) mark overload resolution as an unevaluated context, so we
11399 // can just check that here. Skip the rest of this function if we've already
11400 // marked the function as used.
11401 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11402 // C++11 [temp.inst]p3:
11403 // Unless a function template specialization has been explicitly
11404 // instantiated or explicitly specialized, the function template
11405 // specialization is implicitly instantiated when the specialization is
11406 // referenced in a context that requires a function definition to exist.
11408 // We consider constexpr function templates to be referenced in a context
11409 // that requires a definition to exist whenever they are referenced.
11411 // FIXME: This instantiates constexpr functions too frequently. If this is
11412 // really an unevaluated context (and we're not just in the definition of a
11413 // function template or overload resolution or other cases which we
11414 // incorrectly consider to be unevaluated contexts), and we're not in a
11415 // subexpression which we actually need to evaluate (for instance, a
11416 // template argument, array bound or an expression in a braced-init-list),
11417 // we are not permitted to instantiate this constexpr function definition.
11419 // FIXME: This also implicitly defines special members too frequently. They
11420 // are only supposed to be implicitly defined if they are odr-used, but they
11421 // are not odr-used from constant expressions in unevaluated contexts.
11422 // However, they cannot be referenced if they are deleted, and they are
11423 // deleted whenever the implicit definition of the special member would
11425 if (!Func->isConstexpr() || Func->getBody())
11427 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11428 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11432 // Note that this declaration has been used.
11433 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11434 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11435 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11436 if (Constructor->isDefaultConstructor()) {
11437 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11439 DefineImplicitDefaultConstructor(Loc, Constructor);
11440 } else if (Constructor->isCopyConstructor()) {
11441 DefineImplicitCopyConstructor(Loc, Constructor);
11442 } else if (Constructor->isMoveConstructor()) {
11443 DefineImplicitMoveConstructor(Loc, Constructor);
11445 } else if (Constructor->getInheritedConstructor()) {
11446 DefineInheritingConstructor(Loc, Constructor);
11448 } else if (CXXDestructorDecl *Destructor =
11449 dyn_cast<CXXDestructorDecl>(Func)) {
11450 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11451 if (Destructor->isDefaulted() && !Destructor->isDeleted())
11452 DefineImplicitDestructor(Loc, Destructor);
11453 if (Destructor->isVirtual())
11454 MarkVTableUsed(Loc, Destructor->getParent());
11455 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11456 if (MethodDecl->isOverloadedOperator() &&
11457 MethodDecl->getOverloadedOperator() == OO_Equal) {
11458 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11459 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11460 if (MethodDecl->isCopyAssignmentOperator())
11461 DefineImplicitCopyAssignment(Loc, MethodDecl);
11463 DefineImplicitMoveAssignment(Loc, MethodDecl);
11465 } else if (isa<CXXConversionDecl>(MethodDecl) &&
11466 MethodDecl->getParent()->isLambda()) {
11467 CXXConversionDecl *Conversion =
11468 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11469 if (Conversion->isLambdaToBlockPointerConversion())
11470 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11472 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11473 } else if (MethodDecl->isVirtual())
11474 MarkVTableUsed(Loc, MethodDecl->getParent());
11477 // Recursive functions should be marked when used from another function.
11478 // FIXME: Is this really right?
11479 if (CurContext == Func) return;
11481 // Resolve the exception specification for any function which is
11482 // used: CodeGen will need it.
11483 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11484 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11485 ResolveExceptionSpec(Loc, FPT);
11487 // Implicit instantiation of function templates and member functions of
11488 // class templates.
11489 if (Func->isImplicitlyInstantiable()) {
11490 bool AlreadyInstantiated = false;
11491 SourceLocation PointOfInstantiation = Loc;
11492 if (FunctionTemplateSpecializationInfo *SpecInfo
11493 = Func->getTemplateSpecializationInfo()) {
11494 if (SpecInfo->getPointOfInstantiation().isInvalid())
11495 SpecInfo->setPointOfInstantiation(Loc);
11496 else if (SpecInfo->getTemplateSpecializationKind()
11497 == TSK_ImplicitInstantiation) {
11498 AlreadyInstantiated = true;
11499 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11501 } else if (MemberSpecializationInfo *MSInfo
11502 = Func->getMemberSpecializationInfo()) {
11503 if (MSInfo->getPointOfInstantiation().isInvalid())
11504 MSInfo->setPointOfInstantiation(Loc);
11505 else if (MSInfo->getTemplateSpecializationKind()
11506 == TSK_ImplicitInstantiation) {
11507 AlreadyInstantiated = true;
11508 PointOfInstantiation = MSInfo->getPointOfInstantiation();
11512 if (!AlreadyInstantiated || Func->isConstexpr()) {
11513 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11514 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11515 ActiveTemplateInstantiations.size())
11516 PendingLocalImplicitInstantiations.push_back(
11517 std::make_pair(Func, PointOfInstantiation));
11518 else if (Func->isConstexpr())
11519 // Do not defer instantiations of constexpr functions, to avoid the
11520 // expression evaluator needing to call back into Sema if it sees a
11521 // call to such a function.
11522 InstantiateFunctionDefinition(PointOfInstantiation, Func);
11524 PendingInstantiations.push_back(std::make_pair(Func,
11525 PointOfInstantiation));
11526 // Notify the consumer that a function was implicitly instantiated.
11527 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11531 // Walk redefinitions, as some of them may be instantiable.
11532 for (auto i : Func->redecls()) {
11533 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11534 MarkFunctionReferenced(Loc, i);
11538 // Keep track of used but undefined functions.
11539 if (!Func->isDefined()) {
11540 if (mightHaveNonExternalLinkage(Func))
11541 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11542 else if (Func->getMostRecentDecl()->isInlined() &&
11543 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11544 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11545 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11548 // Normally the most current decl is marked used while processing the use and
11549 // any subsequent decls are marked used by decl merging. This fails with
11550 // template instantiation since marking can happen at the end of the file
11551 // and, because of the two phase lookup, this function is called with at
11552 // decl in the middle of a decl chain. We loop to maintain the invariant
11553 // that once a decl is used, all decls after it are also used.
11554 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11555 F->markUsed(Context);
11562 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11563 VarDecl *var, DeclContext *DC) {
11564 DeclContext *VarDC = var->getDeclContext();
11566 // If the parameter still belongs to the translation unit, then
11567 // we're actually just using one parameter in the declaration of
11569 if (isa<ParmVarDecl>(var) &&
11570 isa<TranslationUnitDecl>(VarDC))
11573 // For C code, don't diagnose about capture if we're not actually in code
11574 // right now; it's impossible to write a non-constant expression outside of
11575 // function context, so we'll get other (more useful) diagnostics later.
11577 // For C++, things get a bit more nasty... it would be nice to suppress this
11578 // diagnostic for certain cases like using a local variable in an array bound
11579 // for a member of a local class, but the correct predicate is not obvious.
11580 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11583 if (isa<CXXMethodDecl>(VarDC) &&
11584 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11585 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11586 << var->getIdentifier();
11587 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11588 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11589 << var->getIdentifier() << fn->getDeclName();
11590 } else if (isa<BlockDecl>(VarDC)) {
11591 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11592 << var->getIdentifier();
11594 // FIXME: Is there any other context where a local variable can be
11596 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11597 << var->getIdentifier();
11600 S.Diag(var->getLocation(), diag::note_entity_declared_at)
11601 << var->getIdentifier();
11603 // FIXME: Add additional diagnostic info about class etc. which prevents
11608 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11609 bool &SubCapturesAreNested,
11610 QualType &CaptureType,
11611 QualType &DeclRefType) {
11612 // Check whether we've already captured it.
11613 if (CSI->CaptureMap.count(Var)) {
11614 // If we found a capture, any subcaptures are nested.
11615 SubCapturesAreNested = true;
11617 // Retrieve the capture type for this variable.
11618 CaptureType = CSI->getCapture(Var).getCaptureType();
11620 // Compute the type of an expression that refers to this variable.
11621 DeclRefType = CaptureType.getNonReferenceType();
11623 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11624 if (Cap.isCopyCapture() &&
11625 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11626 DeclRefType.addConst();
11632 // Only block literals, captured statements, and lambda expressions can
11633 // capture; other scopes don't work.
11634 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11635 SourceLocation Loc,
11636 const bool Diagnose, Sema &S) {
11637 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11638 return getLambdaAwareParentOfDeclContext(DC);
11641 diagnoseUncapturableValueReference(S, Loc, Var, DC);
11646 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11647 // certain types of variables (unnamed, variably modified types etc.)
11648 // so check for eligibility.
11649 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11650 SourceLocation Loc,
11651 const bool Diagnose, Sema &S) {
11653 bool IsBlock = isa<BlockScopeInfo>(CSI);
11654 bool IsLambda = isa<LambdaScopeInfo>(CSI);
11656 // Lambdas are not allowed to capture unnamed variables
11657 // (e.g. anonymous unions).
11658 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11659 // assuming that's the intent.
11660 if (IsLambda && !Var->getDeclName()) {
11662 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11663 S.Diag(Var->getLocation(), diag::note_declared_at);
11668 // Prohibit variably-modified types; they're difficult to deal with.
11669 if (Var->getType()->isVariablyModifiedType() && (IsBlock || IsLambda)) {
11672 S.Diag(Loc, diag::err_ref_vm_type);
11674 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11675 S.Diag(Var->getLocation(), diag::note_previous_decl)
11676 << Var->getDeclName();
11680 // Prohibit structs with flexible array members too.
11681 // We cannot capture what is in the tail end of the struct.
11682 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11683 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11686 S.Diag(Loc, diag::err_ref_flexarray_type);
11688 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11689 << Var->getDeclName();
11690 S.Diag(Var->getLocation(), diag::note_previous_decl)
11691 << Var->getDeclName();
11696 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11697 // Lambdas and captured statements are not allowed to capture __block
11698 // variables; they don't support the expected semantics.
11699 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11701 S.Diag(Loc, diag::err_capture_block_variable)
11702 << Var->getDeclName() << !IsLambda;
11703 S.Diag(Var->getLocation(), diag::note_previous_decl)
11704 << Var->getDeclName();
11712 // Returns true if the capture by block was successful.
11713 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11714 SourceLocation Loc,
11715 const bool BuildAndDiagnose,
11716 QualType &CaptureType,
11717 QualType &DeclRefType,
11720 Expr *CopyExpr = nullptr;
11721 bool ByRef = false;
11723 // Blocks are not allowed to capture arrays.
11724 if (CaptureType->isArrayType()) {
11725 if (BuildAndDiagnose) {
11726 S.Diag(Loc, diag::err_ref_array_type);
11727 S.Diag(Var->getLocation(), diag::note_previous_decl)
11728 << Var->getDeclName();
11733 // Forbid the block-capture of autoreleasing variables.
11734 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11735 if (BuildAndDiagnose) {
11736 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11738 S.Diag(Var->getLocation(), diag::note_previous_decl)
11739 << Var->getDeclName();
11743 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11744 if (HasBlocksAttr || CaptureType->isReferenceType()) {
11745 // Block capture by reference does not change the capture or
11746 // declaration reference types.
11749 // Block capture by copy introduces 'const'.
11750 CaptureType = CaptureType.getNonReferenceType().withConst();
11751 DeclRefType = CaptureType;
11753 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11754 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11755 // The capture logic needs the destructor, so make sure we mark it.
11756 // Usually this is unnecessary because most local variables have
11757 // their destructors marked at declaration time, but parameters are
11758 // an exception because it's technically only the call site that
11759 // actually requires the destructor.
11760 if (isa<ParmVarDecl>(Var))
11761 S.FinalizeVarWithDestructor(Var, Record);
11763 // Enter a new evaluation context to insulate the copy
11764 // full-expression.
11765 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11767 // According to the blocks spec, the capture of a variable from
11768 // the stack requires a const copy constructor. This is not true
11769 // of the copy/move done to move a __block variable to the heap.
11770 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11771 DeclRefType.withConst(),
11775 = S.PerformCopyInitialization(
11776 InitializedEntity::InitializeBlock(Var->getLocation(),
11777 CaptureType, false),
11780 // Build a full-expression copy expression if initialization
11781 // succeeded and used a non-trivial constructor. Recover from
11782 // errors by pretending that the copy isn't necessary.
11783 if (!Result.isInvalid() &&
11784 !cast<CXXConstructExpr>(Result.get())->getConstructor()
11786 Result = S.MaybeCreateExprWithCleanups(Result);
11787 CopyExpr = Result.get();
11793 // Actually capture the variable.
11794 if (BuildAndDiagnose)
11795 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11796 SourceLocation(), CaptureType, CopyExpr);
11803 /// \brief Capture the given variable in the captured region.
11804 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11806 SourceLocation Loc,
11807 const bool BuildAndDiagnose,
11808 QualType &CaptureType,
11809 QualType &DeclRefType,
11810 const bool RefersToEnclosingLocal,
11813 // By default, capture variables by reference.
11815 // Using an LValue reference type is consistent with Lambdas (see below).
11816 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11817 Expr *CopyExpr = nullptr;
11818 if (BuildAndDiagnose) {
11819 // The current implementation assumes that all variables are captured
11820 // by references. Since there is no capture by copy, no expression
11821 // evaluation will be needed.
11822 RecordDecl *RD = RSI->TheRecordDecl;
11825 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11826 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11827 nullptr, false, ICIS_NoInit);
11828 Field->setImplicit(true);
11829 Field->setAccess(AS_private);
11830 RD->addDecl(Field);
11832 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11833 DeclRefType, VK_LValue, Loc);
11834 Var->setReferenced(true);
11835 Var->markUsed(S.Context);
11838 // Actually capture the variable.
11839 if (BuildAndDiagnose)
11840 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11841 SourceLocation(), CaptureType, CopyExpr);
11847 /// \brief Create a field within the lambda class for the variable
11848 /// being captured. Handle Array captures.
11849 static ExprResult addAsFieldToClosureType(Sema &S,
11850 LambdaScopeInfo *LSI,
11851 VarDecl *Var, QualType FieldType,
11852 QualType DeclRefType,
11853 SourceLocation Loc,
11854 bool RefersToEnclosingLocal) {
11855 CXXRecordDecl *Lambda = LSI->Lambda;
11857 // Build the non-static data member.
11859 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
11860 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11861 nullptr, false, ICIS_NoInit);
11862 Field->setImplicit(true);
11863 Field->setAccess(AS_private);
11864 Lambda->addDecl(Field);
11866 // C++11 [expr.prim.lambda]p21:
11867 // When the lambda-expression is evaluated, the entities that
11868 // are captured by copy are used to direct-initialize each
11869 // corresponding non-static data member of the resulting closure
11870 // object. (For array members, the array elements are
11871 // direct-initialized in increasing subscript order.) These
11872 // initializations are performed in the (unspecified) order in
11873 // which the non-static data members are declared.
11875 // Introduce a new evaluation context for the initialization, so
11876 // that temporaries introduced as part of the capture are retained
11877 // to be re-"exported" from the lambda expression itself.
11878 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11880 // C++ [expr.prim.labda]p12:
11881 // An entity captured by a lambda-expression is odr-used (3.2) in
11882 // the scope containing the lambda-expression.
11883 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11884 DeclRefType, VK_LValue, Loc);
11885 Var->setReferenced(true);
11886 Var->markUsed(S.Context);
11888 // When the field has array type, create index variables for each
11889 // dimension of the array. We use these index variables to subscript
11890 // the source array, and other clients (e.g., CodeGen) will perform
11891 // the necessary iteration with these index variables.
11892 SmallVector<VarDecl *, 4> IndexVariables;
11893 QualType BaseType = FieldType;
11894 QualType SizeType = S.Context.getSizeType();
11895 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11896 while (const ConstantArrayType *Array
11897 = S.Context.getAsConstantArrayType(BaseType)) {
11898 // Create the iteration variable for this array index.
11899 IdentifierInfo *IterationVarName = nullptr;
11901 SmallString<8> Str;
11902 llvm::raw_svector_ostream OS(Str);
11903 OS << "__i" << IndexVariables.size();
11904 IterationVarName = &S.Context.Idents.get(OS.str());
11906 VarDecl *IterationVar
11907 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11908 IterationVarName, SizeType,
11909 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11911 IndexVariables.push_back(IterationVar);
11912 LSI->ArrayIndexVars.push_back(IterationVar);
11914 // Create a reference to the iteration variable.
11915 ExprResult IterationVarRef
11916 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11917 assert(!IterationVarRef.isInvalid() &&
11918 "Reference to invented variable cannot fail!");
11919 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
11920 assert(!IterationVarRef.isInvalid() &&
11921 "Conversion of invented variable cannot fail!");
11923 // Subscript the array with this iteration variable.
11924 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11925 Ref, Loc, IterationVarRef.get(), Loc);
11926 if (Subscript.isInvalid()) {
11927 S.CleanupVarDeclMarking();
11928 S.DiscardCleanupsInEvaluationContext();
11929 return ExprError();
11932 Ref = Subscript.get();
11933 BaseType = Array->getElementType();
11936 // Construct the entity that we will be initializing. For an array, this
11937 // will be first element in the array, which may require several levels
11938 // of array-subscript entities.
11939 SmallVector<InitializedEntity, 4> Entities;
11940 Entities.reserve(1 + IndexVariables.size());
11941 Entities.push_back(
11942 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11943 Field->getType(), Loc));
11944 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11945 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11949 InitializationKind InitKind
11950 = InitializationKind::CreateDirect(Loc, Loc, Loc);
11951 InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11952 ExprResult Result(true);
11953 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11954 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11956 // If this initialization requires any cleanups (e.g., due to a
11957 // default argument to a copy constructor), note that for the
11959 if (S.ExprNeedsCleanups)
11960 LSI->ExprNeedsCleanups = true;
11962 // Exit the expression evaluation context used for the capture.
11963 S.CleanupVarDeclMarking();
11964 S.DiscardCleanupsInEvaluationContext();
11970 /// \brief Capture the given variable in the lambda.
11971 static bool captureInLambda(LambdaScopeInfo *LSI,
11973 SourceLocation Loc,
11974 const bool BuildAndDiagnose,
11975 QualType &CaptureType,
11976 QualType &DeclRefType,
11977 const bool RefersToEnclosingLocal,
11978 const Sema::TryCaptureKind Kind,
11979 SourceLocation EllipsisLoc,
11980 const bool IsTopScope,
11983 // Determine whether we are capturing by reference or by value.
11984 bool ByRef = false;
11985 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11986 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11988 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11991 // Compute the type of the field that will capture this variable.
11993 // C++11 [expr.prim.lambda]p15:
11994 // An entity is captured by reference if it is implicitly or
11995 // explicitly captured but not captured by copy. It is
11996 // unspecified whether additional unnamed non-static data
11997 // members are declared in the closure type for entities
11998 // captured by reference.
12000 // FIXME: It is not clear whether we want to build an lvalue reference
12001 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12002 // to do the former, while EDG does the latter. Core issue 1249 will
12003 // clarify, but for now we follow GCC because it's a more permissive and
12004 // easily defensible position.
12005 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12007 // C++11 [expr.prim.lambda]p14:
12008 // For each entity captured by copy, an unnamed non-static
12009 // data member is declared in the closure type. The
12010 // declaration order of these members is unspecified. The type
12011 // of such a data member is the type of the corresponding
12012 // captured entity if the entity is not a reference to an
12013 // object, or the referenced type otherwise. [Note: If the
12014 // captured entity is a reference to a function, the
12015 // corresponding data member is also a reference to a
12016 // function. - end note ]
12017 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12018 if (!RefType->getPointeeType()->isFunctionType())
12019 CaptureType = RefType->getPointeeType();
12022 // Forbid the lambda copy-capture of autoreleasing variables.
12023 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12024 if (BuildAndDiagnose) {
12025 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12026 S.Diag(Var->getLocation(), diag::note_previous_decl)
12027 << Var->getDeclName();
12032 // Make sure that by-copy captures are of a complete and non-abstract type.
12033 if (BuildAndDiagnose) {
12034 if (!CaptureType->isDependentType() &&
12035 S.RequireCompleteType(Loc, CaptureType,
12036 diag::err_capture_of_incomplete_type,
12037 Var->getDeclName()))
12040 if (S.RequireNonAbstractType(Loc, CaptureType,
12041 diag::err_capture_of_abstract_type))
12046 // Capture this variable in the lambda.
12047 Expr *CopyExpr = nullptr;
12048 if (BuildAndDiagnose) {
12049 ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12050 CaptureType, DeclRefType, Loc,
12051 RefersToEnclosingLocal);
12052 if (!Result.isInvalid())
12053 CopyExpr = Result.get();
12056 // Compute the type of a reference to this captured variable.
12058 DeclRefType = CaptureType.getNonReferenceType();
12060 // C++ [expr.prim.lambda]p5:
12061 // The closure type for a lambda-expression has a public inline
12062 // function call operator [...]. This function call operator is
12063 // declared const (9.3.1) if and only if the lambda-expression’s
12064 // parameter-declaration-clause is not followed by mutable.
12065 DeclRefType = CaptureType.getNonReferenceType();
12066 if (!LSI->Mutable && !CaptureType->isReferenceType())
12067 DeclRefType.addConst();
12070 // Add the capture.
12071 if (BuildAndDiagnose)
12072 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
12073 Loc, EllipsisLoc, CaptureType, CopyExpr);
12079 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
12080 TryCaptureKind Kind, SourceLocation EllipsisLoc,
12081 bool BuildAndDiagnose,
12082 QualType &CaptureType,
12083 QualType &DeclRefType,
12084 const unsigned *const FunctionScopeIndexToStopAt) {
12085 bool Nested = false;
12087 DeclContext *DC = CurContext;
12088 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12089 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12090 // We need to sync up the Declaration Context with the
12091 // FunctionScopeIndexToStopAt
12092 if (FunctionScopeIndexToStopAt) {
12093 unsigned FSIndex = FunctionScopes.size() - 1;
12094 while (FSIndex != MaxFunctionScopesIndex) {
12095 DC = getLambdaAwareParentOfDeclContext(DC);
12101 // If the variable is declared in the current context (and is not an
12102 // init-capture), there is no need to capture it.
12103 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
12104 if (!Var->hasLocalStorage()) return true;
12106 // Walk up the stack to determine whether we can capture the variable,
12107 // performing the "simple" checks that don't depend on type. We stop when
12108 // we've either hit the declared scope of the variable or find an existing
12109 // capture of that variable. We start from the innermost capturing-entity
12110 // (the DC) and ensure that all intervening capturing-entities
12111 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12112 // declcontext can either capture the variable or have already captured
12114 CaptureType = Var->getType();
12115 DeclRefType = CaptureType.getNonReferenceType();
12116 bool Explicit = (Kind != TryCapture_Implicit);
12117 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12119 // Only block literals, captured statements, and lambda expressions can
12120 // capture; other scopes don't work.
12121 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12125 if (!ParentDC) return true;
12127 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
12128 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12131 // Check whether we've already captured it.
12132 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12135 // If we are instantiating a generic lambda call operator body,
12136 // we do not want to capture new variables. What was captured
12137 // during either a lambdas transformation or initial parsing
12139 if (isGenericLambdaCallOperatorSpecialization(DC)) {
12140 if (BuildAndDiagnose) {
12141 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12142 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12143 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12144 Diag(Var->getLocation(), diag::note_previous_decl)
12145 << Var->getDeclName();
12146 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12148 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12152 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12153 // certain types of variables (unnamed, variably modified types etc.)
12154 // so check for eligibility.
12155 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12158 // Try to capture variable-length arrays types.
12159 if (Var->getType()->isVariablyModifiedType()) {
12160 // We're going to walk down into the type and look for VLA
12162 QualType QTy = Var->getType();
12163 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12164 QTy = PVD->getOriginalType();
12166 const Type *Ty = QTy.getTypePtr();
12167 switch (Ty->getTypeClass()) {
12168 #define TYPE(Class, Base)
12169 #define ABSTRACT_TYPE(Class, Base)
12170 #define NON_CANONICAL_TYPE(Class, Base)
12171 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
12172 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12173 #include "clang/AST/TypeNodes.def"
12176 // These types are never variably-modified.
12177 case Type::Builtin:
12178 case Type::Complex:
12180 case Type::ExtVector:
12183 case Type::Elaborated:
12184 case Type::TemplateSpecialization:
12185 case Type::ObjCObject:
12186 case Type::ObjCInterface:
12187 case Type::ObjCObjectPointer:
12188 llvm_unreachable("type class is never variably-modified!");
12189 case Type::Adjusted:
12190 QTy = cast<AdjustedType>(Ty)->getOriginalType();
12192 case Type::Decayed:
12193 QTy = cast<DecayedType>(Ty)->getPointeeType();
12195 case Type::Pointer:
12196 QTy = cast<PointerType>(Ty)->getPointeeType();
12198 case Type::BlockPointer:
12199 QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12201 case Type::LValueReference:
12202 case Type::RValueReference:
12203 QTy = cast<ReferenceType>(Ty)->getPointeeType();
12205 case Type::MemberPointer:
12206 QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12208 case Type::ConstantArray:
12209 case Type::IncompleteArray:
12210 // Losing element qualification here is fine.
12211 QTy = cast<ArrayType>(Ty)->getElementType();
12213 case Type::VariableArray: {
12214 // Losing element qualification here is fine.
12215 const VariableArrayType *Vat = cast<VariableArrayType>(Ty);
12217 // Unknown size indication requires no size computation.
12218 // Otherwise, evaluate and record it.
12219 if (Expr *Size = Vat->getSizeExpr()) {
12220 MarkDeclarationsReferencedInExpr(Size);
12222 QTy = Vat->getElementType();
12225 case Type::FunctionProto:
12226 case Type::FunctionNoProto:
12227 QTy = cast<FunctionType>(Ty)->getReturnType();
12231 case Type::UnaryTransform:
12232 case Type::Attributed:
12233 case Type::SubstTemplateTypeParm:
12234 case Type::PackExpansion:
12235 // Keep walking after single level desugaring.
12236 QTy = QTy.getSingleStepDesugaredType(getASTContext());
12238 case Type::Typedef:
12239 QTy = cast<TypedefType>(Ty)->desugar();
12241 case Type::Decltype:
12242 QTy = cast<DecltypeType>(Ty)->desugar();
12245 QTy = cast<AutoType>(Ty)->getDeducedType();
12247 case Type::TypeOfExpr:
12248 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12251 QTy = cast<AtomicType>(Ty)->getValueType();
12254 } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12257 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12258 // No capture-default, and this is not an explicit capture
12259 // so cannot capture this variable.
12260 if (BuildAndDiagnose) {
12261 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12262 Diag(Var->getLocation(), diag::note_previous_decl)
12263 << Var->getDeclName();
12264 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12265 diag::note_lambda_decl);
12266 // FIXME: If we error out because an outer lambda can not implicitly
12267 // capture a variable that an inner lambda explicitly captures, we
12268 // should have the inner lambda do the explicit capture - because
12269 // it makes for cleaner diagnostics later. This would purely be done
12270 // so that the diagnostic does not misleadingly claim that a variable
12271 // can not be captured by a lambda implicitly even though it is captured
12272 // explicitly. Suggestion:
12273 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12274 // at the function head
12275 // - cache the StartingDeclContext - this must be a lambda
12276 // - captureInLambda in the innermost lambda the variable.
12281 FunctionScopesIndex--;
12284 } while (!Var->getDeclContext()->Equals(DC));
12286 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12287 // computing the type of the capture at each step, checking type-specific
12288 // requirements, and adding captures if requested.
12289 // If the variable had already been captured previously, we start capturing
12290 // at the lambda nested within that one.
12291 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12293 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12295 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12296 if (!captureInBlock(BSI, Var, ExprLoc,
12297 BuildAndDiagnose, CaptureType,
12298 DeclRefType, Nested, *this))
12301 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12302 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12303 BuildAndDiagnose, CaptureType,
12304 DeclRefType, Nested, *this))
12308 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12309 if (!captureInLambda(LSI, Var, ExprLoc,
12310 BuildAndDiagnose, CaptureType,
12311 DeclRefType, Nested, Kind, EllipsisLoc,
12312 /*IsTopScope*/I == N - 1, *this))
12320 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12321 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12322 QualType CaptureType;
12323 QualType DeclRefType;
12324 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12325 /*BuildAndDiagnose=*/true, CaptureType,
12326 DeclRefType, nullptr);
12329 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12330 QualType CaptureType;
12331 QualType DeclRefType;
12333 // Determine whether we can capture this variable.
12334 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12335 /*BuildAndDiagnose=*/false, CaptureType,
12336 DeclRefType, nullptr))
12339 return DeclRefType;
12344 // If either the type of the variable or the initializer is dependent,
12345 // return false. Otherwise, determine whether the variable is a constant
12346 // expression. Use this if you need to know if a variable that might or
12347 // might not be dependent is truly a constant expression.
12348 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12349 ASTContext &Context) {
12351 if (Var->getType()->isDependentType())
12353 const VarDecl *DefVD = nullptr;
12354 Var->getAnyInitializer(DefVD);
12357 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12358 Expr *Init = cast<Expr>(Eval->Value);
12359 if (Init->isValueDependent())
12361 return IsVariableAConstantExpression(Var, Context);
12365 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12366 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12367 // an object that satisfies the requirements for appearing in a
12368 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12369 // is immediately applied." This function handles the lvalue-to-rvalue
12370 // conversion part.
12371 MaybeODRUseExprs.erase(E->IgnoreParens());
12373 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12374 // to a variable that is a constant expression, and if so, identify it as
12375 // a reference to a variable that does not involve an odr-use of that
12377 if (LambdaScopeInfo *LSI = getCurLambda()) {
12378 Expr *SansParensExpr = E->IgnoreParens();
12379 VarDecl *Var = nullptr;
12380 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12381 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12382 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12383 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12385 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12386 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12390 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12391 if (!Res.isUsable())
12394 // If a constant-expression is a reference to a variable where we delay
12395 // deciding whether it is an odr-use, just assume we will apply the
12396 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
12397 // (a non-type template argument), we have special handling anyway.
12398 UpdateMarkingForLValueToRValue(Res.get());
12402 void Sema::CleanupVarDeclMarking() {
12403 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12404 e = MaybeODRUseExprs.end();
12407 SourceLocation Loc;
12408 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12409 Var = cast<VarDecl>(DRE->getDecl());
12410 Loc = DRE->getLocation();
12411 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12412 Var = cast<VarDecl>(ME->getMemberDecl());
12413 Loc = ME->getMemberLoc();
12415 llvm_unreachable("Unexpcted expression");
12418 MarkVarDeclODRUsed(Var, Loc, *this,
12419 /*MaxFunctionScopeIndex Pointer*/ nullptr);
12422 MaybeODRUseExprs.clear();
12426 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12427 VarDecl *Var, Expr *E) {
12428 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12429 "Invalid Expr argument to DoMarkVarDeclReferenced");
12430 Var->setReferenced();
12432 // If the context is not potentially evaluated, this is not an odr-use and
12433 // does not trigger instantiation.
12434 if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12435 if (SemaRef.isUnevaluatedContext())
12438 // If we don't yet know whether this context is going to end up being an
12439 // evaluated context, and we're referencing a variable from an enclosing
12440 // scope, add a potential capture.
12442 // FIXME: Is this necessary? These contexts are only used for default
12443 // arguments, where local variables can't be used.
12444 const bool RefersToEnclosingScope =
12445 (SemaRef.CurContext != Var->getDeclContext() &&
12446 Var->getDeclContext()->isFunctionOrMethod() &&
12447 Var->hasLocalStorage());
12448 if (!RefersToEnclosingScope)
12451 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12452 // If a variable could potentially be odr-used, defer marking it so
12453 // until we finish analyzing the full expression for any lvalue-to-rvalue
12454 // or discarded value conversions that would obviate odr-use.
12455 // Add it to the list of potential captures that will be analyzed
12456 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12457 // unless the variable is a reference that was initialized by a constant
12458 // expression (this will never need to be captured or odr-used).
12459 assert(E && "Capture variable should be used in an expression.");
12460 if (!Var->getType()->isReferenceType() ||
12461 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12462 LSI->addPotentialCapture(E->IgnoreParens());
12467 VarTemplateSpecializationDecl *VarSpec =
12468 dyn_cast<VarTemplateSpecializationDecl>(Var);
12469 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12470 "Can't instantiate a partial template specialization.");
12472 // Perform implicit instantiation of static data members, static data member
12473 // templates of class templates, and variable template specializations. Delay
12474 // instantiations of variable templates, except for those that could be used
12475 // in a constant expression.
12476 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12477 if (isTemplateInstantiation(TSK)) {
12478 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12480 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12481 if (Var->getPointOfInstantiation().isInvalid()) {
12482 // This is a modification of an existing AST node. Notify listeners.
12483 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12484 L->StaticDataMemberInstantiated(Var);
12485 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12486 // Don't bother trying to instantiate it again, unless we might need
12487 // its initializer before we get to the end of the TU.
12488 TryInstantiating = false;
12491 if (Var->getPointOfInstantiation().isInvalid())
12492 Var->setTemplateSpecializationKind(TSK, Loc);
12494 if (TryInstantiating) {
12495 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12496 bool InstantiationDependent = false;
12497 bool IsNonDependent =
12498 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12499 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12502 // Do not instantiate specializations that are still type-dependent.
12503 if (IsNonDependent) {
12504 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12505 // Do not defer instantiations of variables which could be used in a
12506 // constant expression.
12507 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12509 SemaRef.PendingInstantiations
12510 .push_back(std::make_pair(Var, PointOfInstantiation));
12516 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12517 // the requirements for appearing in a constant expression (5.19) and, if
12518 // it is an object, the lvalue-to-rvalue conversion (4.1)
12519 // is immediately applied." We check the first part here, and
12520 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12521 // Note that we use the C++11 definition everywhere because nothing in
12522 // C++03 depends on whether we get the C++03 version correct. The second
12523 // part does not apply to references, since they are not objects.
12524 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12525 // A reference initialized by a constant expression can never be
12526 // odr-used, so simply ignore it.
12527 if (!Var->getType()->isReferenceType())
12528 SemaRef.MaybeODRUseExprs.insert(E);
12530 MarkVarDeclODRUsed(Var, Loc, SemaRef,
12531 /*MaxFunctionScopeIndex ptr*/ nullptr);
12534 /// \brief Mark a variable referenced, and check whether it is odr-used
12535 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
12536 /// used directly for normal expressions referring to VarDecl.
12537 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12538 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12541 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12542 Decl *D, Expr *E, bool OdrUse) {
12543 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12544 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12548 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12550 // If this is a call to a method via a cast, also mark the method in the
12551 // derived class used in case codegen can devirtualize the call.
12552 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12555 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12558 const Expr *Base = ME->getBase();
12559 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12560 if (!MostDerivedClassDecl)
12562 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12563 if (!DM || DM->isPure())
12565 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12568 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12569 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12570 // TODO: update this with DR# once a defect report is filed.
12571 // C++11 defect. The address of a pure member should not be an ODR use, even
12572 // if it's a qualified reference.
12573 bool OdrUse = true;
12574 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12575 if (Method->isVirtual())
12577 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12580 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12581 void Sema::MarkMemberReferenced(MemberExpr *E) {
12582 // C++11 [basic.def.odr]p2:
12583 // A non-overloaded function whose name appears as a potentially-evaluated
12584 // expression or a member of a set of candidate functions, if selected by
12585 // overload resolution when referred to from a potentially-evaluated
12586 // expression, is odr-used, unless it is a pure virtual function and its
12587 // name is not explicitly qualified.
12588 bool OdrUse = true;
12589 if (!E->hasQualifier()) {
12590 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12591 if (Method->isPure())
12594 SourceLocation Loc = E->getMemberLoc().isValid() ?
12595 E->getMemberLoc() : E->getLocStart();
12596 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12599 /// \brief Perform marking for a reference to an arbitrary declaration. It
12600 /// marks the declaration referenced, and performs odr-use checking for
12601 /// functions and variables. This method should not be used when building a
12602 /// normal expression which refers to a variable.
12603 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12605 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12606 MarkVariableReferenced(Loc, VD);
12609 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12610 MarkFunctionReferenced(Loc, FD);
12614 D->setReferenced();
12618 // Mark all of the declarations referenced
12619 // FIXME: Not fully implemented yet! We need to have a better understanding
12620 // of when we're entering
12621 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12623 SourceLocation Loc;
12626 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12628 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12630 bool TraverseTemplateArgument(const TemplateArgument &Arg);
12631 bool TraverseRecordType(RecordType *T);
12635 bool MarkReferencedDecls::TraverseTemplateArgument(
12636 const TemplateArgument &Arg) {
12637 if (Arg.getKind() == TemplateArgument::Declaration) {
12638 if (Decl *D = Arg.getAsDecl())
12639 S.MarkAnyDeclReferenced(Loc, D, true);
12642 return Inherited::TraverseTemplateArgument(Arg);
12645 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12646 if (ClassTemplateSpecializationDecl *Spec
12647 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12648 const TemplateArgumentList &Args = Spec->getTemplateArgs();
12649 return TraverseTemplateArguments(Args.data(), Args.size());
12655 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12656 MarkReferencedDecls Marker(*this, Loc);
12657 Marker.TraverseType(Context.getCanonicalType(T));
12661 /// \brief Helper class that marks all of the declarations referenced by
12662 /// potentially-evaluated subexpressions as "referenced".
12663 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12665 bool SkipLocalVariables;
12668 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12670 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12671 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12673 void VisitDeclRefExpr(DeclRefExpr *E) {
12674 // If we were asked not to visit local variables, don't.
12675 if (SkipLocalVariables) {
12676 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12677 if (VD->hasLocalStorage())
12681 S.MarkDeclRefReferenced(E);
12684 void VisitMemberExpr(MemberExpr *E) {
12685 S.MarkMemberReferenced(E);
12686 Inherited::VisitMemberExpr(E);
12689 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12690 S.MarkFunctionReferenced(E->getLocStart(),
12691 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12692 Visit(E->getSubExpr());
12695 void VisitCXXNewExpr(CXXNewExpr *E) {
12696 if (E->getOperatorNew())
12697 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12698 if (E->getOperatorDelete())
12699 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12700 Inherited::VisitCXXNewExpr(E);
12703 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12704 if (E->getOperatorDelete())
12705 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12706 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12707 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12708 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12709 S.MarkFunctionReferenced(E->getLocStart(),
12710 S.LookupDestructor(Record));
12713 Inherited::VisitCXXDeleteExpr(E);
12716 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12717 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12718 Inherited::VisitCXXConstructExpr(E);
12721 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12722 Visit(E->getExpr());
12725 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12726 Inherited::VisitImplicitCastExpr(E);
12728 if (E->getCastKind() == CK_LValueToRValue)
12729 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12734 /// \brief Mark any declarations that appear within this expression or any
12735 /// potentially-evaluated subexpressions as "referenced".
12737 /// \param SkipLocalVariables If true, don't mark local variables as
12739 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12740 bool SkipLocalVariables) {
12741 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12744 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12745 /// of the program being compiled.
12747 /// This routine emits the given diagnostic when the code currently being
12748 /// type-checked is "potentially evaluated", meaning that there is a
12749 /// possibility that the code will actually be executable. Code in sizeof()
12750 /// expressions, code used only during overload resolution, etc., are not
12751 /// potentially evaluated. This routine will suppress such diagnostics or,
12752 /// in the absolutely nutty case of potentially potentially evaluated
12753 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12756 /// This routine should be used for all diagnostics that describe the run-time
12757 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12758 /// Failure to do so will likely result in spurious diagnostics or failures
12759 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12760 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12761 const PartialDiagnostic &PD) {
12762 switch (ExprEvalContexts.back().Context) {
12764 case UnevaluatedAbstract:
12765 // The argument will never be evaluated, so don't complain.
12768 case ConstantEvaluated:
12769 // Relevant diagnostics should be produced by constant evaluation.
12772 case PotentiallyEvaluated:
12773 case PotentiallyEvaluatedIfUsed:
12774 if (Statement && getCurFunctionOrMethodDecl()) {
12775 FunctionScopes.back()->PossiblyUnreachableDiags.
12776 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12787 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12788 CallExpr *CE, FunctionDecl *FD) {
12789 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12792 // If we're inside a decltype's expression, don't check for a valid return
12793 // type or construct temporaries until we know whether this is the last call.
12794 if (ExprEvalContexts.back().IsDecltype) {
12795 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12799 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12804 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12805 : FD(FD), CE(CE) { }
12807 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12809 S.Diag(Loc, diag::err_call_incomplete_return)
12810 << T << CE->getSourceRange();
12814 S.Diag(Loc, diag::err_call_function_incomplete_return)
12815 << CE->getSourceRange() << FD->getDeclName() << T;
12816 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
12817 << FD->getDeclName();
12819 } Diagnoser(FD, CE);
12821 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12827 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12828 // will prevent this condition from triggering, which is what we want.
12829 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12830 SourceLocation Loc;
12832 unsigned diagnostic = diag::warn_condition_is_assignment;
12833 bool IsOrAssign = false;
12835 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12836 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12839 IsOrAssign = Op->getOpcode() == BO_OrAssign;
12841 // Greylist some idioms by putting them into a warning subcategory.
12842 if (ObjCMessageExpr *ME
12843 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12844 Selector Sel = ME->getSelector();
12846 // self = [<foo> init...]
12847 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12848 diagnostic = diag::warn_condition_is_idiomatic_assignment;
12850 // <foo> = [<bar> nextObject]
12851 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12852 diagnostic = diag::warn_condition_is_idiomatic_assignment;
12855 Loc = Op->getOperatorLoc();
12856 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12857 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12860 IsOrAssign = Op->getOperator() == OO_PipeEqual;
12861 Loc = Op->getOperatorLoc();
12862 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12863 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12865 // Not an assignment.
12869 Diag(Loc, diagnostic) << E->getSourceRange();
12871 SourceLocation Open = E->getLocStart();
12872 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12873 Diag(Loc, diag::note_condition_assign_silence)
12874 << FixItHint::CreateInsertion(Open, "(")
12875 << FixItHint::CreateInsertion(Close, ")");
12878 Diag(Loc, diag::note_condition_or_assign_to_comparison)
12879 << FixItHint::CreateReplacement(Loc, "!=");
12881 Diag(Loc, diag::note_condition_assign_to_comparison)
12882 << FixItHint::CreateReplacement(Loc, "==");
12885 /// \brief Redundant parentheses over an equality comparison can indicate
12886 /// that the user intended an assignment used as condition.
12887 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12888 // Don't warn if the parens came from a macro.
12889 SourceLocation parenLoc = ParenE->getLocStart();
12890 if (parenLoc.isInvalid() || parenLoc.isMacroID())
12892 // Don't warn for dependent expressions.
12893 if (ParenE->isTypeDependent())
12896 Expr *E = ParenE->IgnoreParens();
12898 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12899 if (opE->getOpcode() == BO_EQ &&
12900 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12901 == Expr::MLV_Valid) {
12902 SourceLocation Loc = opE->getOperatorLoc();
12904 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12905 SourceRange ParenERange = ParenE->getSourceRange();
12906 Diag(Loc, diag::note_equality_comparison_silence)
12907 << FixItHint::CreateRemoval(ParenERange.getBegin())
12908 << FixItHint::CreateRemoval(ParenERange.getEnd());
12909 Diag(Loc, diag::note_equality_comparison_to_assign)
12910 << FixItHint::CreateReplacement(Loc, "=");
12914 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12915 DiagnoseAssignmentAsCondition(E);
12916 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12917 DiagnoseEqualityWithExtraParens(parenE);
12919 ExprResult result = CheckPlaceholderExpr(E);
12920 if (result.isInvalid()) return ExprError();
12923 if (!E->isTypeDependent()) {
12924 if (getLangOpts().CPlusPlus)
12925 return CheckCXXBooleanCondition(E); // C++ 6.4p4
12927 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12928 if (ERes.isInvalid())
12929 return ExprError();
12932 QualType T = E->getType();
12933 if (!T->isScalarType()) { // C99 6.8.4.1p1
12934 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12935 << T << E->getSourceRange();
12936 return ExprError();
12943 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12946 return ExprError();
12948 return CheckBooleanCondition(SubExpr, Loc);
12952 /// A visitor for rebuilding a call to an __unknown_any expression
12953 /// to have an appropriate type.
12954 struct RebuildUnknownAnyFunction
12955 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12959 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12961 ExprResult VisitStmt(Stmt *S) {
12962 llvm_unreachable("unexpected statement!");
12965 ExprResult VisitExpr(Expr *E) {
12966 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12967 << E->getSourceRange();
12968 return ExprError();
12971 /// Rebuild an expression which simply semantically wraps another
12972 /// expression which it shares the type and value kind of.
12973 template <class T> ExprResult rebuildSugarExpr(T *E) {
12974 ExprResult SubResult = Visit(E->getSubExpr());
12975 if (SubResult.isInvalid()) return ExprError();
12977 Expr *SubExpr = SubResult.get();
12978 E->setSubExpr(SubExpr);
12979 E->setType(SubExpr->getType());
12980 E->setValueKind(SubExpr->getValueKind());
12981 assert(E->getObjectKind() == OK_Ordinary);
12985 ExprResult VisitParenExpr(ParenExpr *E) {
12986 return rebuildSugarExpr(E);
12989 ExprResult VisitUnaryExtension(UnaryOperator *E) {
12990 return rebuildSugarExpr(E);
12993 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12994 ExprResult SubResult = Visit(E->getSubExpr());
12995 if (SubResult.isInvalid()) return ExprError();
12997 Expr *SubExpr = SubResult.get();
12998 E->setSubExpr(SubExpr);
12999 E->setType(S.Context.getPointerType(SubExpr->getType()));
13000 assert(E->getValueKind() == VK_RValue);
13001 assert(E->getObjectKind() == OK_Ordinary);
13005 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13006 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13008 E->setType(VD->getType());
13010 assert(E->getValueKind() == VK_RValue);
13011 if (S.getLangOpts().CPlusPlus &&
13012 !(isa<CXXMethodDecl>(VD) &&
13013 cast<CXXMethodDecl>(VD)->isInstance()))
13014 E->setValueKind(VK_LValue);
13019 ExprResult VisitMemberExpr(MemberExpr *E) {
13020 return resolveDecl(E, E->getMemberDecl());
13023 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13024 return resolveDecl(E, E->getDecl());
13029 /// Given a function expression of unknown-any type, try to rebuild it
13030 /// to have a function type.
13031 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13032 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13033 if (Result.isInvalid()) return ExprError();
13034 return S.DefaultFunctionArrayConversion(Result.get());
13038 /// A visitor for rebuilding an expression of type __unknown_anytype
13039 /// into one which resolves the type directly on the referring
13040 /// expression. Strict preservation of the original source
13041 /// structure is not a goal.
13042 struct RebuildUnknownAnyExpr
13043 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13047 /// The current destination type.
13050 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13051 : S(S), DestType(CastType) {}
13053 ExprResult VisitStmt(Stmt *S) {
13054 llvm_unreachable("unexpected statement!");
13057 ExprResult VisitExpr(Expr *E) {
13058 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13059 << E->getSourceRange();
13060 return ExprError();
13063 ExprResult VisitCallExpr(CallExpr *E);
13064 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
13066 /// Rebuild an expression which simply semantically wraps another
13067 /// expression which it shares the type and value kind of.
13068 template <class T> ExprResult rebuildSugarExpr(T *E) {
13069 ExprResult SubResult = Visit(E->getSubExpr());
13070 if (SubResult.isInvalid()) return ExprError();
13071 Expr *SubExpr = SubResult.get();
13072 E->setSubExpr(SubExpr);
13073 E->setType(SubExpr->getType());
13074 E->setValueKind(SubExpr->getValueKind());
13075 assert(E->getObjectKind() == OK_Ordinary);
13079 ExprResult VisitParenExpr(ParenExpr *E) {
13080 return rebuildSugarExpr(E);
13083 ExprResult VisitUnaryExtension(UnaryOperator *E) {
13084 return rebuildSugarExpr(E);
13087 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13088 const PointerType *Ptr = DestType->getAs<PointerType>();
13090 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13091 << E->getSourceRange();
13092 return ExprError();
13094 assert(E->getValueKind() == VK_RValue);
13095 assert(E->getObjectKind() == OK_Ordinary);
13096 E->setType(DestType);
13098 // Build the sub-expression as if it were an object of the pointee type.
13099 DestType = Ptr->getPointeeType();
13100 ExprResult SubResult = Visit(E->getSubExpr());
13101 if (SubResult.isInvalid()) return ExprError();
13102 E->setSubExpr(SubResult.get());
13106 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13108 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13110 ExprResult VisitMemberExpr(MemberExpr *E) {
13111 return resolveDecl(E, E->getMemberDecl());
13114 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13115 return resolveDecl(E, E->getDecl());
13120 /// Rebuilds a call expression which yielded __unknown_anytype.
13121 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13122 Expr *CalleeExpr = E->getCallee();
13126 FK_FunctionPointer,
13131 QualType CalleeType = CalleeExpr->getType();
13132 if (CalleeType == S.Context.BoundMemberTy) {
13133 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13134 Kind = FK_MemberFunction;
13135 CalleeType = Expr::findBoundMemberType(CalleeExpr);
13136 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13137 CalleeType = Ptr->getPointeeType();
13138 Kind = FK_FunctionPointer;
13140 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13141 Kind = FK_BlockPointer;
13143 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13145 // Verify that this is a legal result type of a function.
13146 if (DestType->isArrayType() || DestType->isFunctionType()) {
13147 unsigned diagID = diag::err_func_returning_array_function;
13148 if (Kind == FK_BlockPointer)
13149 diagID = diag::err_block_returning_array_function;
13151 S.Diag(E->getExprLoc(), diagID)
13152 << DestType->isFunctionType() << DestType;
13153 return ExprError();
13156 // Otherwise, go ahead and set DestType as the call's result.
13157 E->setType(DestType.getNonLValueExprType(S.Context));
13158 E->setValueKind(Expr::getValueKindForType(DestType));
13159 assert(E->getObjectKind() == OK_Ordinary);
13161 // Rebuild the function type, replacing the result type with DestType.
13162 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13164 // __unknown_anytype(...) is a special case used by the debugger when
13165 // it has no idea what a function's signature is.
13167 // We want to build this call essentially under the K&R
13168 // unprototyped rules, but making a FunctionNoProtoType in C++
13169 // would foul up all sorts of assumptions. However, we cannot
13170 // simply pass all arguments as variadic arguments, nor can we
13171 // portably just call the function under a non-variadic type; see
13172 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13173 // However, it turns out that in practice it is generally safe to
13174 // call a function declared as "A foo(B,C,D);" under the prototype
13175 // "A foo(B,C,D,...);". The only known exception is with the
13176 // Windows ABI, where any variadic function is implicitly cdecl
13177 // regardless of its normal CC. Therefore we change the parameter
13178 // types to match the types of the arguments.
13180 // This is a hack, but it is far superior to moving the
13181 // corresponding target-specific code from IR-gen to Sema/AST.
13183 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13184 SmallVector<QualType, 8> ArgTypes;
13185 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13186 ArgTypes.reserve(E->getNumArgs());
13187 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13188 Expr *Arg = E->getArg(i);
13189 QualType ArgType = Arg->getType();
13190 if (E->isLValue()) {
13191 ArgType = S.Context.getLValueReferenceType(ArgType);
13192 } else if (E->isXValue()) {
13193 ArgType = S.Context.getRValueReferenceType(ArgType);
13195 ArgTypes.push_back(ArgType);
13197 ParamTypes = ArgTypes;
13199 DestType = S.Context.getFunctionType(DestType, ParamTypes,
13200 Proto->getExtProtoInfo());
13202 DestType = S.Context.getFunctionNoProtoType(DestType,
13203 FnType->getExtInfo());
13206 // Rebuild the appropriate pointer-to-function type.
13208 case FK_MemberFunction:
13212 case FK_FunctionPointer:
13213 DestType = S.Context.getPointerType(DestType);
13216 case FK_BlockPointer:
13217 DestType = S.Context.getBlockPointerType(DestType);
13221 // Finally, we can recurse.
13222 ExprResult CalleeResult = Visit(CalleeExpr);
13223 if (!CalleeResult.isUsable()) return ExprError();
13224 E->setCallee(CalleeResult.get());
13226 // Bind a temporary if necessary.
13227 return S.MaybeBindToTemporary(E);
13230 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13231 // Verify that this is a legal result type of a call.
13232 if (DestType->isArrayType() || DestType->isFunctionType()) {
13233 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13234 << DestType->isFunctionType() << DestType;
13235 return ExprError();
13238 // Rewrite the method result type if available.
13239 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13240 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13241 Method->setReturnType(DestType);
13244 // Change the type of the message.
13245 E->setType(DestType.getNonReferenceType());
13246 E->setValueKind(Expr::getValueKindForType(DestType));
13248 return S.MaybeBindToTemporary(E);
13251 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13252 // The only case we should ever see here is a function-to-pointer decay.
13253 if (E->getCastKind() == CK_FunctionToPointerDecay) {
13254 assert(E->getValueKind() == VK_RValue);
13255 assert(E->getObjectKind() == OK_Ordinary);
13257 E->setType(DestType);
13259 // Rebuild the sub-expression as the pointee (function) type.
13260 DestType = DestType->castAs<PointerType>()->getPointeeType();
13262 ExprResult Result = Visit(E->getSubExpr());
13263 if (!Result.isUsable()) return ExprError();
13265 E->setSubExpr(Result.get());
13267 } else if (E->getCastKind() == CK_LValueToRValue) {
13268 assert(E->getValueKind() == VK_RValue);
13269 assert(E->getObjectKind() == OK_Ordinary);
13271 assert(isa<BlockPointerType>(E->getType()));
13273 E->setType(DestType);
13275 // The sub-expression has to be a lvalue reference, so rebuild it as such.
13276 DestType = S.Context.getLValueReferenceType(DestType);
13278 ExprResult Result = Visit(E->getSubExpr());
13279 if (!Result.isUsable()) return ExprError();
13281 E->setSubExpr(Result.get());
13284 llvm_unreachable("Unhandled cast type!");
13288 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13289 ExprValueKind ValueKind = VK_LValue;
13290 QualType Type = DestType;
13292 // We know how to make this work for certain kinds of decls:
13295 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13296 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13297 DestType = Ptr->getPointeeType();
13298 ExprResult Result = resolveDecl(E, VD);
13299 if (Result.isInvalid()) return ExprError();
13300 return S.ImpCastExprToType(Result.get(), Type,
13301 CK_FunctionToPointerDecay, VK_RValue);
13304 if (!Type->isFunctionType()) {
13305 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13306 << VD << E->getSourceRange();
13307 return ExprError();
13310 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13311 if (MD->isInstance()) {
13312 ValueKind = VK_RValue;
13313 Type = S.Context.BoundMemberTy;
13316 // Function references aren't l-values in C.
13317 if (!S.getLangOpts().CPlusPlus)
13318 ValueKind = VK_RValue;
13321 } else if (isa<VarDecl>(VD)) {
13322 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13323 Type = RefTy->getPointeeType();
13324 } else if (Type->isFunctionType()) {
13325 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13326 << VD << E->getSourceRange();
13327 return ExprError();
13332 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13333 << VD << E->getSourceRange();
13334 return ExprError();
13337 // Modifying the declaration like this is friendly to IR-gen but
13338 // also really dangerous.
13339 VD->setType(DestType);
13341 E->setValueKind(ValueKind);
13345 /// Check a cast of an unknown-any type. We intentionally only
13346 /// trigger this for C-style casts.
13347 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13348 Expr *CastExpr, CastKind &CastKind,
13349 ExprValueKind &VK, CXXCastPath &Path) {
13350 // Rewrite the casted expression from scratch.
13351 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13352 if (!result.isUsable()) return ExprError();
13354 CastExpr = result.get();
13355 VK = CastExpr->getValueKind();
13356 CastKind = CK_NoOp;
13361 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13362 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13365 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13366 Expr *arg, QualType ¶mType) {
13367 // If the syntactic form of the argument is not an explicit cast of
13368 // any sort, just do default argument promotion.
13369 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13371 ExprResult result = DefaultArgumentPromotion(arg);
13372 if (result.isInvalid()) return ExprError();
13373 paramType = result.get()->getType();
13377 // Otherwise, use the type that was written in the explicit cast.
13378 assert(!arg->hasPlaceholderType());
13379 paramType = castArg->getTypeAsWritten();
13381 // Copy-initialize a parameter of that type.
13382 InitializedEntity entity =
13383 InitializedEntity::InitializeParameter(Context, paramType,
13384 /*consumed*/ false);
13385 return PerformCopyInitialization(entity, callLoc, arg);
13388 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13390 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13392 E = E->IgnoreParenImpCasts();
13393 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13394 E = call->getCallee();
13395 diagID = diag::err_uncasted_call_of_unknown_any;
13401 SourceLocation loc;
13403 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13404 loc = ref->getLocation();
13405 d = ref->getDecl();
13406 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13407 loc = mem->getMemberLoc();
13408 d = mem->getMemberDecl();
13409 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13410 diagID = diag::err_uncasted_call_of_unknown_any;
13411 loc = msg->getSelectorStartLoc();
13412 d = msg->getMethodDecl();
13414 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13415 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13416 << orig->getSourceRange();
13417 return ExprError();
13420 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13421 << E->getSourceRange();
13422 return ExprError();
13425 S.Diag(loc, diagID) << d << orig->getSourceRange();
13427 // Never recoverable.
13428 return ExprError();
13431 /// Check for operands with placeholder types and complain if found.
13432 /// Returns true if there was an error and no recovery was possible.
13433 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13434 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13435 if (!placeholderType) return E;
13437 switch (placeholderType->getKind()) {
13439 // Overloaded expressions.
13440 case BuiltinType::Overload: {
13441 // Try to resolve a single function template specialization.
13442 // This is obligatory.
13443 ExprResult result = E;
13444 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13447 // If that failed, try to recover with a call.
13449 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13450 /*complain*/ true);
13455 // Bound member functions.
13456 case BuiltinType::BoundMember: {
13457 ExprResult result = E;
13458 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13459 /*complain*/ true);
13463 // ARC unbridged casts.
13464 case BuiltinType::ARCUnbridgedCast: {
13465 Expr *realCast = stripARCUnbridgedCast(E);
13466 diagnoseARCUnbridgedCast(realCast);
13470 // Expressions of unknown type.
13471 case BuiltinType::UnknownAny:
13472 return diagnoseUnknownAnyExpr(*this, E);
13475 case BuiltinType::PseudoObject:
13476 return checkPseudoObjectRValue(E);
13478 case BuiltinType::BuiltinFn: {
13479 // Accept __noop without parens by implicitly converting it to a call expr.
13480 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
13482 auto *FD = cast<FunctionDecl>(DRE->getDecl());
13483 if (FD->getBuiltinID() == Builtin::BI__noop) {
13484 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
13485 CK_BuiltinFnToFnPtr).get();
13486 return new (Context) CallExpr(Context, E, None, Context.IntTy,
13487 VK_RValue, SourceLocation());
13491 Diag(E->getLocStart(), diag::err_builtin_fn_use);
13492 return ExprError();
13495 // Everything else should be impossible.
13496 #define BUILTIN_TYPE(Id, SingletonId) \
13497 case BuiltinType::Id:
13498 #define PLACEHOLDER_TYPE(Id, SingletonId)
13499 #include "clang/AST/BuiltinTypes.def"
13503 llvm_unreachable("invalid placeholder type!");
13506 bool Sema::CheckCaseExpression(Expr *E) {
13507 if (E->isTypeDependent())
13509 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13510 return E->getType()->isIntegralOrEnumerationType();
13514 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13516 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13517 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13518 "Unknown Objective-C Boolean value!");
13519 QualType BoolT = Context.ObjCBuiltinBoolTy;
13520 if (!Context.getBOOLDecl()) {
13521 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13522 Sema::LookupOrdinaryName);
13523 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13524 NamedDecl *ND = Result.getFoundDecl();
13525 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13526 Context.setBOOLDecl(TD);
13529 if (Context.getBOOLDecl())
13530 BoolT = Context.getBOOLType();
13531 return new (Context)
13532 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);