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->getResultType()->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 // See if this declaration is unavailable or deprecated.
89 AvailabilityResult Result = D->getAvailability(&Message);
90 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
91 if (Result == AR_Available) {
92 const DeclContext *DC = ECD->getDeclContext();
93 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
94 Result = TheEnumDecl->getAvailability(&Message);
97 const ObjCPropertyDecl *ObjCPDecl = 0;
98 if (Result == AR_Deprecated || Result == AR_Unavailable) {
99 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
100 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
101 AvailabilityResult PDeclResult = PD->getAvailability(0);
102 if (PDeclResult == Result)
110 case AR_NotYetIntroduced:
114 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
118 if (S.getCurContextAvailability() != AR_Unavailable) {
119 if (Message.empty()) {
120 if (!UnknownObjCClass) {
121 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
123 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
124 << ObjCPDecl->getDeclName() << 1;
127 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
131 S.Diag(Loc, diag::err_unavailable_message)
132 << D->getDeclName() << Message;
133 S.Diag(D->getLocation(), diag::note_unavailable_here)
134 << isa<FunctionDecl>(D) << false;
136 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
137 << ObjCPDecl->getDeclName() << 1;
144 /// \brief Emit a note explaining that this function is deleted.
145 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
146 assert(Decl->isDeleted());
148 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
150 if (Method && Method->isDeleted() && Method->isDefaulted()) {
151 // If the method was explicitly defaulted, point at that declaration.
152 if (!Method->isImplicit())
153 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
155 // Try to diagnose why this special member function was implicitly
156 // deleted. This might fail, if that reason no longer applies.
157 CXXSpecialMember CSM = getSpecialMember(Method);
158 if (CSM != CXXInvalid)
159 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
164 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
165 if (CXXConstructorDecl *BaseCD =
166 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
167 Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
168 if (BaseCD->isDeleted()) {
169 NoteDeletedFunction(BaseCD);
171 // FIXME: An explanation of why exactly it can't be inherited
173 Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
179 Diag(Decl->getLocation(), diag::note_unavailable_here)
183 /// \brief Determine whether a FunctionDecl was ever declared with an
184 /// explicit storage class.
185 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
186 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
187 E = D->redecls_end();
189 if (I->getStorageClass() != SC_None)
195 /// \brief Check whether we're in an extern inline function and referring to a
196 /// variable or function with internal linkage (C11 6.7.4p3).
198 /// This is only a warning because we used to silently accept this code, but
199 /// in many cases it will not behave correctly. This is not enabled in C++ mode
200 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
201 /// and so while there may still be user mistakes, most of the time we can't
202 /// prove that there are errors.
203 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
205 SourceLocation Loc) {
206 // This is disabled under C++; there are too many ways for this to fire in
207 // contexts where the warning is a false positive, or where it is technically
208 // correct but benign.
209 if (S.getLangOpts().CPlusPlus)
212 // Check if this is an inlined function or method.
213 FunctionDecl *Current = S.getCurFunctionDecl();
216 if (!Current->isInlined())
218 if (!Current->isExternallyVisible())
221 // Check if the decl has internal linkage.
222 if (D->getFormalLinkage() != InternalLinkage)
225 // Downgrade from ExtWarn to Extension if
226 // (1) the supposedly external inline function is in the main file,
227 // and probably won't be included anywhere else.
228 // (2) the thing we're referencing is a pure function.
229 // (3) the thing we're referencing is another inline function.
230 // This last can give us false negatives, but it's better than warning on
231 // wrappers for simple C library functions.
232 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
233 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
234 if (!DowngradeWarning && UsedFn)
235 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
237 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
238 : diag::warn_internal_in_extern_inline)
239 << /*IsVar=*/!UsedFn << D;
241 S.MaybeSuggestAddingStaticToDecl(Current);
243 S.Diag(D->getCanonicalDecl()->getLocation(),
244 diag::note_internal_decl_declared_here)
248 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
249 const FunctionDecl *First = Cur->getFirstDecl();
251 // Suggest "static" on the function, if possible.
252 if (!hasAnyExplicitStorageClass(First)) {
253 SourceLocation DeclBegin = First->getSourceRange().getBegin();
254 Diag(DeclBegin, diag::note_convert_inline_to_static)
255 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
259 /// \brief Determine whether the use of this declaration is valid, and
260 /// emit any corresponding diagnostics.
262 /// This routine diagnoses various problems with referencing
263 /// declarations that can occur when using a declaration. For example,
264 /// it might warn if a deprecated or unavailable declaration is being
265 /// used, or produce an error (and return true) if a C++0x deleted
266 /// function is being used.
268 /// \returns true if there was an error (this declaration cannot be
269 /// referenced), false otherwise.
271 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
272 const ObjCInterfaceDecl *UnknownObjCClass) {
273 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
274 // If there were any diagnostics suppressed by template argument deduction,
276 SuppressedDiagnosticsMap::iterator
277 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
278 if (Pos != SuppressedDiagnostics.end()) {
279 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
280 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
281 Diag(Suppressed[I].first, Suppressed[I].second);
283 // Clear out the list of suppressed diagnostics, so that we don't emit
284 // them again for this specialization. However, we don't obsolete this
285 // entry from the table, because we want to avoid ever emitting these
286 // diagnostics again.
291 // See if this is an auto-typed variable whose initializer we are parsing.
292 if (ParsingInitForAutoVars.count(D)) {
293 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
298 // See if this is a deleted function.
299 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
300 if (FD->isDeleted()) {
301 Diag(Loc, diag::err_deleted_function_use);
302 NoteDeletedFunction(FD);
306 // If the function has a deduced return type, and we can't deduce it,
307 // then we can't use it either.
308 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
309 DeduceReturnType(FD, Loc))
312 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
314 DiagnoseUnusedOfDecl(*this, D, Loc);
316 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
321 /// \brief Retrieve the message suffix that should be added to a
322 /// diagnostic complaining about the given function being deleted or
324 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
326 if (FD->getAvailability(&Message))
327 return ": " + Message;
329 return std::string();
332 /// DiagnoseSentinelCalls - This routine checks whether a call or
333 /// message-send is to a declaration with the sentinel attribute, and
334 /// if so, it checks that the requirements of the sentinel are
336 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
337 ArrayRef<Expr *> Args) {
338 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
342 // The number of formal parameters of the declaration.
343 unsigned numFormalParams;
345 // The kind of declaration. This is also an index into a %select in
347 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
349 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
350 numFormalParams = MD->param_size();
351 calleeType = CT_Method;
352 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
353 numFormalParams = FD->param_size();
354 calleeType = CT_Function;
355 } else if (isa<VarDecl>(D)) {
356 QualType type = cast<ValueDecl>(D)->getType();
357 const FunctionType *fn = 0;
358 if (const PointerType *ptr = type->getAs<PointerType>()) {
359 fn = ptr->getPointeeType()->getAs<FunctionType>();
361 calleeType = CT_Function;
362 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
363 fn = ptr->getPointeeType()->castAs<FunctionType>();
364 calleeType = CT_Block;
369 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
370 numFormalParams = proto->getNumArgs();
378 // "nullPos" is the number of formal parameters at the end which
379 // effectively count as part of the variadic arguments. This is
380 // useful if you would prefer to not have *any* formal parameters,
381 // but the language forces you to have at least one.
382 unsigned nullPos = attr->getNullPos();
383 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
384 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
386 // The number of arguments which should follow the sentinel.
387 unsigned numArgsAfterSentinel = attr->getSentinel();
389 // If there aren't enough arguments for all the formal parameters,
390 // the sentinel, and the args after the sentinel, complain.
391 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
392 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
393 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
397 // Otherwise, find the sentinel expression.
398 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
399 if (!sentinelExpr) return;
400 if (sentinelExpr->isValueDependent()) return;
401 if (Context.isSentinelNullExpr(sentinelExpr)) return;
403 // Pick a reasonable string to insert. Optimistically use 'nil' or
404 // 'NULL' if those are actually defined in the context. Only use
405 // 'nil' for ObjC methods, where it's much more likely that the
406 // variadic arguments form a list of object pointers.
407 SourceLocation MissingNilLoc
408 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
409 std::string NullValue;
410 if (calleeType == CT_Method &&
411 PP.getIdentifierInfo("nil")->hasMacroDefinition())
413 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
416 NullValue = "(void*) 0";
418 if (MissingNilLoc.isInvalid())
419 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
421 Diag(MissingNilLoc, diag::warn_missing_sentinel)
423 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
424 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
427 SourceRange Sema::getExprRange(Expr *E) const {
428 return E ? E->getSourceRange() : SourceRange();
431 //===----------------------------------------------------------------------===//
432 // Standard Promotions and Conversions
433 //===----------------------------------------------------------------------===//
435 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
436 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
437 // Handle any placeholder expressions which made it here.
438 if (E->getType()->isPlaceholderType()) {
439 ExprResult result = CheckPlaceholderExpr(E);
440 if (result.isInvalid()) return ExprError();
444 QualType Ty = E->getType();
445 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
447 if (Ty->isFunctionType())
448 E = ImpCastExprToType(E, Context.getPointerType(Ty),
449 CK_FunctionToPointerDecay).take();
450 else if (Ty->isArrayType()) {
451 // In C90 mode, arrays only promote to pointers if the array expression is
452 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
453 // type 'array of type' is converted to an expression that has type 'pointer
454 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
455 // that has type 'array of type' ...". The relevant change is "an lvalue"
456 // (C90) to "an expression" (C99).
459 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
460 // T" can be converted to an rvalue of type "pointer to T".
462 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
463 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
464 CK_ArrayToPointerDecay).take();
469 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
470 // Check to see if we are dereferencing a null pointer. If so,
471 // and if not volatile-qualified, this is undefined behavior that the
472 // optimizer will delete, so warn about it. People sometimes try to use this
473 // to get a deterministic trap and are surprised by clang's behavior. This
474 // only handles the pattern "*null", which is a very syntactic check.
475 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
476 if (UO->getOpcode() == UO_Deref &&
477 UO->getSubExpr()->IgnoreParenCasts()->
478 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
479 !UO->getType().isVolatileQualified()) {
480 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
481 S.PDiag(diag::warn_indirection_through_null)
482 << UO->getSubExpr()->getSourceRange());
483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
484 S.PDiag(diag::note_indirection_through_null));
488 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
489 SourceLocation AssignLoc,
491 const ObjCIvarDecl *IV = OIRE->getDecl();
495 DeclarationName MemberName = IV->getDeclName();
496 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
497 if (!Member || !Member->isStr("isa"))
500 const Expr *Base = OIRE->getBase();
501 QualType BaseType = Base->getType();
503 BaseType = BaseType->getPointeeType();
504 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
505 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
506 ObjCInterfaceDecl *ClassDeclared = 0;
507 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
508 if (!ClassDeclared->getSuperClass()
509 && (*ClassDeclared->ivar_begin()) == IV) {
511 NamedDecl *ObjectSetClass =
512 S.LookupSingleName(S.TUScope,
513 &S.Context.Idents.get("object_setClass"),
514 SourceLocation(), S.LookupOrdinaryName);
515 if (ObjectSetClass) {
516 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
518 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
519 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
521 FixItHint::CreateInsertion(RHSLocEnd, ")");
524 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
526 NamedDecl *ObjectGetClass =
527 S.LookupSingleName(S.TUScope,
528 &S.Context.Idents.get("object_getClass"),
529 SourceLocation(), S.LookupOrdinaryName);
531 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
532 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
533 FixItHint::CreateReplacement(
534 SourceRange(OIRE->getOpLoc(),
535 OIRE->getLocEnd()), ")");
537 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
539 S.Diag(IV->getLocation(), diag::note_ivar_decl);
544 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
545 // Handle any placeholder expressions which made it here.
546 if (E->getType()->isPlaceholderType()) {
547 ExprResult result = CheckPlaceholderExpr(E);
548 if (result.isInvalid()) return ExprError();
552 // C++ [conv.lval]p1:
553 // A glvalue of a non-function, non-array type T can be
554 // converted to a prvalue.
555 if (!E->isGLValue()) return Owned(E);
557 QualType T = E->getType();
558 assert(!T.isNull() && "r-value conversion on typeless expression?");
560 // We don't want to throw lvalue-to-rvalue casts on top of
561 // expressions of certain types in C++.
562 if (getLangOpts().CPlusPlus &&
563 (E->getType() == Context.OverloadTy ||
564 T->isDependentType() ||
568 // The C standard is actually really unclear on this point, and
569 // DR106 tells us what the result should be but not why. It's
570 // generally best to say that void types just doesn't undergo
571 // lvalue-to-rvalue at all. Note that expressions of unqualified
572 // 'void' type are never l-values, but qualified void can be.
576 // OpenCL usually rejects direct accesses to values of 'half' type.
577 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
579 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
584 CheckForNullPointerDereference(*this, E);
585 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
586 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
587 &Context.Idents.get("object_getClass"),
588 SourceLocation(), LookupOrdinaryName);
590 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
591 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
592 FixItHint::CreateReplacement(
593 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
595 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
597 else if (const ObjCIvarRefExpr *OIRE =
598 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
599 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
601 // C++ [conv.lval]p1:
602 // [...] If T is a non-class type, the type of the prvalue is the
603 // cv-unqualified version of T. Otherwise, the type of the
607 // If the lvalue has qualified type, the value has the unqualified
608 // version of the type of the lvalue; otherwise, the value has the
609 // type of the lvalue.
610 if (T.hasQualifiers())
611 T = T.getUnqualifiedType();
613 UpdateMarkingForLValueToRValue(E);
615 // Loading a __weak object implicitly retains the value, so we need a cleanup to
617 if (getLangOpts().ObjCAutoRefCount &&
618 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
619 ExprNeedsCleanups = true;
621 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
625 // ... if the lvalue has atomic type, the value has the non-atomic version
626 // of the type of the lvalue ...
627 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
628 T = Atomic->getValueType().getUnqualifiedType();
629 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
630 Res.get(), 0, VK_RValue));
636 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
637 ExprResult Res = DefaultFunctionArrayConversion(E);
640 Res = DefaultLvalueConversion(Res.take());
647 /// UsualUnaryConversions - Performs various conversions that are common to most
648 /// operators (C99 6.3). The conversions of array and function types are
649 /// sometimes suppressed. For example, the array->pointer conversion doesn't
650 /// apply if the array is an argument to the sizeof or address (&) operators.
651 /// In these instances, this routine should *not* be called.
652 ExprResult Sema::UsualUnaryConversions(Expr *E) {
653 // First, convert to an r-value.
654 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
659 QualType Ty = E->getType();
660 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
662 // Half FP have to be promoted to float unless it is natively supported
663 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
664 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
666 // Try to perform integral promotions if the object has a theoretically
668 if (Ty->isIntegralOrUnscopedEnumerationType()) {
671 // The following may be used in an expression wherever an int or
672 // unsigned int may be used:
673 // - an object or expression with an integer type whose integer
674 // conversion rank is less than or equal to the rank of int
676 // - A bit-field of type _Bool, int, signed int, or unsigned int.
678 // If an int can represent all values of the original type, the
679 // value is converted to an int; otherwise, it is converted to an
680 // unsigned int. These are called the integer promotions. All
681 // other types are unchanged by the integer promotions.
683 QualType PTy = Context.isPromotableBitField(E);
685 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
688 if (Ty->isPromotableIntegerType()) {
689 QualType PT = Context.getPromotedIntegerType(Ty);
690 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
697 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
698 /// do not have a prototype. Arguments that have type float or __fp16
699 /// are promoted to double. All other argument types are converted by
700 /// UsualUnaryConversions().
701 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
702 QualType Ty = E->getType();
703 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
705 ExprResult Res = UsualUnaryConversions(E);
710 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
712 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
713 if (BTy && (BTy->getKind() == BuiltinType::Half ||
714 BTy->getKind() == BuiltinType::Float))
715 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
717 // C++ performs lvalue-to-rvalue conversion as a default argument
718 // promotion, even on class types, but note:
719 // C++11 [conv.lval]p2:
720 // When an lvalue-to-rvalue conversion occurs in an unevaluated
721 // operand or a subexpression thereof the value contained in the
722 // referenced object is not accessed. Otherwise, if the glvalue
723 // has a class type, the conversion copy-initializes a temporary
724 // of type T from the glvalue and the result of the conversion
725 // is a prvalue for the temporary.
726 // FIXME: add some way to gate this entire thing for correctness in
727 // potentially potentially evaluated contexts.
728 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
729 ExprResult Temp = PerformCopyInitialization(
730 InitializedEntity::InitializeTemporary(E->getType()),
733 if (Temp.isInvalid())
741 /// Determine the degree of POD-ness for an expression.
742 /// Incomplete types are considered POD, since this check can be performed
743 /// when we're in an unevaluated context.
744 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
745 if (Ty->isIncompleteType()) {
746 // C++11 [expr.call]p7:
747 // After these conversions, if the argument does not have arithmetic,
748 // enumeration, pointer, pointer to member, or class type, the program
751 // Since we've already performed array-to-pointer and function-to-pointer
752 // decay, the only such type in C++ is cv void. This also handles
753 // initializer lists as variadic arguments.
754 if (Ty->isVoidType())
757 if (Ty->isObjCObjectType())
762 if (Ty.isCXX98PODType(Context))
765 // C++11 [expr.call]p7:
766 // Passing a potentially-evaluated argument of class type (Clause 9)
767 // having a non-trivial copy constructor, a non-trivial move constructor,
768 // or a non-trivial destructor, with no corresponding parameter,
769 // is conditionally-supported with implementation-defined semantics.
770 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
771 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
772 if (!Record->hasNonTrivialCopyConstructor() &&
773 !Record->hasNonTrivialMoveConstructor() &&
774 !Record->hasNonTrivialDestructor())
775 return VAK_ValidInCXX11;
777 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
780 if (Ty->isObjCObjectType())
783 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
784 // permitted to reject them. We should consider doing so.
785 return VAK_Undefined;
788 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
789 // Don't allow one to pass an Objective-C interface to a vararg.
790 const QualType &Ty = E->getType();
791 VarArgKind VAK = isValidVarArgType(Ty);
793 // Complain about passing non-POD types through varargs.
798 case VAK_ValidInCXX11:
801 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
802 << E->getType() << CT);
808 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
809 << getLangOpts().CPlusPlus11 << Ty << CT);
813 if (Ty->isObjCObjectType())
816 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
819 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
820 << isa<InitListExpr>(E) << Ty << CT;
825 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
826 /// will create a trap if the resulting type is not a POD type.
827 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
828 FunctionDecl *FDecl) {
829 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
830 // Strip the unbridged-cast placeholder expression off, if applicable.
831 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
832 (CT == VariadicMethod ||
833 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
834 E = stripARCUnbridgedCast(E);
836 // Otherwise, do normal placeholder checking.
838 ExprResult ExprRes = CheckPlaceholderExpr(E);
839 if (ExprRes.isInvalid())
845 ExprResult ExprRes = DefaultArgumentPromotion(E);
846 if (ExprRes.isInvalid())
850 // Diagnostics regarding non-POD argument types are
851 // emitted along with format string checking in Sema::CheckFunctionCall().
852 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
853 // Turn this into a trap.
855 SourceLocation TemplateKWLoc;
857 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
859 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
861 if (TrapFn.isInvalid())
864 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
865 E->getLocStart(), None,
867 if (Call.isInvalid())
870 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
872 if (Comma.isInvalid())
877 if (!getLangOpts().CPlusPlus &&
878 RequireCompleteType(E->getExprLoc(), E->getType(),
879 diag::err_call_incomplete_argument))
885 /// \brief Converts an integer to complex float type. Helper function of
886 /// UsualArithmeticConversions()
888 /// \return false if the integer expression is an integer type and is
889 /// successfully converted to the complex type.
890 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
891 ExprResult &ComplexExpr,
895 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
896 if (SkipCast) return false;
897 if (IntTy->isIntegerType()) {
898 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
899 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
900 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
901 CK_FloatingRealToComplex);
903 assert(IntTy->isComplexIntegerType());
904 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
905 CK_IntegralComplexToFloatingComplex);
910 /// \brief Takes two complex float types and converts them to the same type.
911 /// Helper function of UsualArithmeticConversions()
913 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
914 ExprResult &RHS, QualType LHSType,
917 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
920 // _Complex float -> _Complex double
922 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
926 // _Complex float -> _Complex double
927 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
931 /// \brief Converts otherExpr to complex float and promotes complexExpr if
932 /// necessary. Helper function of UsualArithmeticConversions()
933 static QualType handleOtherComplexFloatConversion(Sema &S,
934 ExprResult &ComplexExpr,
935 ExprResult &OtherExpr,
938 bool ConvertComplexExpr,
939 bool ConvertOtherExpr) {
940 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
942 // If just the complexExpr is complex, the otherExpr needs to be converted,
943 // and the complexExpr might need to be promoted.
944 if (order > 0) { // complexExpr is wider
945 // float -> _Complex double
946 if (ConvertOtherExpr) {
947 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
948 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
949 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
950 CK_FloatingRealToComplex);
955 // otherTy is at least as wide. Find its corresponding complex type.
956 QualType result = (order == 0 ? ComplexTy :
957 S.Context.getComplexType(OtherTy));
959 // double -> _Complex double
960 if (ConvertOtherExpr)
961 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
962 CK_FloatingRealToComplex);
964 // _Complex float -> _Complex double
965 if (ConvertComplexExpr && order < 0)
966 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
967 CK_FloatingComplexCast);
972 /// \brief Handle arithmetic conversion with complex types. Helper function of
973 /// UsualArithmeticConversions()
974 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
975 ExprResult &RHS, QualType LHSType,
978 // if we have an integer operand, the result is the complex type.
979 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
982 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
983 /*skipCast*/IsCompAssign))
986 // This handles complex/complex, complex/float, or float/complex.
987 // When both operands are complex, the shorter operand is converted to the
988 // type of the longer, and that is the type of the result. This corresponds
989 // to what is done when combining two real floating-point operands.
990 // The fun begins when size promotion occur across type domains.
991 // From H&S 6.3.4: When one operand is complex and the other is a real
992 // floating-point type, the less precise type is converted, within it's
993 // real or complex domain, to the precision of the other type. For example,
994 // when combining a "long double" with a "double _Complex", the
995 // "double _Complex" is promoted to "long double _Complex".
997 bool LHSComplexFloat = LHSType->isComplexType();
998 bool RHSComplexFloat = RHSType->isComplexType();
1000 // If both are complex, just cast to the more precise type.
1001 if (LHSComplexFloat && RHSComplexFloat)
1002 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1006 // If only one operand is complex, promote it if necessary and convert the
1007 // other operand to complex.
1008 if (LHSComplexFloat)
1009 return handleOtherComplexFloatConversion(
1010 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1011 /*convertOtherExpr*/ true);
1013 assert(RHSComplexFloat);
1014 return handleOtherComplexFloatConversion(
1015 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1016 /*convertOtherExpr*/ !IsCompAssign);
1019 /// \brief Hande arithmetic conversion from integer to float. Helper function
1020 /// of UsualArithmeticConversions()
1021 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1022 ExprResult &IntExpr,
1023 QualType FloatTy, QualType IntTy,
1024 bool ConvertFloat, bool ConvertInt) {
1025 if (IntTy->isIntegerType()) {
1027 // Convert intExpr to the lhs floating point type.
1028 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
1029 CK_IntegralToFloating);
1033 // Convert both sides to the appropriate complex float.
1034 assert(IntTy->isComplexIntegerType());
1035 QualType result = S.Context.getComplexType(FloatTy);
1037 // _Complex int -> _Complex float
1039 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
1040 CK_IntegralComplexToFloatingComplex);
1042 // float -> _Complex float
1044 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1045 CK_FloatingRealToComplex);
1050 /// \brief Handle arithmethic conversion with floating point types. Helper
1051 /// function of UsualArithmeticConversions()
1052 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1053 ExprResult &RHS, QualType LHSType,
1054 QualType RHSType, bool IsCompAssign) {
1055 bool LHSFloat = LHSType->isRealFloatingType();
1056 bool RHSFloat = RHSType->isRealFloatingType();
1058 // If we have two real floating types, convert the smaller operand
1059 // to the bigger result.
1060 if (LHSFloat && RHSFloat) {
1061 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1063 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1067 assert(order < 0 && "illegal float comparison");
1069 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1074 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1075 /*convertFloat=*/!IsCompAssign,
1076 /*convertInt=*/ true);
1078 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1079 /*convertInt=*/ true,
1080 /*convertFloat=*/!IsCompAssign);
1083 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1086 /// These helper callbacks are placed in an anonymous namespace to
1087 /// permit their use as function template parameters.
1088 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1089 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1092 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1093 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1094 CK_IntegralComplexCast);
1098 /// \brief Handle integer arithmetic conversions. Helper function of
1099 /// UsualArithmeticConversions()
1100 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1101 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1102 ExprResult &RHS, QualType LHSType,
1103 QualType RHSType, bool IsCompAssign) {
1104 // The rules for this case are in C99 6.3.1.8
1105 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1106 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1107 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1108 if (LHSSigned == RHSSigned) {
1109 // Same signedness; use the higher-ranked type
1111 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1113 } else if (!IsCompAssign)
1114 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1116 } else if (order != (LHSSigned ? 1 : -1)) {
1117 // The unsigned type has greater than or equal rank to the
1118 // signed type, so use the unsigned type
1120 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1122 } else if (!IsCompAssign)
1123 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1125 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1126 // The two types are different widths; if we are here, that
1127 // means the signed type is larger than the unsigned type, so
1128 // use the signed type.
1130 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1132 } else if (!IsCompAssign)
1133 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1136 // The signed type is higher-ranked than the unsigned type,
1137 // but isn't actually any bigger (like unsigned int and long
1138 // on most 32-bit systems). Use the unsigned type corresponding
1139 // to the signed type.
1141 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1142 RHS = (*doRHSCast)(S, RHS.take(), result);
1144 LHS = (*doLHSCast)(S, LHS.take(), result);
1149 /// \brief Handle conversions with GCC complex int extension. Helper function
1150 /// of UsualArithmeticConversions()
1151 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1152 ExprResult &RHS, QualType LHSType,
1154 bool IsCompAssign) {
1155 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1156 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1158 if (LHSComplexInt && RHSComplexInt) {
1159 QualType LHSEltType = LHSComplexInt->getElementType();
1160 QualType RHSEltType = RHSComplexInt->getElementType();
1161 QualType ScalarType =
1162 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1163 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1165 return S.Context.getComplexType(ScalarType);
1168 if (LHSComplexInt) {
1169 QualType LHSEltType = LHSComplexInt->getElementType();
1170 QualType ScalarType =
1171 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1172 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1173 QualType ComplexType = S.Context.getComplexType(ScalarType);
1174 RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1175 CK_IntegralRealToComplex);
1180 assert(RHSComplexInt);
1182 QualType RHSEltType = RHSComplexInt->getElementType();
1183 QualType ScalarType =
1184 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1185 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1186 QualType ComplexType = S.Context.getComplexType(ScalarType);
1189 LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1190 CK_IntegralRealToComplex);
1194 /// UsualArithmeticConversions - Performs various conversions that are common to
1195 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1196 /// routine returns the first non-arithmetic type found. The client is
1197 /// responsible for emitting appropriate error diagnostics.
1198 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1199 bool IsCompAssign) {
1200 if (!IsCompAssign) {
1201 LHS = UsualUnaryConversions(LHS.take());
1202 if (LHS.isInvalid())
1206 RHS = UsualUnaryConversions(RHS.take());
1207 if (RHS.isInvalid())
1210 // For conversion purposes, we ignore any qualifiers.
1211 // For example, "const float" and "float" are equivalent.
1213 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1215 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1217 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1218 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1219 LHSType = AtomicLHS->getValueType();
1221 // If both types are identical, no conversion is needed.
1222 if (LHSType == RHSType)
1225 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1226 // The caller can deal with this (e.g. pointer + int).
1227 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1230 // Apply unary and bitfield promotions to the LHS's type.
1231 QualType LHSUnpromotedType = LHSType;
1232 if (LHSType->isPromotableIntegerType())
1233 LHSType = Context.getPromotedIntegerType(LHSType);
1234 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1235 if (!LHSBitfieldPromoteTy.isNull())
1236 LHSType = LHSBitfieldPromoteTy;
1237 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1238 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1240 // If both types are identical, no conversion is needed.
1241 if (LHSType == RHSType)
1244 // At this point, we have two different arithmetic types.
1246 // Handle complex types first (C99 6.3.1.8p1).
1247 if (LHSType->isComplexType() || RHSType->isComplexType())
1248 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1251 // Now handle "real" floating types (i.e. float, double, long double).
1252 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1253 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1256 // Handle GCC complex int extension.
1257 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1258 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1261 // Finally, we have two differing integer types.
1262 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1263 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1267 //===----------------------------------------------------------------------===//
1268 // Semantic Analysis for various Expression Types
1269 //===----------------------------------------------------------------------===//
1273 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1274 SourceLocation DefaultLoc,
1275 SourceLocation RParenLoc,
1276 Expr *ControllingExpr,
1277 ArrayRef<ParsedType> ArgTypes,
1278 ArrayRef<Expr *> ArgExprs) {
1279 unsigned NumAssocs = ArgTypes.size();
1280 assert(NumAssocs == ArgExprs.size());
1282 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1283 for (unsigned i = 0; i < NumAssocs; ++i) {
1285 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1290 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1292 llvm::makeArrayRef(Types, NumAssocs),
1299 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1300 SourceLocation DefaultLoc,
1301 SourceLocation RParenLoc,
1302 Expr *ControllingExpr,
1303 ArrayRef<TypeSourceInfo *> Types,
1304 ArrayRef<Expr *> Exprs) {
1305 unsigned NumAssocs = Types.size();
1306 assert(NumAssocs == Exprs.size());
1307 if (ControllingExpr->getType()->isPlaceholderType()) {
1308 ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1309 if (result.isInvalid()) return ExprError();
1310 ControllingExpr = result.take();
1313 bool TypeErrorFound = false,
1314 IsResultDependent = ControllingExpr->isTypeDependent(),
1315 ContainsUnexpandedParameterPack
1316 = ControllingExpr->containsUnexpandedParameterPack();
1318 for (unsigned i = 0; i < NumAssocs; ++i) {
1319 if (Exprs[i]->containsUnexpandedParameterPack())
1320 ContainsUnexpandedParameterPack = true;
1323 if (Types[i]->getType()->containsUnexpandedParameterPack())
1324 ContainsUnexpandedParameterPack = true;
1326 if (Types[i]->getType()->isDependentType()) {
1327 IsResultDependent = true;
1329 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1330 // complete object type other than a variably modified type."
1332 if (Types[i]->getType()->isIncompleteType())
1333 D = diag::err_assoc_type_incomplete;
1334 else if (!Types[i]->getType()->isObjectType())
1335 D = diag::err_assoc_type_nonobject;
1336 else if (Types[i]->getType()->isVariablyModifiedType())
1337 D = diag::err_assoc_type_variably_modified;
1340 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1341 << Types[i]->getTypeLoc().getSourceRange()
1342 << Types[i]->getType();
1343 TypeErrorFound = true;
1346 // C11 6.5.1.1p2 "No two generic associations in the same generic
1347 // selection shall specify compatible types."
1348 for (unsigned j = i+1; j < NumAssocs; ++j)
1349 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1350 Context.typesAreCompatible(Types[i]->getType(),
1351 Types[j]->getType())) {
1352 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1353 diag::err_assoc_compatible_types)
1354 << Types[j]->getTypeLoc().getSourceRange()
1355 << Types[j]->getType()
1356 << Types[i]->getType();
1357 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1358 diag::note_compat_assoc)
1359 << Types[i]->getTypeLoc().getSourceRange()
1360 << Types[i]->getType();
1361 TypeErrorFound = true;
1369 // If we determined that the generic selection is result-dependent, don't
1370 // try to compute the result expression.
1371 if (IsResultDependent)
1372 return Owned(new (Context) GenericSelectionExpr(
1373 Context, KeyLoc, ControllingExpr,
1375 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1377 SmallVector<unsigned, 1> CompatIndices;
1378 unsigned DefaultIndex = -1U;
1379 for (unsigned i = 0; i < NumAssocs; ++i) {
1382 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1383 Types[i]->getType()))
1384 CompatIndices.push_back(i);
1387 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1388 // type compatible with at most one of the types named in its generic
1389 // association list."
1390 if (CompatIndices.size() > 1) {
1391 // We strip parens here because the controlling expression is typically
1392 // parenthesized in macro definitions.
1393 ControllingExpr = ControllingExpr->IgnoreParens();
1394 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1395 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1396 << (unsigned) CompatIndices.size();
1397 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1398 E = CompatIndices.end(); I != E; ++I) {
1399 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1400 diag::note_compat_assoc)
1401 << Types[*I]->getTypeLoc().getSourceRange()
1402 << Types[*I]->getType();
1407 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1408 // its controlling expression shall have type compatible with exactly one of
1409 // the types named in its generic association list."
1410 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1411 // We strip parens here because the controlling expression is typically
1412 // parenthesized in macro definitions.
1413 ControllingExpr = ControllingExpr->IgnoreParens();
1414 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1415 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1419 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1420 // type name that is compatible with the type of the controlling expression,
1421 // then the result expression of the generic selection is the expression
1422 // in that generic association. Otherwise, the result expression of the
1423 // generic selection is the expression in the default generic association."
1424 unsigned ResultIndex =
1425 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1427 return Owned(new (Context) GenericSelectionExpr(
1428 Context, KeyLoc, ControllingExpr,
1430 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1434 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1435 /// location of the token and the offset of the ud-suffix within it.
1436 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1438 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1442 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1443 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1444 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1445 IdentifierInfo *UDSuffix,
1446 SourceLocation UDSuffixLoc,
1447 ArrayRef<Expr*> Args,
1448 SourceLocation LitEndLoc) {
1449 assert(Args.size() <= 2 && "too many arguments for literal operator");
1452 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1453 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1454 if (ArgTy[ArgIdx]->isArrayType())
1455 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1458 DeclarationName OpName =
1459 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1460 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1461 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1463 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1464 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1465 /*AllowRaw*/false, /*AllowTemplate*/false,
1466 /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1469 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1472 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1473 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1474 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1475 /// multiple tokens. However, the common case is that StringToks points to one
1479 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1481 assert(NumStringToks && "Must have at least one string!");
1483 StringLiteralParser Literal(StringToks, NumStringToks, PP);
1484 if (Literal.hadError)
1487 SmallVector<SourceLocation, 4> StringTokLocs;
1488 for (unsigned i = 0; i != NumStringToks; ++i)
1489 StringTokLocs.push_back(StringToks[i].getLocation());
1491 QualType CharTy = Context.CharTy;
1492 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1493 if (Literal.isWide()) {
1494 CharTy = Context.getWideCharType();
1495 Kind = StringLiteral::Wide;
1496 } else if (Literal.isUTF8()) {
1497 Kind = StringLiteral::UTF8;
1498 } else if (Literal.isUTF16()) {
1499 CharTy = Context.Char16Ty;
1500 Kind = StringLiteral::UTF16;
1501 } else if (Literal.isUTF32()) {
1502 CharTy = Context.Char32Ty;
1503 Kind = StringLiteral::UTF32;
1504 } else if (Literal.isPascal()) {
1505 CharTy = Context.UnsignedCharTy;
1508 QualType CharTyConst = CharTy;
1509 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1510 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1511 CharTyConst.addConst();
1513 // Get an array type for the string, according to C99 6.4.5. This includes
1514 // the nul terminator character as well as the string length for pascal
1516 QualType StrTy = Context.getConstantArrayType(CharTyConst,
1517 llvm::APInt(32, Literal.GetNumStringChars()+1),
1518 ArrayType::Normal, 0);
1520 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1521 if (getLangOpts().OpenCL) {
1522 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1525 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1526 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1527 Kind, Literal.Pascal, StrTy,
1529 StringTokLocs.size());
1530 if (Literal.getUDSuffix().empty())
1533 // We're building a user-defined literal.
1534 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1535 SourceLocation UDSuffixLoc =
1536 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1537 Literal.getUDSuffixOffset());
1539 // Make sure we're allowed user-defined literals here.
1541 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1543 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1544 // operator "" X (str, len)
1545 QualType SizeType = Context.getSizeType();
1547 DeclarationName OpName =
1548 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1549 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1550 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1552 QualType ArgTy[] = {
1553 Context.getArrayDecayedType(StrTy), SizeType
1556 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1557 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1558 /*AllowRaw*/false, /*AllowTemplate*/false,
1559 /*AllowStringTemplate*/true)) {
1562 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1563 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1565 Expr *Args[] = { Lit, LenArg };
1567 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1570 case LOLR_StringTemplate: {
1571 TemplateArgumentListInfo ExplicitArgs;
1573 unsigned CharBits = Context.getIntWidth(CharTy);
1574 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1575 llvm::APSInt Value(CharBits, CharIsUnsigned);
1577 TemplateArgument TypeArg(CharTy);
1578 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1579 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1581 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1582 Value = Lit->getCodeUnit(I);
1583 TemplateArgument Arg(Context, Value, CharTy);
1584 TemplateArgumentLocInfo ArgInfo;
1585 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1587 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1592 llvm_unreachable("unexpected literal operator lookup result");
1596 llvm_unreachable("unexpected literal operator lookup result");
1600 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1602 const CXXScopeSpec *SS) {
1603 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1604 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1607 /// BuildDeclRefExpr - Build an expression that references a
1608 /// declaration that does not require a closure capture.
1610 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1611 const DeclarationNameInfo &NameInfo,
1612 const CXXScopeSpec *SS, NamedDecl *FoundD,
1613 const TemplateArgumentListInfo *TemplateArgs) {
1614 if (getLangOpts().CUDA)
1615 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1616 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1617 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1618 CalleeTarget = IdentifyCUDATarget(Callee);
1619 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1620 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1621 << CalleeTarget << D->getIdentifier() << CallerTarget;
1622 Diag(D->getLocation(), diag::note_previous_decl)
1623 << D->getIdentifier();
1628 bool refersToEnclosingScope =
1629 (CurContext != D->getDeclContext() &&
1630 D->getDeclContext()->isFunctionOrMethod()) ||
1632 cast<VarDecl>(D)->isInitCapture());
1635 if (isa<VarTemplateSpecializationDecl>(D)) {
1636 VarTemplateSpecializationDecl *VarSpec =
1637 cast<VarTemplateSpecializationDecl>(D);
1639 E = DeclRefExpr::Create(
1641 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1642 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1643 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1645 assert(!TemplateArgs && "No template arguments for non-variable"
1646 " template specialization referrences");
1647 E = DeclRefExpr::Create(
1649 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1650 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1653 MarkDeclRefReferenced(E);
1655 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1656 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1657 DiagnosticsEngine::Level Level =
1658 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1660 if (Level != DiagnosticsEngine::Ignored)
1661 recordUseOfEvaluatedWeak(E);
1664 // Just in case we're building an illegal pointer-to-member.
1665 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1666 if (FD && FD->isBitField())
1667 E->setObjectKind(OK_BitField);
1672 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1673 /// possibly a list of template arguments.
1675 /// If this produces template arguments, it is permitted to call
1676 /// DecomposeTemplateName.
1678 /// This actually loses a lot of source location information for
1679 /// non-standard name kinds; we should consider preserving that in
1682 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1683 TemplateArgumentListInfo &Buffer,
1684 DeclarationNameInfo &NameInfo,
1685 const TemplateArgumentListInfo *&TemplateArgs) {
1686 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1687 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1688 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1690 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1691 Id.TemplateId->NumArgs);
1692 translateTemplateArguments(TemplateArgsPtr, Buffer);
1694 TemplateName TName = Id.TemplateId->Template.get();
1695 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1696 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1697 TemplateArgs = &Buffer;
1699 NameInfo = GetNameFromUnqualifiedId(Id);
1704 /// Diagnose an empty lookup.
1706 /// \return false if new lookup candidates were found
1707 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1708 CorrectionCandidateCallback &CCC,
1709 TemplateArgumentListInfo *ExplicitTemplateArgs,
1710 ArrayRef<Expr *> Args) {
1711 DeclarationName Name = R.getLookupName();
1713 unsigned diagnostic = diag::err_undeclared_var_use;
1714 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1715 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1716 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1717 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1718 diagnostic = diag::err_undeclared_use;
1719 diagnostic_suggest = diag::err_undeclared_use_suggest;
1722 // If the original lookup was an unqualified lookup, fake an
1723 // unqualified lookup. This is useful when (for example) the
1724 // original lookup would not have found something because it was a
1726 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1729 if (isa<CXXRecordDecl>(DC)) {
1730 LookupQualifiedName(R, DC);
1733 // Don't give errors about ambiguities in this lookup.
1734 R.suppressDiagnostics();
1736 // During a default argument instantiation the CurContext points
1737 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1738 // function parameter list, hence add an explicit check.
1739 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1740 ActiveTemplateInstantiations.back().Kind ==
1741 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1742 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1743 bool isInstance = CurMethod &&
1744 CurMethod->isInstance() &&
1745 DC == CurMethod->getParent() && !isDefaultArgument;
1748 // Give a code modification hint to insert 'this->'.
1749 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1750 // Actually quite difficult!
1751 if (getLangOpts().MicrosoftMode)
1752 diagnostic = diag::warn_found_via_dependent_bases_lookup;
1754 Diag(R.getNameLoc(), diagnostic) << Name
1755 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1756 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1757 CallsUndergoingInstantiation.back()->getCallee());
1759 CXXMethodDecl *DepMethod;
1760 if (CurMethod->isDependentContext())
1761 DepMethod = CurMethod;
1762 else if (CurMethod->getTemplatedKind() ==
1763 FunctionDecl::TK_FunctionTemplateSpecialization)
1764 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1765 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1767 DepMethod = cast<CXXMethodDecl>(
1768 CurMethod->getInstantiatedFromMemberFunction());
1769 assert(DepMethod && "No template pattern found");
1771 QualType DepThisType = DepMethod->getThisType(Context);
1772 CheckCXXThisCapture(R.getNameLoc());
1773 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1774 R.getNameLoc(), DepThisType, false);
1775 TemplateArgumentListInfo TList;
1776 if (ULE->hasExplicitTemplateArgs())
1777 ULE->copyTemplateArgumentsInto(TList);
1780 SS.Adopt(ULE->getQualifierLoc());
1781 CXXDependentScopeMemberExpr *DepExpr =
1782 CXXDependentScopeMemberExpr::Create(
1783 Context, DepThis, DepThisType, true, SourceLocation(),
1784 SS.getWithLocInContext(Context),
1785 ULE->getTemplateKeywordLoc(), 0,
1786 R.getLookupNameInfo(),
1787 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1788 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1790 Diag(R.getNameLoc(), diagnostic) << Name;
1793 // Do we really want to note all of these?
1794 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1795 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1797 // Return true if we are inside a default argument instantiation
1798 // and the found name refers to an instance member function, otherwise
1799 // the function calling DiagnoseEmptyLookup will try to create an
1800 // implicit member call and this is wrong for default argument.
1801 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1802 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1806 // Tell the callee to try to recover.
1813 // In Microsoft mode, if we are performing lookup from within a friend
1814 // function definition declared at class scope then we must set
1815 // DC to the lexical parent to be able to search into the parent
1817 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1818 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1819 DC->getLexicalParent()->isRecord())
1820 DC = DC->getLexicalParent();
1822 DC = DC->getParent();
1825 // We didn't find anything, so try to correct for a typo.
1826 TypoCorrection Corrected;
1827 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1829 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1830 bool DroppedSpecifier =
1831 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1832 R.setLookupName(Corrected.getCorrection());
1834 bool AcceptableWithRecovery = false;
1835 bool AcceptableWithoutRecovery = false;
1836 NamedDecl *ND = Corrected.getCorrectionDecl();
1838 if (Corrected.isOverloaded()) {
1839 OverloadCandidateSet OCS(R.getNameLoc());
1840 OverloadCandidateSet::iterator Best;
1841 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1842 CDEnd = Corrected.end();
1843 CD != CDEnd; ++CD) {
1844 if (FunctionTemplateDecl *FTD =
1845 dyn_cast<FunctionTemplateDecl>(*CD))
1846 AddTemplateOverloadCandidate(
1847 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1849 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1850 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1851 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1854 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1856 ND = Best->Function;
1857 Corrected.setCorrectionDecl(ND);
1860 // FIXME: Arbitrarily pick the first declaration for the note.
1861 Corrected.setCorrectionDecl(ND);
1867 AcceptableWithRecovery =
1868 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1869 // FIXME: If we ended up with a typo for a type name or
1870 // Objective-C class name, we're in trouble because the parser
1871 // is in the wrong place to recover. Suggest the typo
1872 // correction, but don't make it a fix-it since we're not going
1873 // to recover well anyway.
1874 AcceptableWithoutRecovery =
1875 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1877 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1878 // because we aren't able to recover.
1879 AcceptableWithoutRecovery = true;
1882 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1883 unsigned NoteID = (Corrected.getCorrectionDecl() &&
1884 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1885 ? diag::note_implicit_param_decl
1886 : diag::note_previous_decl;
1888 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1889 PDiag(NoteID), AcceptableWithRecovery);
1891 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1892 << Name << computeDeclContext(SS, false)
1893 << DroppedSpecifier << SS.getRange(),
1894 PDiag(NoteID), AcceptableWithRecovery);
1896 // Tell the callee whether to try to recover.
1897 return !AcceptableWithRecovery;
1902 // Emit a special diagnostic for failed member lookups.
1903 // FIXME: computing the declaration context might fail here (?)
1904 if (!SS.isEmpty()) {
1905 Diag(R.getNameLoc(), diag::err_no_member)
1906 << Name << computeDeclContext(SS, false)
1911 // Give up, we can't recover.
1912 Diag(R.getNameLoc(), diagnostic) << Name;
1916 ExprResult Sema::ActOnIdExpression(Scope *S,
1918 SourceLocation TemplateKWLoc,
1920 bool HasTrailingLParen,
1921 bool IsAddressOfOperand,
1922 CorrectionCandidateCallback *CCC,
1923 bool IsInlineAsmIdentifier) {
1924 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1925 "cannot be direct & operand and have a trailing lparen");
1929 TemplateArgumentListInfo TemplateArgsBuffer;
1931 // Decompose the UnqualifiedId into the following data.
1932 DeclarationNameInfo NameInfo;
1933 const TemplateArgumentListInfo *TemplateArgs;
1934 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1936 DeclarationName Name = NameInfo.getName();
1937 IdentifierInfo *II = Name.getAsIdentifierInfo();
1938 SourceLocation NameLoc = NameInfo.getLoc();
1940 // C++ [temp.dep.expr]p3:
1941 // An id-expression is type-dependent if it contains:
1942 // -- an identifier that was declared with a dependent type,
1943 // (note: handled after lookup)
1944 // -- a template-id that is dependent,
1945 // (note: handled in BuildTemplateIdExpr)
1946 // -- a conversion-function-id that specifies a dependent type,
1947 // -- a nested-name-specifier that contains a class-name that
1948 // names a dependent type.
1949 // Determine whether this is a member of an unknown specialization;
1950 // we need to handle these differently.
1951 bool DependentID = false;
1952 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1953 Name.getCXXNameType()->isDependentType()) {
1955 } else if (SS.isSet()) {
1956 if (DeclContext *DC = computeDeclContext(SS, false)) {
1957 if (RequireCompleteDeclContext(SS, DC))
1965 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1966 IsAddressOfOperand, TemplateArgs);
1968 // Perform the required lookup.
1969 LookupResult R(*this, NameInfo,
1970 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1971 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1973 // Lookup the template name again to correctly establish the context in
1974 // which it was found. This is really unfortunate as we already did the
1975 // lookup to determine that it was a template name in the first place. If
1976 // this becomes a performance hit, we can work harder to preserve those
1977 // results until we get here but it's likely not worth it.
1978 bool MemberOfUnknownSpecialization;
1979 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1980 MemberOfUnknownSpecialization);
1982 if (MemberOfUnknownSpecialization ||
1983 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1984 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1985 IsAddressOfOperand, TemplateArgs);
1987 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1988 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1990 // If the result might be in a dependent base class, this is a dependent
1992 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1993 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1994 IsAddressOfOperand, TemplateArgs);
1996 // If this reference is in an Objective-C method, then we need to do
1997 // some special Objective-C lookup, too.
1998 if (IvarLookupFollowUp) {
1999 ExprResult E(LookupInObjCMethod(R, S, II, true));
2003 if (Expr *Ex = E.takeAs<Expr>())
2008 if (R.isAmbiguous())
2011 // Determine whether this name might be a candidate for
2012 // argument-dependent lookup.
2013 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2015 if (R.empty() && !ADL) {
2017 // Otherwise, this could be an implicitly declared function reference (legal
2018 // in C90, extension in C99, forbidden in C++).
2019 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2020 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2021 if (D) R.addDecl(D);
2024 // If this name wasn't predeclared and if this is not a function
2025 // call, diagnose the problem.
2027 // In Microsoft mode, if we are inside a template class member function
2028 // whose parent class has dependent base classes, and we can't resolve
2029 // an identifier, then assume the identifier is a member of a dependent
2030 // base class. The goal is to postpone name lookup to instantiation time
2031 // to be able to search into the type dependent base classes.
2032 // FIXME: If we want 100% compatibility with MSVC, we will have delay all
2033 // unqualified name lookup. Any name lookup during template parsing means
2034 // clang might find something that MSVC doesn't. For now, we only handle
2035 // the common case of members of a dependent base class.
2036 if (getLangOpts().MicrosoftMode) {
2037 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2038 if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) {
2039 assert(SS.isEmpty() && "qualifiers should be already handled");
2040 QualType ThisType = MD->getThisType(Context);
2041 // Since the 'this' expression is synthesized, we don't need to
2042 // perform the double-lookup check.
2043 NamedDecl *FirstQualifierInScope = 0;
2044 return Owned(CXXDependentScopeMemberExpr::Create(
2045 Context, /*This=*/0, ThisType, /*IsArrow=*/true,
2046 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context),
2047 TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs));
2051 // Don't diagnose an empty lookup for inline assmebly.
2052 if (IsInlineAsmIdentifier)
2055 CorrectionCandidateCallback DefaultValidator;
2056 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2059 assert(!R.empty() &&
2060 "DiagnoseEmptyLookup returned false but added no results");
2062 // If we found an Objective-C instance variable, let
2063 // LookupInObjCMethod build the appropriate expression to
2064 // reference the ivar.
2065 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2067 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2068 // In a hopelessly buggy code, Objective-C instance variable
2069 // lookup fails and no expression will be built to reference it.
2070 if (!E.isInvalid() && !E.get())
2077 // This is guaranteed from this point on.
2078 assert(!R.empty() || ADL);
2080 // Check whether this might be a C++ implicit instance member access.
2081 // C++ [class.mfct.non-static]p3:
2082 // When an id-expression that is not part of a class member access
2083 // syntax and not used to form a pointer to member is used in the
2084 // body of a non-static member function of class X, if name lookup
2085 // resolves the name in the id-expression to a non-static non-type
2086 // member of some class C, the id-expression is transformed into a
2087 // class member access expression using (*this) as the
2088 // postfix-expression to the left of the . operator.
2090 // But we don't actually need to do this for '&' operands if R
2091 // resolved to a function or overloaded function set, because the
2092 // expression is ill-formed if it actually works out to be a
2093 // non-static member function:
2095 // C++ [expr.ref]p4:
2096 // Otherwise, if E1.E2 refers to a non-static member function. . .
2097 // [t]he expression can be used only as the left-hand operand of a
2098 // member function call.
2100 // There are other safeguards against such uses, but it's important
2101 // to get this right here so that we don't end up making a
2102 // spuriously dependent expression if we're inside a dependent
2104 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2105 bool MightBeImplicitMember;
2106 if (!IsAddressOfOperand)
2107 MightBeImplicitMember = true;
2108 else if (!SS.isEmpty())
2109 MightBeImplicitMember = false;
2110 else if (R.isOverloadedResult())
2111 MightBeImplicitMember = false;
2112 else if (R.isUnresolvableResult())
2113 MightBeImplicitMember = true;
2115 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2116 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2117 isa<MSPropertyDecl>(R.getFoundDecl());
2119 if (MightBeImplicitMember)
2120 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2124 if (TemplateArgs || TemplateKWLoc.isValid()) {
2126 // In C++1y, if this is a variable template id, then check it
2127 // in BuildTemplateIdExpr().
2128 // The single lookup result must be a variable template declaration.
2129 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2130 Id.TemplateId->Kind == TNK_Var_template) {
2131 assert(R.getAsSingle<VarTemplateDecl>() &&
2132 "There should only be one declaration found.");
2135 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2138 return BuildDeclarationNameExpr(SS, R, ADL);
2141 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2142 /// declaration name, generally during template instantiation.
2143 /// There's a large number of things which don't need to be done along
2146 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2147 const DeclarationNameInfo &NameInfo,
2148 bool IsAddressOfOperand) {
2149 DeclContext *DC = computeDeclContext(SS, false);
2151 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2152 NameInfo, /*TemplateArgs=*/0);
2154 if (RequireCompleteDeclContext(SS, DC))
2157 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2158 LookupQualifiedName(R, DC);
2160 if (R.isAmbiguous())
2163 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2164 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2165 NameInfo, /*TemplateArgs=*/0);
2168 Diag(NameInfo.getLoc(), diag::err_no_member)
2169 << NameInfo.getName() << DC << SS.getRange();
2173 // Defend against this resolving to an implicit member access. We usually
2174 // won't get here if this might be a legitimate a class member (we end up in
2175 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2176 // a pointer-to-member or in an unevaluated context in C++11.
2177 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2178 return BuildPossibleImplicitMemberExpr(SS,
2179 /*TemplateKWLoc=*/SourceLocation(),
2180 R, /*TemplateArgs=*/0);
2182 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2185 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2186 /// detected that we're currently inside an ObjC method. Perform some
2187 /// additional lookup.
2189 /// Ideally, most of this would be done by lookup, but there's
2190 /// actually quite a lot of extra work involved.
2192 /// Returns a null sentinel to indicate trivial success.
2194 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2195 IdentifierInfo *II, bool AllowBuiltinCreation) {
2196 SourceLocation Loc = Lookup.getNameLoc();
2197 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2199 // Check for error condition which is already reported.
2203 // There are two cases to handle here. 1) scoped lookup could have failed,
2204 // in which case we should look for an ivar. 2) scoped lookup could have
2205 // found a decl, but that decl is outside the current instance method (i.e.
2206 // a global variable). In these two cases, we do a lookup for an ivar with
2207 // this name, if the lookup sucedes, we replace it our current decl.
2209 // If we're in a class method, we don't normally want to look for
2210 // ivars. But if we don't find anything else, and there's an
2211 // ivar, that's an error.
2212 bool IsClassMethod = CurMethod->isClassMethod();
2216 LookForIvars = true;
2217 else if (IsClassMethod)
2218 LookForIvars = false;
2220 LookForIvars = (Lookup.isSingleResult() &&
2221 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2222 ObjCInterfaceDecl *IFace = 0;
2224 IFace = CurMethod->getClassInterface();
2225 ObjCInterfaceDecl *ClassDeclared;
2226 ObjCIvarDecl *IV = 0;
2227 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2228 // Diagnose using an ivar in a class method.
2230 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2231 << IV->getDeclName());
2233 // If we're referencing an invalid decl, just return this as a silent
2234 // error node. The error diagnostic was already emitted on the decl.
2235 if (IV->isInvalidDecl())
2238 // Check if referencing a field with __attribute__((deprecated)).
2239 if (DiagnoseUseOfDecl(IV, Loc))
2242 // Diagnose the use of an ivar outside of the declaring class.
2243 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2244 !declaresSameEntity(ClassDeclared, IFace) &&
2245 !getLangOpts().DebuggerSupport)
2246 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2248 // FIXME: This should use a new expr for a direct reference, don't
2249 // turn this into Self->ivar, just return a BareIVarExpr or something.
2250 IdentifierInfo &II = Context.Idents.get("self");
2251 UnqualifiedId SelfName;
2252 SelfName.setIdentifier(&II, SourceLocation());
2253 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2254 CXXScopeSpec SelfScopeSpec;
2255 SourceLocation TemplateKWLoc;
2256 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2257 SelfName, false, false);
2258 if (SelfExpr.isInvalid())
2261 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2262 if (SelfExpr.isInvalid())
2265 MarkAnyDeclReferenced(Loc, IV, true);
2266 if (!IV->getBackingIvarReferencedInAccessor()) {
2267 // Mark this ivar 'referenced' in this method, if it is a backing ivar
2268 // of a property and current method is one of its property accessor.
2269 const ObjCPropertyDecl *PDecl;
2270 const ObjCIvarDecl *BIV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
2271 if (BIV && BIV == IV)
2272 IV->setBackingIvarReferencedInAccessor(true);
2275 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2276 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2277 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2278 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2280 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2281 Loc, IV->getLocation(),
2285 if (getLangOpts().ObjCAutoRefCount) {
2286 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2287 DiagnosticsEngine::Level Level =
2288 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2289 if (Level != DiagnosticsEngine::Ignored)
2290 recordUseOfEvaluatedWeak(Result);
2292 if (CurContext->isClosure())
2293 Diag(Loc, diag::warn_implicitly_retains_self)
2294 << FixItHint::CreateInsertion(Loc, "self->");
2297 return Owned(Result);
2299 } else if (CurMethod->isInstanceMethod()) {
2300 // We should warn if a local variable hides an ivar.
2301 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2302 ObjCInterfaceDecl *ClassDeclared;
2303 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2304 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2305 declaresSameEntity(IFace, ClassDeclared))
2306 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2309 } else if (Lookup.isSingleResult() &&
2310 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2311 // If accessing a stand-alone ivar in a class method, this is an error.
2312 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2313 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2314 << IV->getDeclName());
2317 if (Lookup.empty() && II && AllowBuiltinCreation) {
2318 // FIXME. Consolidate this with similar code in LookupName.
2319 if (unsigned BuiltinID = II->getBuiltinID()) {
2320 if (!(getLangOpts().CPlusPlus &&
2321 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2322 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2323 S, Lookup.isForRedeclaration(),
2324 Lookup.getNameLoc());
2325 if (D) Lookup.addDecl(D);
2329 // Sentinel value saying that we didn't do anything special.
2330 return Owned((Expr*) 0);
2333 /// \brief Cast a base object to a member's actual type.
2335 /// Logically this happens in three phases:
2337 /// * First we cast from the base type to the naming class.
2338 /// The naming class is the class into which we were looking
2339 /// when we found the member; it's the qualifier type if a
2340 /// qualifier was provided, and otherwise it's the base type.
2342 /// * Next we cast from the naming class to the declaring class.
2343 /// If the member we found was brought into a class's scope by
2344 /// a using declaration, this is that class; otherwise it's
2345 /// the class declaring the member.
2347 /// * Finally we cast from the declaring class to the "true"
2348 /// declaring class of the member. This conversion does not
2349 /// obey access control.
2351 Sema::PerformObjectMemberConversion(Expr *From,
2352 NestedNameSpecifier *Qualifier,
2353 NamedDecl *FoundDecl,
2354 NamedDecl *Member) {
2355 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2359 QualType DestRecordType;
2361 QualType FromRecordType;
2362 QualType FromType = From->getType();
2363 bool PointerConversions = false;
2364 if (isa<FieldDecl>(Member)) {
2365 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2367 if (FromType->getAs<PointerType>()) {
2368 DestType = Context.getPointerType(DestRecordType);
2369 FromRecordType = FromType->getPointeeType();
2370 PointerConversions = true;
2372 DestType = DestRecordType;
2373 FromRecordType = FromType;
2375 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2376 if (Method->isStatic())
2379 DestType = Method->getThisType(Context);
2380 DestRecordType = DestType->getPointeeType();
2382 if (FromType->getAs<PointerType>()) {
2383 FromRecordType = FromType->getPointeeType();
2384 PointerConversions = true;
2386 FromRecordType = FromType;
2387 DestType = DestRecordType;
2390 // No conversion necessary.
2394 if (DestType->isDependentType() || FromType->isDependentType())
2397 // If the unqualified types are the same, no conversion is necessary.
2398 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2401 SourceRange FromRange = From->getSourceRange();
2402 SourceLocation FromLoc = FromRange.getBegin();
2404 ExprValueKind VK = From->getValueKind();
2406 // C++ [class.member.lookup]p8:
2407 // [...] Ambiguities can often be resolved by qualifying a name with its
2410 // If the member was a qualified name and the qualified referred to a
2411 // specific base subobject type, we'll cast to that intermediate type
2412 // first and then to the object in which the member is declared. That allows
2413 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2415 // class Base { public: int x; };
2416 // class Derived1 : public Base { };
2417 // class Derived2 : public Base { };
2418 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2420 // void VeryDerived::f() {
2421 // x = 17; // error: ambiguous base subobjects
2422 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2424 if (Qualifier && Qualifier->getAsType()) {
2425 QualType QType = QualType(Qualifier->getAsType(), 0);
2426 assert(QType->isRecordType() && "lookup done with non-record type");
2428 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2430 // In C++98, the qualifier type doesn't actually have to be a base
2431 // type of the object type, in which case we just ignore it.
2432 // Otherwise build the appropriate casts.
2433 if (IsDerivedFrom(FromRecordType, QRecordType)) {
2434 CXXCastPath BasePath;
2435 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2436 FromLoc, FromRange, &BasePath))
2439 if (PointerConversions)
2440 QType = Context.getPointerType(QType);
2441 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2442 VK, &BasePath).take();
2445 FromRecordType = QRecordType;
2447 // If the qualifier type was the same as the destination type,
2449 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2454 bool IgnoreAccess = false;
2456 // If we actually found the member through a using declaration, cast
2457 // down to the using declaration's type.
2459 // Pointer equality is fine here because only one declaration of a
2460 // class ever has member declarations.
2461 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2462 assert(isa<UsingShadowDecl>(FoundDecl));
2463 QualType URecordType = Context.getTypeDeclType(
2464 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2466 // We only need to do this if the naming-class to declaring-class
2467 // conversion is non-trivial.
2468 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2469 assert(IsDerivedFrom(FromRecordType, URecordType));
2470 CXXCastPath BasePath;
2471 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2472 FromLoc, FromRange, &BasePath))
2475 QualType UType = URecordType;
2476 if (PointerConversions)
2477 UType = Context.getPointerType(UType);
2478 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2479 VK, &BasePath).take();
2481 FromRecordType = URecordType;
2484 // We don't do access control for the conversion from the
2485 // declaring class to the true declaring class.
2486 IgnoreAccess = true;
2489 CXXCastPath BasePath;
2490 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2491 FromLoc, FromRange, &BasePath,
2495 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2499 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2500 const LookupResult &R,
2501 bool HasTrailingLParen) {
2502 // Only when used directly as the postfix-expression of a call.
2503 if (!HasTrailingLParen)
2506 // Never if a scope specifier was provided.
2510 // Only in C++ or ObjC++.
2511 if (!getLangOpts().CPlusPlus)
2514 // Turn off ADL when we find certain kinds of declarations during
2516 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2519 // C++0x [basic.lookup.argdep]p3:
2520 // -- a declaration of a class member
2521 // Since using decls preserve this property, we check this on the
2523 if (D->isCXXClassMember())
2526 // C++0x [basic.lookup.argdep]p3:
2527 // -- a block-scope function declaration that is not a
2528 // using-declaration
2529 // NOTE: we also trigger this for function templates (in fact, we
2530 // don't check the decl type at all, since all other decl types
2531 // turn off ADL anyway).
2532 if (isa<UsingShadowDecl>(D))
2533 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2534 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2537 // C++0x [basic.lookup.argdep]p3:
2538 // -- a declaration that is neither a function or a function
2540 // And also for builtin functions.
2541 if (isa<FunctionDecl>(D)) {
2542 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2544 // But also builtin functions.
2545 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2547 } else if (!isa<FunctionTemplateDecl>(D))
2555 /// Diagnoses obvious problems with the use of the given declaration
2556 /// as an expression. This is only actually called for lookups that
2557 /// were not overloaded, and it doesn't promise that the declaration
2558 /// will in fact be used.
2559 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2560 if (isa<TypedefNameDecl>(D)) {
2561 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2565 if (isa<ObjCInterfaceDecl>(D)) {
2566 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2570 if (isa<NamespaceDecl>(D)) {
2571 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2579 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2582 // If this is a single, fully-resolved result and we don't need ADL,
2583 // just build an ordinary singleton decl ref.
2584 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2585 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2586 R.getRepresentativeDecl());
2588 // We only need to check the declaration if there's exactly one
2589 // result, because in the overloaded case the results can only be
2590 // functions and function templates.
2591 if (R.isSingleResult() &&
2592 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2595 // Otherwise, just build an unresolved lookup expression. Suppress
2596 // any lookup-related diagnostics; we'll hash these out later, when
2597 // we've picked a target.
2598 R.suppressDiagnostics();
2600 UnresolvedLookupExpr *ULE
2601 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2602 SS.getWithLocInContext(Context),
2603 R.getLookupNameInfo(),
2604 NeedsADL, R.isOverloadedResult(),
2605 R.begin(), R.end());
2610 /// \brief Complete semantic analysis for a reference to the given declaration.
2611 ExprResult Sema::BuildDeclarationNameExpr(
2612 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2613 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2614 assert(D && "Cannot refer to a NULL declaration");
2615 assert(!isa<FunctionTemplateDecl>(D) &&
2616 "Cannot refer unambiguously to a function template");
2618 SourceLocation Loc = NameInfo.getLoc();
2619 if (CheckDeclInExpr(*this, Loc, D))
2622 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2623 // Specifically diagnose references to class templates that are missing
2624 // a template argument list.
2625 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2626 << Template << SS.getRange();
2627 Diag(Template->getLocation(), diag::note_template_decl_here);
2631 // Make sure that we're referring to a value.
2632 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2634 Diag(Loc, diag::err_ref_non_value)
2635 << D << SS.getRange();
2636 Diag(D->getLocation(), diag::note_declared_at);
2640 // Check whether this declaration can be used. Note that we suppress
2641 // this check when we're going to perform argument-dependent lookup
2642 // on this function name, because this might not be the function
2643 // that overload resolution actually selects.
2644 if (DiagnoseUseOfDecl(VD, Loc))
2647 // Only create DeclRefExpr's for valid Decl's.
2648 if (VD->isInvalidDecl())
2651 // Handle members of anonymous structs and unions. If we got here,
2652 // and the reference is to a class member indirect field, then this
2653 // must be the subject of a pointer-to-member expression.
2654 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2655 if (!indirectField->isCXXClassMember())
2656 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2660 QualType type = VD->getType();
2661 ExprValueKind valueKind = VK_RValue;
2663 switch (D->getKind()) {
2664 // Ignore all the non-ValueDecl kinds.
2665 #define ABSTRACT_DECL(kind)
2666 #define VALUE(type, base)
2667 #define DECL(type, base) \
2669 #include "clang/AST/DeclNodes.inc"
2670 llvm_unreachable("invalid value decl kind");
2672 // These shouldn't make it here.
2673 case Decl::ObjCAtDefsField:
2674 case Decl::ObjCIvar:
2675 llvm_unreachable("forming non-member reference to ivar?");
2677 // Enum constants are always r-values and never references.
2678 // Unresolved using declarations are dependent.
2679 case Decl::EnumConstant:
2680 case Decl::UnresolvedUsingValue:
2681 valueKind = VK_RValue;
2684 // Fields and indirect fields that got here must be for
2685 // pointer-to-member expressions; we just call them l-values for
2686 // internal consistency, because this subexpression doesn't really
2687 // exist in the high-level semantics.
2689 case Decl::IndirectField:
2690 assert(getLangOpts().CPlusPlus &&
2691 "building reference to field in C?");
2693 // These can't have reference type in well-formed programs, but
2694 // for internal consistency we do this anyway.
2695 type = type.getNonReferenceType();
2696 valueKind = VK_LValue;
2699 // Non-type template parameters are either l-values or r-values
2700 // depending on the type.
2701 case Decl::NonTypeTemplateParm: {
2702 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2703 type = reftype->getPointeeType();
2704 valueKind = VK_LValue; // even if the parameter is an r-value reference
2708 // For non-references, we need to strip qualifiers just in case
2709 // the template parameter was declared as 'const int' or whatever.
2710 valueKind = VK_RValue;
2711 type = type.getUnqualifiedType();
2716 case Decl::VarTemplateSpecialization:
2717 case Decl::VarTemplatePartialSpecialization:
2718 // In C, "extern void blah;" is valid and is an r-value.
2719 if (!getLangOpts().CPlusPlus &&
2720 !type.hasQualifiers() &&
2721 type->isVoidType()) {
2722 valueKind = VK_RValue;
2727 case Decl::ImplicitParam:
2728 case Decl::ParmVar: {
2729 // These are always l-values.
2730 valueKind = VK_LValue;
2731 type = type.getNonReferenceType();
2733 // FIXME: Does the addition of const really only apply in
2734 // potentially-evaluated contexts? Since the variable isn't actually
2735 // captured in an unevaluated context, it seems that the answer is no.
2736 if (!isUnevaluatedContext()) {
2737 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2738 if (!CapturedType.isNull())
2739 type = CapturedType;
2745 case Decl::Function: {
2746 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2747 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2748 type = Context.BuiltinFnTy;
2749 valueKind = VK_RValue;
2754 const FunctionType *fty = type->castAs<FunctionType>();
2756 // If we're referring to a function with an __unknown_anytype
2757 // result type, make the entire expression __unknown_anytype.
2758 if (fty->getResultType() == Context.UnknownAnyTy) {
2759 type = Context.UnknownAnyTy;
2760 valueKind = VK_RValue;
2764 // Functions are l-values in C++.
2765 if (getLangOpts().CPlusPlus) {
2766 valueKind = VK_LValue;
2770 // C99 DR 316 says that, if a function type comes from a
2771 // function definition (without a prototype), that type is only
2772 // used for checking compatibility. Therefore, when referencing
2773 // the function, we pretend that we don't have the full function
2775 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2776 isa<FunctionProtoType>(fty))
2777 type = Context.getFunctionNoProtoType(fty->getResultType(),
2780 // Functions are r-values in C.
2781 valueKind = VK_RValue;
2785 case Decl::MSProperty:
2786 valueKind = VK_LValue;
2789 case Decl::CXXMethod:
2790 // If we're referring to a method with an __unknown_anytype
2791 // result type, make the entire expression __unknown_anytype.
2792 // This should only be possible with a type written directly.
2793 if (const FunctionProtoType *proto
2794 = dyn_cast<FunctionProtoType>(VD->getType()))
2795 if (proto->getResultType() == Context.UnknownAnyTy) {
2796 type = Context.UnknownAnyTy;
2797 valueKind = VK_RValue;
2801 // C++ methods are l-values if static, r-values if non-static.
2802 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2803 valueKind = VK_LValue;
2808 case Decl::CXXConversion:
2809 case Decl::CXXDestructor:
2810 case Decl::CXXConstructor:
2811 valueKind = VK_RValue;
2815 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2820 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2821 PredefinedExpr::IdentType IT) {
2822 // Pick the current block, lambda, captured statement or function.
2823 Decl *currentDecl = 0;
2824 if (const BlockScopeInfo *BSI = getCurBlock())
2825 currentDecl = BSI->TheDecl;
2826 else if (const LambdaScopeInfo *LSI = getCurLambda())
2827 currentDecl = LSI->CallOperator;
2828 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2829 currentDecl = CSI->TheCapturedDecl;
2831 currentDecl = getCurFunctionOrMethodDecl();
2834 Diag(Loc, diag::ext_predef_outside_function);
2835 currentDecl = Context.getTranslationUnitDecl();
2839 if (cast<DeclContext>(currentDecl)->isDependentContext())
2840 ResTy = Context.DependentTy;
2842 // Pre-defined identifiers are of type char[x], where x is the length of
2844 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2846 llvm::APInt LengthI(32, Length + 1);
2847 if (IT == PredefinedExpr::LFunction)
2848 ResTy = Context.WideCharTy.withConst();
2850 ResTy = Context.CharTy.withConst();
2851 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2854 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2857 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2858 PredefinedExpr::IdentType IT;
2861 default: llvm_unreachable("Unknown simple primary expr!");
2862 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2863 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2864 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2865 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2866 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2869 return BuildPredefinedExpr(Loc, IT);
2872 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2873 SmallString<16> CharBuffer;
2874 bool Invalid = false;
2875 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2879 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2881 if (Literal.hadError())
2885 if (Literal.isWide())
2886 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2887 else if (Literal.isUTF16())
2888 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2889 else if (Literal.isUTF32())
2890 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2891 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2892 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
2894 Ty = Context.CharTy; // 'x' -> char in C++
2896 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2897 if (Literal.isWide())
2898 Kind = CharacterLiteral::Wide;
2899 else if (Literal.isUTF16())
2900 Kind = CharacterLiteral::UTF16;
2901 else if (Literal.isUTF32())
2902 Kind = CharacterLiteral::UTF32;
2904 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2907 if (Literal.getUDSuffix().empty())
2910 // We're building a user-defined literal.
2911 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2912 SourceLocation UDSuffixLoc =
2913 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2915 // Make sure we're allowed user-defined literals here.
2917 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2919 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2920 // operator "" X (ch)
2921 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2922 Lit, Tok.getLocation());
2925 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2926 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2927 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2928 Context.IntTy, Loc));
2931 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2932 QualType Ty, SourceLocation Loc) {
2933 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2935 using llvm::APFloat;
2936 APFloat Val(Format);
2938 APFloat::opStatus result = Literal.GetFloatValue(Val);
2940 // Overflow is always an error, but underflow is only an error if
2941 // we underflowed to zero (APFloat reports denormals as underflow).
2942 if ((result & APFloat::opOverflow) ||
2943 ((result & APFloat::opUnderflow) && Val.isZero())) {
2944 unsigned diagnostic;
2945 SmallString<20> buffer;
2946 if (result & APFloat::opOverflow) {
2947 diagnostic = diag::warn_float_overflow;
2948 APFloat::getLargest(Format).toString(buffer);
2950 diagnostic = diag::warn_float_underflow;
2951 APFloat::getSmallest(Format).toString(buffer);
2954 S.Diag(Loc, diagnostic)
2956 << StringRef(buffer.data(), buffer.size());
2959 bool isExact = (result == APFloat::opOK);
2960 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2963 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2964 // Fast path for a single digit (which is quite common). A single digit
2965 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2966 if (Tok.getLength() == 1) {
2967 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2968 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2971 SmallString<128> SpellingBuffer;
2972 // NumericLiteralParser wants to overread by one character. Add padding to
2973 // the buffer in case the token is copied to the buffer. If getSpelling()
2974 // returns a StringRef to the memory buffer, it should have a null char at
2975 // the EOF, so it is also safe.
2976 SpellingBuffer.resize(Tok.getLength() + 1);
2978 // Get the spelling of the token, which eliminates trigraphs, etc.
2979 bool Invalid = false;
2980 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2984 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2985 if (Literal.hadError)
2988 if (Literal.hasUDSuffix()) {
2989 // We're building a user-defined literal.
2990 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2991 SourceLocation UDSuffixLoc =
2992 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2994 // Make sure we're allowed user-defined literals here.
2996 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2999 if (Literal.isFloatingLiteral()) {
3000 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3001 // long double, the literal is treated as a call of the form
3002 // operator "" X (f L)
3003 CookedTy = Context.LongDoubleTy;
3005 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3006 // unsigned long long, the literal is treated as a call of the form
3007 // operator "" X (n ULL)
3008 CookedTy = Context.UnsignedLongLongTy;
3011 DeclarationName OpName =
3012 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3013 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3014 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3016 SourceLocation TokLoc = Tok.getLocation();
3018 // Perform literal operator lookup to determine if we're building a raw
3019 // literal or a cooked one.
3020 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3021 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3022 /*AllowRaw*/true, /*AllowTemplate*/true,
3023 /*AllowStringTemplate*/false)) {
3029 if (Literal.isFloatingLiteral()) {
3030 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3032 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3033 if (Literal.GetIntegerValue(ResultVal))
3034 Diag(Tok.getLocation(), diag::err_integer_too_large);
3035 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3038 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3042 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3043 // literal is treated as a call of the form
3044 // operator "" X ("n")
3045 unsigned Length = Literal.getUDSuffixOffset();
3046 QualType StrTy = Context.getConstantArrayType(
3047 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3048 ArrayType::Normal, 0);
3049 Expr *Lit = StringLiteral::Create(
3050 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3051 /*Pascal*/false, StrTy, &TokLoc, 1);
3052 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3055 case LOLR_Template: {
3056 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3057 // template), L is treated as a call fo the form
3058 // operator "" X <'c1', 'c2', ... 'ck'>()
3059 // where n is the source character sequence c1 c2 ... ck.
3060 TemplateArgumentListInfo ExplicitArgs;
3061 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3062 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3063 llvm::APSInt Value(CharBits, CharIsUnsigned);
3064 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3065 Value = TokSpelling[I];
3066 TemplateArgument Arg(Context, Value, Context.CharTy);
3067 TemplateArgumentLocInfo ArgInfo;
3068 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3070 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3073 case LOLR_StringTemplate:
3074 llvm_unreachable("unexpected literal operator lookup result");
3080 if (Literal.isFloatingLiteral()) {
3082 if (Literal.isFloat)
3083 Ty = Context.FloatTy;
3084 else if (!Literal.isLong)
3085 Ty = Context.DoubleTy;
3087 Ty = Context.LongDoubleTy;
3089 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3091 if (Ty == Context.DoubleTy) {
3092 if (getLangOpts().SinglePrecisionConstants) {
3093 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3094 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3095 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3096 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3099 } else if (!Literal.isIntegerLiteral()) {
3104 // 'long long' is a C99 or C++11 feature.
3105 if (!getLangOpts().C99 && Literal.isLongLong) {
3106 if (getLangOpts().CPlusPlus)
3107 Diag(Tok.getLocation(),
3108 getLangOpts().CPlusPlus11 ?
3109 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3111 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3114 // Get the value in the widest-possible width.
3115 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3116 // The microsoft literal suffix extensions support 128-bit literals, which
3117 // may be wider than [u]intmax_t.
3118 // FIXME: Actually, they don't. We seem to have accidentally invented the
3120 if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3121 PP.getTargetInfo().hasInt128Type())
3123 llvm::APInt ResultVal(MaxWidth, 0);
3125 if (Literal.GetIntegerValue(ResultVal)) {
3126 // If this value didn't fit into uintmax_t, error and force to ull.
3127 Diag(Tok.getLocation(), diag::err_integer_too_large);
3128 Ty = Context.UnsignedLongLongTy;
3129 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3130 "long long is not intmax_t?");
3132 // If this value fits into a ULL, try to figure out what else it fits into
3133 // according to the rules of C99 6.4.4.1p5.
3135 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3136 // be an unsigned int.
3137 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3139 // Check from smallest to largest, picking the smallest type we can.
3141 if (!Literal.isLong && !Literal.isLongLong) {
3142 // Are int/unsigned possibilities?
3143 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3145 // Does it fit in a unsigned int?
3146 if (ResultVal.isIntN(IntSize)) {
3147 // Does it fit in a signed int?
3148 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3150 else if (AllowUnsigned)
3151 Ty = Context.UnsignedIntTy;
3156 // Are long/unsigned long possibilities?
3157 if (Ty.isNull() && !Literal.isLongLong) {
3158 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3160 // Does it fit in a unsigned long?
3161 if (ResultVal.isIntN(LongSize)) {
3162 // Does it fit in a signed long?
3163 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3164 Ty = Context.LongTy;
3165 else if (AllowUnsigned)
3166 Ty = Context.UnsignedLongTy;
3171 // Check long long if needed.
3173 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3175 // Does it fit in a unsigned long long?
3176 if (ResultVal.isIntN(LongLongSize)) {
3177 // Does it fit in a signed long long?
3178 // To be compatible with MSVC, hex integer literals ending with the
3179 // LL or i64 suffix are always signed in Microsoft mode.
3180 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3181 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3182 Ty = Context.LongLongTy;
3183 else if (AllowUnsigned)
3184 Ty = Context.UnsignedLongLongTy;
3185 Width = LongLongSize;
3189 // If it doesn't fit in unsigned long long, and we're using Microsoft
3190 // extensions, then its a 128-bit integer literal.
3191 if (Ty.isNull() && Literal.isMicrosoftInteger &&
3192 PP.getTargetInfo().hasInt128Type()) {
3193 if (Literal.isUnsigned)
3194 Ty = Context.UnsignedInt128Ty;
3196 Ty = Context.Int128Ty;
3200 // If we still couldn't decide a type, we probably have something that
3201 // does not fit in a signed long long, but has no U suffix.
3203 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3204 Ty = Context.UnsignedLongLongTy;
3205 Width = Context.getTargetInfo().getLongLongWidth();
3208 if (ResultVal.getBitWidth() != Width)
3209 ResultVal = ResultVal.trunc(Width);
3211 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3214 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3215 if (Literal.isImaginary)
3216 Res = new (Context) ImaginaryLiteral(Res,
3217 Context.getComplexType(Res->getType()));
3222 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3223 assert((E != 0) && "ActOnParenExpr() missing expr");
3224 return Owned(new (Context) ParenExpr(L, R, E));
3227 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3229 SourceRange ArgRange) {
3230 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3231 // scalar or vector data type argument..."
3232 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3233 // type (C99 6.2.5p18) or void.
3234 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3235 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3240 assert((T->isVoidType() || !T->isIncompleteType()) &&
3241 "Scalar types should always be complete");
3245 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3247 SourceRange ArgRange,
3248 UnaryExprOrTypeTrait TraitKind) {
3249 // Invalid types must be hard errors for SFINAE in C++.
3250 if (S.LangOpts.CPlusPlus)
3254 if (T->isFunctionType() &&
3255 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3256 // sizeof(function)/alignof(function) is allowed as an extension.
3257 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3258 << TraitKind << ArgRange;
3262 // Allow sizeof(void)/alignof(void) as an extension.
3263 if (T->isVoidType()) {
3264 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3271 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3273 SourceRange ArgRange,
3274 UnaryExprOrTypeTrait TraitKind) {
3275 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3276 // runtime doesn't allow it.
3277 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3278 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3279 << T << (TraitKind == UETT_SizeOf)
3287 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3288 /// pointer type is equal to T) and emit a warning if it is.
3289 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3291 // Don't warn if the operation changed the type.
3292 if (T != E->getType())
3295 // Now look for array decays.
3296 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3297 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3300 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3302 << ICE->getSubExpr()->getType();
3305 /// \brief Check the constrains on expression operands to unary type expression
3306 /// and type traits.
3308 /// Completes any types necessary and validates the constraints on the operand
3309 /// expression. The logic mostly mirrors the type-based overload, but may modify
3310 /// the expression as it completes the type for that expression through template
3311 /// instantiation, etc.
3312 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3313 UnaryExprOrTypeTrait ExprKind) {
3314 QualType ExprTy = E->getType();
3315 assert(!ExprTy->isReferenceType());
3317 if (ExprKind == UETT_VecStep)
3318 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3319 E->getSourceRange());
3321 // Whitelist some types as extensions
3322 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3323 E->getSourceRange(), ExprKind))
3326 if (RequireCompleteExprType(E,
3327 diag::err_sizeof_alignof_incomplete_type,
3328 ExprKind, E->getSourceRange()))
3331 // Completing the expression's type may have changed it.
3332 ExprTy = E->getType();
3333 assert(!ExprTy->isReferenceType());
3335 if (ExprTy->isFunctionType()) {
3336 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3337 << ExprKind << E->getSourceRange();
3341 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3342 E->getSourceRange(), ExprKind))
3345 if (ExprKind == UETT_SizeOf) {
3346 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3347 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3348 QualType OType = PVD->getOriginalType();
3349 QualType Type = PVD->getType();
3350 if (Type->isPointerType() && OType->isArrayType()) {
3351 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3353 Diag(PVD->getLocation(), diag::note_declared_at);
3358 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3359 // decays into a pointer and returns an unintended result. This is most
3360 // likely a typo for "sizeof(array) op x".
3361 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3362 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3364 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3372 /// \brief Check the constraints on operands to unary expression and type
3375 /// This will complete any types necessary, and validate the various constraints
3376 /// on those operands.
3378 /// The UsualUnaryConversions() function is *not* called by this routine.
3379 /// C99 6.3.2.1p[2-4] all state:
3380 /// Except when it is the operand of the sizeof operator ...
3382 /// C++ [expr.sizeof]p4
3383 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3384 /// standard conversions are not applied to the operand of sizeof.
3386 /// This policy is followed for all of the unary trait expressions.
3387 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3388 SourceLocation OpLoc,
3389 SourceRange ExprRange,
3390 UnaryExprOrTypeTrait ExprKind) {
3391 if (ExprType->isDependentType())
3394 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3395 // the result is the size of the referenced type."
3396 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3397 // result shall be the alignment of the referenced type."
3398 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3399 ExprType = Ref->getPointeeType();
3401 if (ExprKind == UETT_VecStep)
3402 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3404 // Whitelist some types as extensions
3405 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3409 if (RequireCompleteType(OpLoc, ExprType,
3410 diag::err_sizeof_alignof_incomplete_type,
3411 ExprKind, ExprRange))
3414 if (ExprType->isFunctionType()) {
3415 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3416 << ExprKind << ExprRange;
3420 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3427 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3428 E = E->IgnoreParens();
3430 // Cannot know anything else if the expression is dependent.
3431 if (E->isTypeDependent())
3434 if (E->getObjectKind() == OK_BitField) {
3435 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3436 << 1 << E->getSourceRange();
3441 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3443 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3444 D = ME->getMemberDecl();
3447 // If it's a field, require the containing struct to have a
3448 // complete definition so that we can compute the layout.
3450 // This requires a very particular set of circumstances. For a
3451 // field to be contained within an incomplete type, we must in the
3452 // process of parsing that type. To have an expression refer to a
3453 // field, it must be an id-expression or a member-expression, but
3454 // the latter are always ill-formed when the base type is
3455 // incomplete, including only being partially complete. An
3456 // id-expression can never refer to a field in C because fields
3457 // are not in the ordinary namespace. In C++, an id-expression
3458 // can implicitly be a member access, but only if there's an
3459 // implicit 'this' value, and all such contexts are subject to
3460 // delayed parsing --- except for trailing return types in C++11.
3461 // And if an id-expression referring to a field occurs in a
3462 // context that lacks a 'this' value, it's ill-formed --- except,
3463 // agian, in C++11, where such references are allowed in an
3464 // unevaluated context. So C++11 introduces some new complexity.
3466 // For the record, since __alignof__ on expressions is a GCC
3467 // extension, GCC seems to permit this but always gives the
3468 // nonsensical answer 0.
3470 // We don't really need the layout here --- we could instead just
3471 // directly check for all the appropriate alignment-lowing
3472 // attributes --- but that would require duplicating a lot of
3473 // logic that just isn't worth duplicating for such a marginal
3475 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3476 // Fast path this check, since we at least know the record has a
3477 // definition if we can find a member of it.
3478 if (!FD->getParent()->isCompleteDefinition()) {
3479 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3480 << E->getSourceRange();
3484 // Otherwise, if it's a field, and the field doesn't have
3485 // reference type, then it must have a complete type (or be a
3486 // flexible array member, which we explicitly want to
3487 // white-list anyway), which makes the following checks trivial.
3488 if (!FD->getType()->isReferenceType())
3492 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3495 bool Sema::CheckVecStepExpr(Expr *E) {
3496 E = E->IgnoreParens();
3498 // Cannot know anything else if the expression is dependent.
3499 if (E->isTypeDependent())
3502 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3505 /// \brief Build a sizeof or alignof expression given a type operand.
3507 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3508 SourceLocation OpLoc,
3509 UnaryExprOrTypeTrait ExprKind,
3514 QualType T = TInfo->getType();
3516 if (!T->isDependentType() &&
3517 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3520 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3521 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3522 Context.getSizeType(),
3523 OpLoc, R.getEnd()));
3526 /// \brief Build a sizeof or alignof expression given an expression
3529 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3530 UnaryExprOrTypeTrait ExprKind) {
3531 ExprResult PE = CheckPlaceholderExpr(E);
3537 // Verify that the operand is valid.
3538 bool isInvalid = false;
3539 if (E->isTypeDependent()) {
3540 // Delay type-checking for type-dependent expressions.
3541 } else if (ExprKind == UETT_AlignOf) {
3542 isInvalid = CheckAlignOfExpr(*this, E);
3543 } else if (ExprKind == UETT_VecStep) {
3544 isInvalid = CheckVecStepExpr(E);
3545 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
3546 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3549 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3555 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3556 PE = TransformToPotentiallyEvaluated(E);
3557 if (PE.isInvalid()) return ExprError();
3561 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3562 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3563 ExprKind, E, Context.getSizeType(), OpLoc,
3564 E->getSourceRange().getEnd()));
3567 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3568 /// expr and the same for @c alignof and @c __alignof
3569 /// Note that the ArgRange is invalid if isType is false.
3571 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3572 UnaryExprOrTypeTrait ExprKind, bool IsType,
3573 void *TyOrEx, const SourceRange &ArgRange) {
3574 // If error parsing type, ignore.
3575 if (TyOrEx == 0) return ExprError();
3578 TypeSourceInfo *TInfo;
3579 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3580 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3583 Expr *ArgEx = (Expr *)TyOrEx;
3584 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3588 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3590 if (V.get()->isTypeDependent())
3591 return S.Context.DependentTy;
3593 // _Real and _Imag are only l-values for normal l-values.
3594 if (V.get()->getObjectKind() != OK_Ordinary) {
3595 V = S.DefaultLvalueConversion(V.take());
3600 // These operators return the element type of a complex type.
3601 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3602 return CT->getElementType();
3604 // Otherwise they pass through real integer and floating point types here.
3605 if (V.get()->getType()->isArithmeticType())
3606 return V.get()->getType();
3608 // Test for placeholders.
3609 ExprResult PR = S.CheckPlaceholderExpr(V.get());
3610 if (PR.isInvalid()) return QualType();
3611 if (PR.get() != V.get()) {
3613 return CheckRealImagOperand(S, V, Loc, IsReal);
3616 // Reject anything else.
3617 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3618 << (IsReal ? "__real" : "__imag");
3625 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3626 tok::TokenKind Kind, Expr *Input) {
3627 UnaryOperatorKind Opc;
3629 default: llvm_unreachable("Unknown unary op!");
3630 case tok::plusplus: Opc = UO_PostInc; break;
3631 case tok::minusminus: Opc = UO_PostDec; break;
3634 // Since this might is a postfix expression, get rid of ParenListExprs.
3635 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3636 if (Result.isInvalid()) return ExprError();
3637 Input = Result.take();
3639 return BuildUnaryOp(S, OpLoc, Opc, Input);
3642 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3644 /// \return true on error
3645 static bool checkArithmeticOnObjCPointer(Sema &S,
3646 SourceLocation opLoc,
3648 assert(op->getType()->isObjCObjectPointerType());
3649 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3650 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3653 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3654 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3655 << op->getSourceRange();
3660 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3661 Expr *idx, SourceLocation rbLoc) {
3662 // Since this might be a postfix expression, get rid of ParenListExprs.
3663 if (isa<ParenListExpr>(base)) {
3664 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3665 if (result.isInvalid()) return ExprError();
3666 base = result.take();
3669 // Handle any non-overload placeholder types in the base and index
3670 // expressions. We can't handle overloads here because the other
3671 // operand might be an overloadable type, in which case the overload
3672 // resolution for the operator overload should get the first crack
3674 if (base->getType()->isNonOverloadPlaceholderType()) {
3675 ExprResult result = CheckPlaceholderExpr(base);
3676 if (result.isInvalid()) return ExprError();
3677 base = result.take();
3679 if (idx->getType()->isNonOverloadPlaceholderType()) {
3680 ExprResult result = CheckPlaceholderExpr(idx);
3681 if (result.isInvalid()) return ExprError();
3682 idx = result.take();
3685 // Build an unanalyzed expression if either operand is type-dependent.
3686 if (getLangOpts().CPlusPlus &&
3687 (base->isTypeDependent() || idx->isTypeDependent())) {
3688 return Owned(new (Context) ArraySubscriptExpr(base, idx,
3689 Context.DependentTy,
3690 VK_LValue, OK_Ordinary,
3694 // Use C++ overloaded-operator rules if either operand has record
3695 // type. The spec says to do this if either type is *overloadable*,
3696 // but enum types can't declare subscript operators or conversion
3697 // operators, so there's nothing interesting for overload resolution
3698 // to do if there aren't any record types involved.
3700 // ObjC pointers have their own subscripting logic that is not tied
3701 // to overload resolution and so should not take this path.
3702 if (getLangOpts().CPlusPlus &&
3703 (base->getType()->isRecordType() ||
3704 (!base->getType()->isObjCObjectPointerType() &&
3705 idx->getType()->isRecordType()))) {
3706 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3709 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3713 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3714 Expr *Idx, SourceLocation RLoc) {
3715 Expr *LHSExp = Base;
3718 // Perform default conversions.
3719 if (!LHSExp->getType()->getAs<VectorType>()) {
3720 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3721 if (Result.isInvalid())
3723 LHSExp = Result.take();
3725 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3726 if (Result.isInvalid())
3728 RHSExp = Result.take();
3730 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3731 ExprValueKind VK = VK_LValue;
3732 ExprObjectKind OK = OK_Ordinary;
3734 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3735 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3736 // in the subscript position. As a result, we need to derive the array base
3737 // and index from the expression types.
3738 Expr *BaseExpr, *IndexExpr;
3739 QualType ResultType;
3740 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3743 ResultType = Context.DependentTy;
3744 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3747 ResultType = PTy->getPointeeType();
3748 } else if (const ObjCObjectPointerType *PTy =
3749 LHSTy->getAs<ObjCObjectPointerType>()) {
3753 // Use custom logic if this should be the pseudo-object subscript
3755 if (!LangOpts.isSubscriptPointerArithmetic())
3756 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3758 ResultType = PTy->getPointeeType();
3759 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3760 // Handle the uncommon case of "123[Ptr]".
3763 ResultType = PTy->getPointeeType();
3764 } else if (const ObjCObjectPointerType *PTy =
3765 RHSTy->getAs<ObjCObjectPointerType>()) {
3766 // Handle the uncommon case of "123[Ptr]".
3769 ResultType = PTy->getPointeeType();
3770 if (!LangOpts.isSubscriptPointerArithmetic()) {
3771 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3772 << ResultType << BaseExpr->getSourceRange();
3775 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3776 BaseExpr = LHSExp; // vectors: V[123]
3778 VK = LHSExp->getValueKind();
3779 if (VK != VK_RValue)
3780 OK = OK_VectorComponent;
3782 // FIXME: need to deal with const...
3783 ResultType = VTy->getElementType();
3784 } else if (LHSTy->isArrayType()) {
3785 // If we see an array that wasn't promoted by
3786 // DefaultFunctionArrayLvalueConversion, it must be an array that
3787 // wasn't promoted because of the C90 rule that doesn't
3788 // allow promoting non-lvalue arrays. Warn, then
3789 // force the promotion here.
3790 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3791 LHSExp->getSourceRange();
3792 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3793 CK_ArrayToPointerDecay).take();
3794 LHSTy = LHSExp->getType();
3798 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3799 } else if (RHSTy->isArrayType()) {
3800 // Same as previous, except for 123[f().a] case
3801 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3802 RHSExp->getSourceRange();
3803 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3804 CK_ArrayToPointerDecay).take();
3805 RHSTy = RHSExp->getType();
3809 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3811 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3812 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3815 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3816 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3817 << IndexExpr->getSourceRange());
3819 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3820 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3821 && !IndexExpr->isTypeDependent())
3822 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3824 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3825 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3826 // type. Note that Functions are not objects, and that (in C99 parlance)
3827 // incomplete types are not object types.
3828 if (ResultType->isFunctionType()) {
3829 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3830 << ResultType << BaseExpr->getSourceRange();
3834 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3835 // GNU extension: subscripting on pointer to void
3836 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3837 << BaseExpr->getSourceRange();
3839 // C forbids expressions of unqualified void type from being l-values.
3840 // See IsCForbiddenLValueType.
3841 if (!ResultType.hasQualifiers()) VK = VK_RValue;
3842 } else if (!ResultType->isDependentType() &&
3843 RequireCompleteType(LLoc, ResultType,
3844 diag::err_subscript_incomplete_type, BaseExpr))
3847 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3848 !ResultType.isCForbiddenLValueType());
3850 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3851 ResultType, VK, OK, RLoc));
3854 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3856 ParmVarDecl *Param) {
3857 if (Param->hasUnparsedDefaultArg()) {
3859 diag::err_use_of_default_argument_to_function_declared_later) <<
3860 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3861 Diag(UnparsedDefaultArgLocs[Param],
3862 diag::note_default_argument_declared_here);
3866 if (Param->hasUninstantiatedDefaultArg()) {
3867 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3869 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3872 // Instantiate the expression.
3873 MultiLevelTemplateArgumentList MutiLevelArgList
3874 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3876 InstantiatingTemplate Inst(*this, CallLoc, Param,
3877 MutiLevelArgList.getInnermost());
3878 if (Inst.isInvalid())
3883 // C++ [dcl.fct.default]p5:
3884 // The names in the [default argument] expression are bound, and
3885 // the semantic constraints are checked, at the point where the
3886 // default argument expression appears.
3887 ContextRAII SavedContext(*this, FD);
3888 LocalInstantiationScope Local(*this);
3889 Result = SubstExpr(UninstExpr, MutiLevelArgList);
3891 if (Result.isInvalid())
3894 // Check the expression as an initializer for the parameter.
3895 InitializedEntity Entity
3896 = InitializedEntity::InitializeParameter(Context, Param);
3897 InitializationKind Kind
3898 = InitializationKind::CreateCopy(Param->getLocation(),
3899 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3900 Expr *ResultE = Result.takeAs<Expr>();
3902 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3903 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3904 if (Result.isInvalid())
3907 Expr *Arg = Result.takeAs<Expr>();
3908 CheckCompletedExpr(Arg, Param->getOuterLocStart());
3909 // Build the default argument expression.
3910 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3913 // If the default expression creates temporaries, we need to
3914 // push them to the current stack of expression temporaries so they'll
3915 // be properly destroyed.
3916 // FIXME: We should really be rebuilding the default argument with new
3917 // bound temporaries; see the comment in PR5810.
3918 // We don't need to do that with block decls, though, because
3919 // blocks in default argument expression can never capture anything.
3920 if (isa<ExprWithCleanups>(Param->getInit())) {
3921 // Set the "needs cleanups" bit regardless of whether there are
3922 // any explicit objects.
3923 ExprNeedsCleanups = true;
3925 // Append all the objects to the cleanup list. Right now, this
3926 // should always be a no-op, because blocks in default argument
3927 // expressions should never be able to capture anything.
3928 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3929 "default argument expression has capturing blocks?");
3932 // We already type-checked the argument, so we know it works.
3933 // Just mark all of the declarations in this potentially-evaluated expression
3934 // as being "referenced".
3935 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3936 /*SkipLocalVariables=*/true);
3937 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3941 Sema::VariadicCallType
3942 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3944 if (Proto && Proto->isVariadic()) {
3945 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3946 return VariadicConstructor;
3947 else if (Fn && Fn->getType()->isBlockPointerType())
3948 return VariadicBlock;
3950 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3951 if (Method->isInstance())
3952 return VariadicMethod;
3953 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3954 return VariadicMethod;
3955 return VariadicFunction;
3957 return VariadicDoesNotApply;
3961 class FunctionCallCCC : public FunctionCallFilterCCC {
3963 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3964 unsigned NumArgs, bool HasExplicitTemplateArgs)
3965 : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs),
3966 FunctionName(FuncName) {}
3968 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
3969 if (!candidate.getCorrectionSpecifier() ||
3970 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3974 return FunctionCallFilterCCC::ValidateCandidate(candidate);
3978 const IdentifierInfo *const FunctionName;
3982 static TypoCorrection TryTypoCorrectionForCall(Sema &S,
3983 DeclarationNameInfo FuncName,
3984 ArrayRef<Expr *> Args) {
3985 FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(),
3986 Args.size(), false);
3987 if (TypoCorrection Corrected =
3988 S.CorrectTypo(FuncName, Sema::LookupOrdinaryName,
3989 S.getScopeForContext(S.CurContext), NULL, CCC)) {
3990 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
3991 if (Corrected.isOverloaded()) {
3992 OverloadCandidateSet OCS(FuncName.getLoc());
3993 OverloadCandidateSet::iterator Best;
3994 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
3995 CDEnd = Corrected.end();
3996 CD != CDEnd; ++CD) {
3997 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
3998 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4001 switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) {
4003 ND = Best->Function;
4004 Corrected.setCorrectionDecl(ND);
4010 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4015 return TypoCorrection();
4018 /// ConvertArgumentsForCall - Converts the arguments specified in
4019 /// Args/NumArgs to the parameter types of the function FDecl with
4020 /// function prototype Proto. Call is the call expression itself, and
4021 /// Fn is the function expression. For a C++ member function, this
4022 /// routine does not attempt to convert the object argument. Returns
4023 /// true if the call is ill-formed.
4025 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4026 FunctionDecl *FDecl,
4027 const FunctionProtoType *Proto,
4028 ArrayRef<Expr *> Args,
4029 SourceLocation RParenLoc,
4030 bool IsExecConfig) {
4031 // Bail out early if calling a builtin with custom typechecking.
4032 // We don't need to do this in the
4034 if (unsigned ID = FDecl->getBuiltinID())
4035 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4038 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4039 // assignment, to the types of the corresponding parameter, ...
4040 unsigned NumArgsInProto = Proto->getNumArgs();
4041 bool Invalid = false;
4042 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
4043 unsigned FnKind = Fn->getType()->isBlockPointerType()
4045 : (IsExecConfig ? 3 /* kernel function (exec config) */
4046 : 0 /* function */);
4048 // If too few arguments are available (and we don't have default
4049 // arguments for the remaining parameters), don't make the call.
4050 if (Args.size() < NumArgsInProto) {
4051 if (Args.size() < MinArgs) {
4052 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4054 if (FDecl && (TC = TryTypoCorrectionForCall(
4055 *this, DeclarationNameInfo(FDecl->getDeclName(),
4056 (ME ? ME->getMemberLoc()
4057 : Fn->getLocStart())),
4060 MinArgs == NumArgsInProto && !Proto->isVariadic()
4061 ? diag::err_typecheck_call_too_few_args_suggest
4062 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4063 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4064 << static_cast<unsigned>(Args.size())
4065 << Fn->getSourceRange());
4066 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4067 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
4068 ? diag::err_typecheck_call_too_few_args_one
4069 : diag::err_typecheck_call_too_few_args_at_least_one)
4071 << FDecl->getParamDecl(0) << Fn->getSourceRange();
4073 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
4074 ? diag::err_typecheck_call_too_few_args
4075 : diag::err_typecheck_call_too_few_args_at_least)
4077 << MinArgs << static_cast<unsigned>(Args.size())
4078 << Fn->getSourceRange();
4080 // Emit the location of the prototype.
4081 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4082 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4087 Call->setNumArgs(Context, NumArgsInProto);
4090 // If too many are passed and not variadic, error on the extras and drop
4092 if (Args.size() > NumArgsInProto) {
4093 if (!Proto->isVariadic()) {
4095 if (FDecl && (TC = TryTypoCorrectionForCall(
4096 *this, DeclarationNameInfo(FDecl->getDeclName(),
4100 MinArgs == NumArgsInProto && !Proto->isVariadic()
4101 ? diag::err_typecheck_call_too_many_args_suggest
4102 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4103 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumArgsInProto
4104 << static_cast<unsigned>(Args.size())
4105 << Fn->getSourceRange());
4106 } else if (NumArgsInProto == 1 && FDecl &&
4107 FDecl->getParamDecl(0)->getDeclName())
4108 Diag(Args[NumArgsInProto]->getLocStart(),
4109 MinArgs == NumArgsInProto
4110 ? diag::err_typecheck_call_too_many_args_one
4111 : diag::err_typecheck_call_too_many_args_at_most_one)
4113 << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size())
4114 << Fn->getSourceRange()
4115 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4116 Args.back()->getLocEnd());
4118 Diag(Args[NumArgsInProto]->getLocStart(),
4119 MinArgs == NumArgsInProto
4120 ? diag::err_typecheck_call_too_many_args
4121 : diag::err_typecheck_call_too_many_args_at_most)
4123 << NumArgsInProto << static_cast<unsigned>(Args.size())
4124 << Fn->getSourceRange()
4125 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4126 Args.back()->getLocEnd());
4128 // Emit the location of the prototype.
4129 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4130 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4133 // This deletes the extra arguments.
4134 Call->setNumArgs(Context, NumArgsInProto);
4138 SmallVector<Expr *, 8> AllArgs;
4139 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4141 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4142 Proto, 0, Args, AllArgs, CallType);
4145 unsigned TotalNumArgs = AllArgs.size();
4146 for (unsigned i = 0; i < TotalNumArgs; ++i)
4147 Call->setArg(i, AllArgs[i]);
4152 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4153 FunctionDecl *FDecl,
4154 const FunctionProtoType *Proto,
4155 unsigned FirstProtoArg,
4156 ArrayRef<Expr *> Args,
4157 SmallVectorImpl<Expr *> &AllArgs,
4158 VariadicCallType CallType,
4160 bool IsListInitialization) {
4161 unsigned NumArgsInProto = Proto->getNumArgs();
4162 unsigned NumArgsToCheck = Args.size();
4163 bool Invalid = false;
4164 if (Args.size() != NumArgsInProto)
4165 // Use default arguments for missing arguments
4166 NumArgsToCheck = NumArgsInProto;
4168 // Continue to check argument types (even if we have too few/many args).
4169 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4170 QualType ProtoArgType = Proto->getArgType(i);
4174 if (ArgIx < Args.size()) {
4175 Arg = Args[ArgIx++];
4177 if (RequireCompleteType(Arg->getLocStart(),
4179 diag::err_call_incomplete_argument, Arg))
4182 // Pass the argument
4184 if (FDecl && i < FDecl->getNumParams())
4185 Param = FDecl->getParamDecl(i);
4187 // Strip the unbridged-cast placeholder expression off, if applicable.
4188 bool CFAudited = false;
4189 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4190 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4191 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4192 Arg = stripARCUnbridgedCast(Arg);
4193 else if (getLangOpts().ObjCAutoRefCount &&
4194 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4195 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4198 InitializedEntity Entity = Param ?
4199 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
4200 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4201 Proto->isArgConsumed(i));
4203 // Remember that parameter belongs to a CF audited API.
4205 Entity.setParameterCFAudited();
4207 ExprResult ArgE = PerformCopyInitialization(Entity,
4210 IsListInitialization,
4212 if (ArgE.isInvalid())
4215 Arg = ArgE.takeAs<Expr>();
4217 assert(FDecl && "can't use default arguments without a known callee");
4218 Param = FDecl->getParamDecl(i);
4220 ExprResult ArgExpr =
4221 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4222 if (ArgExpr.isInvalid())
4225 Arg = ArgExpr.takeAs<Expr>();
4228 // Check for array bounds violations for each argument to the call. This
4229 // check only triggers warnings when the argument isn't a more complex Expr
4230 // with its own checking, such as a BinaryOperator.
4231 CheckArrayAccess(Arg);
4233 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4234 CheckStaticArrayArgument(CallLoc, Param, Arg);
4236 AllArgs.push_back(Arg);
4239 // If this is a variadic call, handle args passed through "...".
4240 if (CallType != VariadicDoesNotApply) {
4241 // Assume that extern "C" functions with variadic arguments that
4242 // return __unknown_anytype aren't *really* variadic.
4243 if (Proto->getResultType() == Context.UnknownAnyTy &&
4244 FDecl && FDecl->isExternC()) {
4245 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4246 QualType paramType; // ignored
4247 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4248 Invalid |= arg.isInvalid();
4249 AllArgs.push_back(arg.take());
4252 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4254 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4255 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4257 Invalid |= Arg.isInvalid();
4258 AllArgs.push_back(Arg.take());
4262 // Check for array bounds violations.
4263 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4264 CheckArrayAccess(Args[i]);
4269 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4270 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4271 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4272 TL = DTL.getOriginalLoc();
4273 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4274 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4275 << ATL.getLocalSourceRange();
4278 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4279 /// array parameter, check that it is non-null, and that if it is formed by
4280 /// array-to-pointer decay, the underlying array is sufficiently large.
4282 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4283 /// array type derivation, then for each call to the function, the value of the
4284 /// corresponding actual argument shall provide access to the first element of
4285 /// an array with at least as many elements as specified by the size expression.
4287 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4289 const Expr *ArgExpr) {
4290 // Static array parameters are not supported in C++.
4291 if (!Param || getLangOpts().CPlusPlus)
4294 QualType OrigTy = Param->getOriginalType();
4296 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4297 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4300 if (ArgExpr->isNullPointerConstant(Context,
4301 Expr::NPC_NeverValueDependent)) {
4302 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4303 DiagnoseCalleeStaticArrayParam(*this, Param);
4307 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4311 const ConstantArrayType *ArgCAT =
4312 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4316 if (ArgCAT->getSize().ult(CAT->getSize())) {
4317 Diag(CallLoc, diag::warn_static_array_too_small)
4318 << ArgExpr->getSourceRange()
4319 << (unsigned) ArgCAT->getSize().getZExtValue()
4320 << (unsigned) CAT->getSize().getZExtValue();
4321 DiagnoseCalleeStaticArrayParam(*this, Param);
4325 /// Given a function expression of unknown-any type, try to rebuild it
4326 /// to have a function type.
4327 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4329 /// Is the given type a placeholder that we need to lower out
4330 /// immediately during argument processing?
4331 static bool isPlaceholderToRemoveAsArg(QualType type) {
4332 // Placeholders are never sugared.
4333 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4334 if (!placeholder) return false;
4336 switch (placeholder->getKind()) {
4337 // Ignore all the non-placeholder types.
4338 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4339 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4340 #include "clang/AST/BuiltinTypes.def"
4343 // We cannot lower out overload sets; they might validly be resolved
4344 // by the call machinery.
4345 case BuiltinType::Overload:
4348 // Unbridged casts in ARC can be handled in some call positions and
4349 // should be left in place.
4350 case BuiltinType::ARCUnbridgedCast:
4353 // Pseudo-objects should be converted as soon as possible.
4354 case BuiltinType::PseudoObject:
4357 // The debugger mode could theoretically but currently does not try
4358 // to resolve unknown-typed arguments based on known parameter types.
4359 case BuiltinType::UnknownAny:
4362 // These are always invalid as call arguments and should be reported.
4363 case BuiltinType::BoundMember:
4364 case BuiltinType::BuiltinFn:
4367 llvm_unreachable("bad builtin type kind");
4370 /// Check an argument list for placeholders that we won't try to
4372 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4373 // Apply this processing to all the arguments at once instead of
4374 // dying at the first failure.
4375 bool hasInvalid = false;
4376 for (size_t i = 0, e = args.size(); i != e; i++) {
4377 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4378 ExprResult result = S.CheckPlaceholderExpr(args[i]);
4379 if (result.isInvalid()) hasInvalid = true;
4380 else args[i] = result.take();
4386 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4387 /// This provides the location of the left/right parens and a list of comma
4390 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4391 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4392 Expr *ExecConfig, bool IsExecConfig) {
4393 // Since this might be a postfix expression, get rid of ParenListExprs.
4394 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4395 if (Result.isInvalid()) return ExprError();
4398 if (checkArgsForPlaceholders(*this, ArgExprs))
4401 if (getLangOpts().CPlusPlus) {
4402 // If this is a pseudo-destructor expression, build the call immediately.
4403 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4404 if (!ArgExprs.empty()) {
4405 // Pseudo-destructor calls should not have any arguments.
4406 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4407 << FixItHint::CreateRemoval(
4408 SourceRange(ArgExprs[0]->getLocStart(),
4409 ArgExprs.back()->getLocEnd()));
4412 return Owned(new (Context) CallExpr(Context, Fn, None,
4413 Context.VoidTy, VK_RValue,
4416 if (Fn->getType() == Context.PseudoObjectTy) {
4417 ExprResult result = CheckPlaceholderExpr(Fn);
4418 if (result.isInvalid()) return ExprError();
4422 // Determine whether this is a dependent call inside a C++ template,
4423 // in which case we won't do any semantic analysis now.
4424 // FIXME: Will need to cache the results of name lookup (including ADL) in
4426 bool Dependent = false;
4427 if (Fn->isTypeDependent())
4429 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4434 return Owned(new (Context) CUDAKernelCallExpr(
4435 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4436 Context.DependentTy, VK_RValue, RParenLoc));
4438 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4439 Context.DependentTy, VK_RValue,
4444 // Determine whether this is a call to an object (C++ [over.call.object]).
4445 if (Fn->getType()->isRecordType())
4446 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4447 ArgExprs, RParenLoc));
4449 if (Fn->getType() == Context.UnknownAnyTy) {
4450 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4451 if (result.isInvalid()) return ExprError();
4455 if (Fn->getType() == Context.BoundMemberTy) {
4456 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4460 // Check for overloaded calls. This can happen even in C due to extensions.
4461 if (Fn->getType() == Context.OverloadTy) {
4462 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4464 // We aren't supposed to apply this logic for if there's an '&' involved.
4465 if (!find.HasFormOfMemberPointer) {
4466 OverloadExpr *ovl = find.Expression;
4467 if (isa<UnresolvedLookupExpr>(ovl)) {
4468 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4469 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4470 RParenLoc, ExecConfig);
4472 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4478 // If we're directly calling a function, get the appropriate declaration.
4479 if (Fn->getType() == Context.UnknownAnyTy) {
4480 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4481 if (result.isInvalid()) return ExprError();
4485 Expr *NakedFn = Fn->IgnoreParens();
4487 NamedDecl *NDecl = 0;
4488 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4489 if (UnOp->getOpcode() == UO_AddrOf)
4490 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4492 if (isa<DeclRefExpr>(NakedFn))
4493 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4494 else if (isa<MemberExpr>(NakedFn))
4495 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4497 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4498 ExecConfig, IsExecConfig);
4502 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4503 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4504 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4506 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4507 << "cudaConfigureCall");
4508 QualType ConfigQTy = ConfigDecl->getType();
4510 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4511 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4512 MarkFunctionReferenced(LLLLoc, ConfigDecl);
4514 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4515 /*IsExecConfig=*/true);
4518 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4520 /// __builtin_astype( value, dst type )
4522 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4523 SourceLocation BuiltinLoc,
4524 SourceLocation RParenLoc) {
4525 ExprValueKind VK = VK_RValue;
4526 ExprObjectKind OK = OK_Ordinary;
4527 QualType DstTy = GetTypeFromParser(ParsedDestTy);
4528 QualType SrcTy = E->getType();
4529 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4530 return ExprError(Diag(BuiltinLoc,
4531 diag::err_invalid_astype_of_different_size)
4534 << E->getSourceRange());
4535 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4539 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4540 /// provided arguments.
4542 /// __builtin_convertvector( value, dst type )
4544 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4545 SourceLocation BuiltinLoc,
4546 SourceLocation RParenLoc) {
4547 TypeSourceInfo *TInfo;
4548 GetTypeFromParser(ParsedDestTy, &TInfo);
4549 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4552 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4553 /// i.e. an expression not of \p OverloadTy. The expression should
4554 /// unary-convert to an expression of function-pointer or
4555 /// block-pointer type.
4557 /// \param NDecl the declaration being called, if available
4559 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4560 SourceLocation LParenLoc,
4561 ArrayRef<Expr *> Args,
4562 SourceLocation RParenLoc,
4563 Expr *Config, bool IsExecConfig) {
4564 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4565 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4567 // Promote the function operand.
4568 // We special-case function promotion here because we only allow promoting
4569 // builtin functions to function pointers in the callee of a call.
4572 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4573 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4574 CK_BuiltinFnToFnPtr).take();
4576 Result = UsualUnaryConversions(Fn);
4578 if (Result.isInvalid())
4582 // Make the call expr early, before semantic checks. This guarantees cleanup
4583 // of arguments and function on error.
4586 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4587 cast<CallExpr>(Config), Args,
4588 Context.BoolTy, VK_RValue,
4591 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4592 VK_RValue, RParenLoc);
4594 // Bail out early if calling a builtin with custom typechecking.
4595 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4596 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4599 const FunctionType *FuncT;
4600 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4601 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4602 // have type pointer to function".
4603 FuncT = PT->getPointeeType()->getAs<FunctionType>();
4605 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4606 << Fn->getType() << Fn->getSourceRange());
4607 } else if (const BlockPointerType *BPT =
4608 Fn->getType()->getAs<BlockPointerType>()) {
4609 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4611 // Handle calls to expressions of unknown-any type.
4612 if (Fn->getType() == Context.UnknownAnyTy) {
4613 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4614 if (rewrite.isInvalid()) return ExprError();
4615 Fn = rewrite.take();
4616 TheCall->setCallee(Fn);
4620 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4621 << Fn->getType() << Fn->getSourceRange());
4624 if (getLangOpts().CUDA) {
4626 // CUDA: Kernel calls must be to global functions
4627 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4628 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4629 << FDecl->getName() << Fn->getSourceRange());
4631 // CUDA: Kernel function must have 'void' return type
4632 if (!FuncT->getResultType()->isVoidType())
4633 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4634 << Fn->getType() << Fn->getSourceRange());
4636 // CUDA: Calls to global functions must be configured
4637 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4638 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4639 << FDecl->getName() << Fn->getSourceRange());
4643 // Check for a valid return type
4644 if (CheckCallReturnType(FuncT->getResultType(),
4645 Fn->getLocStart(), TheCall,
4649 // We know the result type of the call, set it.
4650 TheCall->setType(FuncT->getCallResultType(Context));
4651 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4653 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4655 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4659 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4662 // Check if we have too few/too many template arguments, based
4663 // on our knowledge of the function definition.
4664 const FunctionDecl *Def = 0;
4665 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4666 Proto = Def->getType()->getAs<FunctionProtoType>();
4667 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4668 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4669 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4672 // If the function we're calling isn't a function prototype, but we have
4673 // a function prototype from a prior declaratiom, use that prototype.
4674 if (!FDecl->hasPrototype())
4675 Proto = FDecl->getType()->getAs<FunctionProtoType>();
4678 // Promote the arguments (C99 6.5.2.2p6).
4679 for (unsigned i = 0, e = Args.size(); i != e; i++) {
4680 Expr *Arg = Args[i];
4682 if (Proto && i < Proto->getNumArgs()) {
4683 InitializedEntity Entity
4684 = InitializedEntity::InitializeParameter(Context,
4685 Proto->getArgType(i),
4686 Proto->isArgConsumed(i));
4687 ExprResult ArgE = PerformCopyInitialization(Entity,
4690 if (ArgE.isInvalid())
4693 Arg = ArgE.takeAs<Expr>();
4696 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4698 if (ArgE.isInvalid())
4701 Arg = ArgE.takeAs<Expr>();
4704 if (RequireCompleteType(Arg->getLocStart(),
4706 diag::err_call_incomplete_argument, Arg))
4709 TheCall->setArg(i, Arg);
4713 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4714 if (!Method->isStatic())
4715 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4716 << Fn->getSourceRange());
4718 // Check for sentinels
4720 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4722 // Do special checking on direct calls to functions.
4724 if (CheckFunctionCall(FDecl, TheCall, Proto))
4728 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4730 if (CheckPointerCall(NDecl, TheCall, Proto))
4733 if (CheckOtherCall(TheCall, Proto))
4737 return MaybeBindToTemporary(TheCall);
4741 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4742 SourceLocation RParenLoc, Expr *InitExpr) {
4743 assert(Ty && "ActOnCompoundLiteral(): missing type");
4744 // FIXME: put back this assert when initializers are worked out.
4745 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4747 TypeSourceInfo *TInfo;
4748 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4750 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4752 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4756 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4757 SourceLocation RParenLoc, Expr *LiteralExpr) {
4758 QualType literalType = TInfo->getType();
4760 if (literalType->isArrayType()) {
4761 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4762 diag::err_illegal_decl_array_incomplete_type,
4763 SourceRange(LParenLoc,
4764 LiteralExpr->getSourceRange().getEnd())))
4766 if (literalType->isVariableArrayType())
4767 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4768 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4769 } else if (!literalType->isDependentType() &&
4770 RequireCompleteType(LParenLoc, literalType,
4771 diag::err_typecheck_decl_incomplete_type,
4772 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4775 InitializedEntity Entity
4776 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4777 InitializationKind Kind
4778 = InitializationKind::CreateCStyleCast(LParenLoc,
4779 SourceRange(LParenLoc, RParenLoc),
4781 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4782 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4784 if (Result.isInvalid())
4786 LiteralExpr = Result.get();
4788 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4790 !LiteralExpr->isTypeDependent() &&
4791 !LiteralExpr->isValueDependent() &&
4792 !literalType->isDependentType()) { // 6.5.2.5p3
4793 if (CheckForConstantInitializer(LiteralExpr, literalType))
4797 // In C, compound literals are l-values for some reason.
4798 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4800 return MaybeBindToTemporary(
4801 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4802 VK, LiteralExpr, isFileScope));
4806 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4807 SourceLocation RBraceLoc) {
4808 // Immediately handle non-overload placeholders. Overloads can be
4809 // resolved contextually, but everything else here can't.
4810 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4811 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4812 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4814 // Ignore failures; dropping the entire initializer list because
4815 // of one failure would be terrible for indexing/etc.
4816 if (result.isInvalid()) continue;
4818 InitArgList[I] = result.take();
4822 // Semantic analysis for initializers is done by ActOnDeclarator() and
4823 // CheckInitializer() - it requires knowledge of the object being intialized.
4825 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4827 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4831 /// Do an explicit extend of the given block pointer if we're in ARC.
4832 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4833 assert(E.get()->getType()->isBlockPointerType());
4834 assert(E.get()->isRValue());
4836 // Only do this in an r-value context.
4837 if (!S.getLangOpts().ObjCAutoRefCount) return;
4839 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4840 CK_ARCExtendBlockObject, E.get(),
4841 /*base path*/ 0, VK_RValue);
4842 S.ExprNeedsCleanups = true;
4845 /// Prepare a conversion of the given expression to an ObjC object
4847 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4848 QualType type = E.get()->getType();
4849 if (type->isObjCObjectPointerType()) {
4851 } else if (type->isBlockPointerType()) {
4852 maybeExtendBlockObject(*this, E);
4853 return CK_BlockPointerToObjCPointerCast;
4855 assert(type->isPointerType());
4856 return CK_CPointerToObjCPointerCast;
4860 /// Prepares for a scalar cast, performing all the necessary stages
4861 /// except the final cast and returning the kind required.
4862 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4863 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4864 // Also, callers should have filtered out the invalid cases with
4865 // pointers. Everything else should be possible.
4867 QualType SrcTy = Src.get()->getType();
4868 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4871 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4872 case Type::STK_MemberPointer:
4873 llvm_unreachable("member pointer type in C");
4875 case Type::STK_CPointer:
4876 case Type::STK_BlockPointer:
4877 case Type::STK_ObjCObjectPointer:
4878 switch (DestTy->getScalarTypeKind()) {
4879 case Type::STK_CPointer:
4881 case Type::STK_BlockPointer:
4882 return (SrcKind == Type::STK_BlockPointer
4883 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4884 case Type::STK_ObjCObjectPointer:
4885 if (SrcKind == Type::STK_ObjCObjectPointer)
4887 if (SrcKind == Type::STK_CPointer)
4888 return CK_CPointerToObjCPointerCast;
4889 maybeExtendBlockObject(*this, Src);
4890 return CK_BlockPointerToObjCPointerCast;
4891 case Type::STK_Bool:
4892 return CK_PointerToBoolean;
4893 case Type::STK_Integral:
4894 return CK_PointerToIntegral;
4895 case Type::STK_Floating:
4896 case Type::STK_FloatingComplex:
4897 case Type::STK_IntegralComplex:
4898 case Type::STK_MemberPointer:
4899 llvm_unreachable("illegal cast from pointer");
4901 llvm_unreachable("Should have returned before this");
4903 case Type::STK_Bool: // casting from bool is like casting from an integer
4904 case Type::STK_Integral:
4905 switch (DestTy->getScalarTypeKind()) {
4906 case Type::STK_CPointer:
4907 case Type::STK_ObjCObjectPointer:
4908 case Type::STK_BlockPointer:
4909 if (Src.get()->isNullPointerConstant(Context,
4910 Expr::NPC_ValueDependentIsNull))
4911 return CK_NullToPointer;
4912 return CK_IntegralToPointer;
4913 case Type::STK_Bool:
4914 return CK_IntegralToBoolean;
4915 case Type::STK_Integral:
4916 return CK_IntegralCast;
4917 case Type::STK_Floating:
4918 return CK_IntegralToFloating;
4919 case Type::STK_IntegralComplex:
4920 Src = ImpCastExprToType(Src.take(),
4921 DestTy->castAs<ComplexType>()->getElementType(),
4923 return CK_IntegralRealToComplex;
4924 case Type::STK_FloatingComplex:
4925 Src = ImpCastExprToType(Src.take(),
4926 DestTy->castAs<ComplexType>()->getElementType(),
4927 CK_IntegralToFloating);
4928 return CK_FloatingRealToComplex;
4929 case Type::STK_MemberPointer:
4930 llvm_unreachable("member pointer type in C");
4932 llvm_unreachable("Should have returned before this");
4934 case Type::STK_Floating:
4935 switch (DestTy->getScalarTypeKind()) {
4936 case Type::STK_Floating:
4937 return CK_FloatingCast;
4938 case Type::STK_Bool:
4939 return CK_FloatingToBoolean;
4940 case Type::STK_Integral:
4941 return CK_FloatingToIntegral;
4942 case Type::STK_FloatingComplex:
4943 Src = ImpCastExprToType(Src.take(),
4944 DestTy->castAs<ComplexType>()->getElementType(),
4946 return CK_FloatingRealToComplex;
4947 case Type::STK_IntegralComplex:
4948 Src = ImpCastExprToType(Src.take(),
4949 DestTy->castAs<ComplexType>()->getElementType(),
4950 CK_FloatingToIntegral);
4951 return CK_IntegralRealToComplex;
4952 case Type::STK_CPointer:
4953 case Type::STK_ObjCObjectPointer:
4954 case Type::STK_BlockPointer:
4955 llvm_unreachable("valid float->pointer cast?");
4956 case Type::STK_MemberPointer:
4957 llvm_unreachable("member pointer type in C");
4959 llvm_unreachable("Should have returned before this");
4961 case Type::STK_FloatingComplex:
4962 switch (DestTy->getScalarTypeKind()) {
4963 case Type::STK_FloatingComplex:
4964 return CK_FloatingComplexCast;
4965 case Type::STK_IntegralComplex:
4966 return CK_FloatingComplexToIntegralComplex;
4967 case Type::STK_Floating: {
4968 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4969 if (Context.hasSameType(ET, DestTy))
4970 return CK_FloatingComplexToReal;
4971 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4972 return CK_FloatingCast;
4974 case Type::STK_Bool:
4975 return CK_FloatingComplexToBoolean;
4976 case Type::STK_Integral:
4977 Src = ImpCastExprToType(Src.take(),
4978 SrcTy->castAs<ComplexType>()->getElementType(),
4979 CK_FloatingComplexToReal);
4980 return CK_FloatingToIntegral;
4981 case Type::STK_CPointer:
4982 case Type::STK_ObjCObjectPointer:
4983 case Type::STK_BlockPointer:
4984 llvm_unreachable("valid complex float->pointer cast?");
4985 case Type::STK_MemberPointer:
4986 llvm_unreachable("member pointer type in C");
4988 llvm_unreachable("Should have returned before this");
4990 case Type::STK_IntegralComplex:
4991 switch (DestTy->getScalarTypeKind()) {
4992 case Type::STK_FloatingComplex:
4993 return CK_IntegralComplexToFloatingComplex;
4994 case Type::STK_IntegralComplex:
4995 return CK_IntegralComplexCast;
4996 case Type::STK_Integral: {
4997 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4998 if (Context.hasSameType(ET, DestTy))
4999 return CK_IntegralComplexToReal;
5000 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
5001 return CK_IntegralCast;
5003 case Type::STK_Bool:
5004 return CK_IntegralComplexToBoolean;
5005 case Type::STK_Floating:
5006 Src = ImpCastExprToType(Src.take(),
5007 SrcTy->castAs<ComplexType>()->getElementType(),
5008 CK_IntegralComplexToReal);
5009 return CK_IntegralToFloating;
5010 case Type::STK_CPointer:
5011 case Type::STK_ObjCObjectPointer:
5012 case Type::STK_BlockPointer:
5013 llvm_unreachable("valid complex int->pointer cast?");
5014 case Type::STK_MemberPointer:
5015 llvm_unreachable("member pointer type in C");
5017 llvm_unreachable("Should have returned before this");
5020 llvm_unreachable("Unhandled scalar cast");
5023 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5025 assert(VectorTy->isVectorType() && "Not a vector type!");
5027 if (Ty->isVectorType() || Ty->isIntegerType()) {
5028 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
5029 return Diag(R.getBegin(),
5030 Ty->isVectorType() ?
5031 diag::err_invalid_conversion_between_vectors :
5032 diag::err_invalid_conversion_between_vector_and_integer)
5033 << VectorTy << Ty << R;
5035 return Diag(R.getBegin(),
5036 diag::err_invalid_conversion_between_vector_and_scalar)
5037 << VectorTy << Ty << R;
5043 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5044 Expr *CastExpr, CastKind &Kind) {
5045 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5047 QualType SrcTy = CastExpr->getType();
5049 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5050 // an ExtVectorType.
5051 // In OpenCL, casts between vectors of different types are not allowed.
5052 // (See OpenCL 6.2).
5053 if (SrcTy->isVectorType()) {
5054 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
5055 || (getLangOpts().OpenCL &&
5056 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5057 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5058 << DestTy << SrcTy << R;
5062 return Owned(CastExpr);
5065 // All non-pointer scalars can be cast to ExtVector type. The appropriate
5066 // conversion will take place first from scalar to elt type, and then
5067 // splat from elt type to vector.
5068 if (SrcTy->isPointerType())
5069 return Diag(R.getBegin(),
5070 diag::err_invalid_conversion_between_vector_and_scalar)
5071 << DestTy << SrcTy << R;
5073 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5074 ExprResult CastExprRes = Owned(CastExpr);
5075 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5076 if (CastExprRes.isInvalid())
5078 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
5080 Kind = CK_VectorSplat;
5081 return Owned(CastExpr);
5085 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5086 Declarator &D, ParsedType &Ty,
5087 SourceLocation RParenLoc, Expr *CastExpr) {
5088 assert(!D.isInvalidType() && (CastExpr != 0) &&
5089 "ActOnCastExpr(): missing type or expr");
5091 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5092 if (D.isInvalidType())
5095 if (getLangOpts().CPlusPlus) {
5096 // Check that there are no default arguments (C++ only).
5097 CheckExtraCXXDefaultArguments(D);
5100 checkUnusedDeclAttributes(D);
5102 QualType castType = castTInfo->getType();
5103 Ty = CreateParsedType(castType, castTInfo);
5105 bool isVectorLiteral = false;
5107 // Check for an altivec or OpenCL literal,
5108 // i.e. all the elements are integer constants.
5109 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5110 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5111 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5112 && castType->isVectorType() && (PE || PLE)) {
5113 if (PLE && PLE->getNumExprs() == 0) {
5114 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5117 if (PE || PLE->getNumExprs() == 1) {
5118 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5119 if (!E->getType()->isVectorType())
5120 isVectorLiteral = true;
5123 isVectorLiteral = true;
5126 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5127 // then handle it as such.
5128 if (isVectorLiteral)
5129 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5131 // If the Expr being casted is a ParenListExpr, handle it specially.
5132 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5133 // sequence of BinOp comma operators.
5134 if (isa<ParenListExpr>(CastExpr)) {
5135 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5136 if (Result.isInvalid()) return ExprError();
5137 CastExpr = Result.take();
5140 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5143 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5144 SourceLocation RParenLoc, Expr *E,
5145 TypeSourceInfo *TInfo) {
5146 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5147 "Expected paren or paren list expression");
5152 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5153 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5154 LiteralLParenLoc = PE->getLParenLoc();
5155 LiteralRParenLoc = PE->getRParenLoc();
5156 exprs = PE->getExprs();
5157 numExprs = PE->getNumExprs();
5158 } else { // isa<ParenExpr> by assertion at function entrance
5159 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5160 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5161 subExpr = cast<ParenExpr>(E)->getSubExpr();
5166 QualType Ty = TInfo->getType();
5167 assert(Ty->isVectorType() && "Expected vector type");
5169 SmallVector<Expr *, 8> initExprs;
5170 const VectorType *VTy = Ty->getAs<VectorType>();
5171 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5173 // '(...)' form of vector initialization in AltiVec: the number of
5174 // initializers must be one or must match the size of the vector.
5175 // If a single value is specified in the initializer then it will be
5176 // replicated to all the components of the vector
5177 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5178 // The number of initializers must be one or must match the size of the
5179 // vector. If a single value is specified in the initializer then it will
5180 // be replicated to all the components of the vector
5181 if (numExprs == 1) {
5182 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5183 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5184 if (Literal.isInvalid())
5186 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5187 PrepareScalarCast(Literal, ElemTy));
5188 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5190 else if (numExprs < numElems) {
5191 Diag(E->getExprLoc(),
5192 diag::err_incorrect_number_of_vector_initializers);
5196 initExprs.append(exprs, exprs + numExprs);
5199 // For OpenCL, when the number of initializers is a single value,
5200 // it will be replicated to all components of the vector.
5201 if (getLangOpts().OpenCL &&
5202 VTy->getVectorKind() == VectorType::GenericVector &&
5204 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5205 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5206 if (Literal.isInvalid())
5208 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5209 PrepareScalarCast(Literal, ElemTy));
5210 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5213 initExprs.append(exprs, exprs + numExprs);
5215 // FIXME: This means that pretty-printing the final AST will produce curly
5216 // braces instead of the original commas.
5217 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5218 initExprs, LiteralRParenLoc);
5220 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5223 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5224 /// the ParenListExpr into a sequence of comma binary operators.
5226 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5227 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5229 return Owned(OrigExpr);
5231 ExprResult Result(E->getExpr(0));
5233 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5234 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5237 if (Result.isInvalid()) return ExprError();
5239 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5242 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5245 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5249 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5250 /// constant and the other is not a pointer. Returns true if a diagnostic is
5252 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5253 SourceLocation QuestionLoc) {
5254 Expr *NullExpr = LHSExpr;
5255 Expr *NonPointerExpr = RHSExpr;
5256 Expr::NullPointerConstantKind NullKind =
5257 NullExpr->isNullPointerConstant(Context,
5258 Expr::NPC_ValueDependentIsNotNull);
5260 if (NullKind == Expr::NPCK_NotNull) {
5262 NonPointerExpr = LHSExpr;
5264 NullExpr->isNullPointerConstant(Context,
5265 Expr::NPC_ValueDependentIsNotNull);
5268 if (NullKind == Expr::NPCK_NotNull)
5271 if (NullKind == Expr::NPCK_ZeroExpression)
5274 if (NullKind == Expr::NPCK_ZeroLiteral) {
5275 // In this case, check to make sure that we got here from a "NULL"
5276 // string in the source code.
5277 NullExpr = NullExpr->IgnoreParenImpCasts();
5278 SourceLocation loc = NullExpr->getExprLoc();
5279 if (!findMacroSpelling(loc, "NULL"))
5283 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5284 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5285 << NonPointerExpr->getType() << DiagType
5286 << NonPointerExpr->getSourceRange();
5290 /// \brief Return false if the condition expression is valid, true otherwise.
5291 static bool checkCondition(Sema &S, Expr *Cond) {
5292 QualType CondTy = Cond->getType();
5295 if (CondTy->isScalarType()) return false;
5297 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5298 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5301 // Emit the proper error message.
5302 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5303 diag::err_typecheck_cond_expect_scalar :
5304 diag::err_typecheck_cond_expect_scalar_or_vector)
5309 /// \brief Return false if the two expressions can be converted to a vector,
5311 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5314 // Both operands should be of scalar type.
5315 if (!LHS.get()->getType()->isScalarType()) {
5316 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5320 if (!RHS.get()->getType()->isScalarType()) {
5321 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5326 // Implicity convert these scalars to the type of the condition.
5327 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5328 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5332 /// \brief Handle when one or both operands are void type.
5333 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5335 Expr *LHSExpr = LHS.get();
5336 Expr *RHSExpr = RHS.get();
5338 if (!LHSExpr->getType()->isVoidType())
5339 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5340 << RHSExpr->getSourceRange();
5341 if (!RHSExpr->getType()->isVoidType())
5342 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5343 << LHSExpr->getSourceRange();
5344 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5345 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5346 return S.Context.VoidTy;
5349 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5351 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5352 QualType PointerTy) {
5353 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5354 !NullExpr.get()->isNullPointerConstant(S.Context,
5355 Expr::NPC_ValueDependentIsNull))
5358 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5362 /// \brief Checks compatibility between two pointers and return the resulting
5364 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5366 SourceLocation Loc) {
5367 QualType LHSTy = LHS.get()->getType();
5368 QualType RHSTy = RHS.get()->getType();
5370 if (S.Context.hasSameType(LHSTy, RHSTy)) {
5371 // Two identical pointers types are always compatible.
5375 QualType lhptee, rhptee;
5377 // Get the pointee types.
5378 bool IsBlockPointer = false;
5379 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5380 lhptee = LHSBTy->getPointeeType();
5381 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5382 IsBlockPointer = true;
5384 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5385 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5388 // C99 6.5.15p6: If both operands are pointers to compatible types or to
5389 // differently qualified versions of compatible types, the result type is
5390 // a pointer to an appropriately qualified version of the composite
5393 // Only CVR-qualifiers exist in the standard, and the differently-qualified
5394 // clause doesn't make sense for our extensions. E.g. address space 2 should
5395 // be incompatible with address space 3: they may live on different devices or
5397 Qualifiers lhQual = lhptee.getQualifiers();
5398 Qualifiers rhQual = rhptee.getQualifiers();
5400 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5401 lhQual.removeCVRQualifiers();
5402 rhQual.removeCVRQualifiers();
5404 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5405 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5407 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5409 if (CompositeTy.isNull()) {
5410 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5411 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5412 << RHS.get()->getSourceRange();
5413 // In this situation, we assume void* type. No especially good
5414 // reason, but this is what gcc does, and we do have to pick
5415 // to get a consistent AST.
5416 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5417 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5418 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5422 // The pointer types are compatible.
5423 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5425 ResultTy = S.Context.getBlockPointerType(ResultTy);
5427 ResultTy = S.Context.getPointerType(ResultTy);
5429 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5430 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5434 /// \brief Return the resulting type when the operands are both block pointers.
5435 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5438 SourceLocation Loc) {
5439 QualType LHSTy = LHS.get()->getType();
5440 QualType RHSTy = RHS.get()->getType();
5442 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5443 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5444 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5445 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5446 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5449 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5450 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5451 << RHS.get()->getSourceRange();
5455 // We have 2 block pointer types.
5456 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5459 /// \brief Return the resulting type when the operands are both pointers.
5461 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5463 SourceLocation Loc) {
5464 // get the pointer types
5465 QualType LHSTy = LHS.get()->getType();
5466 QualType RHSTy = RHS.get()->getType();
5468 // get the "pointed to" types
5469 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5470 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5472 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5473 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5474 // Figure out necessary qualifiers (C99 6.5.15p6)
5475 QualType destPointee
5476 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5477 QualType destType = S.Context.getPointerType(destPointee);
5478 // Add qualifiers if necessary.
5479 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5480 // Promote to void*.
5481 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5484 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5485 QualType destPointee
5486 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5487 QualType destType = S.Context.getPointerType(destPointee);
5488 // Add qualifiers if necessary.
5489 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5490 // Promote to void*.
5491 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5495 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5498 /// \brief Return false if the first expression is not an integer and the second
5499 /// expression is not a pointer, true otherwise.
5500 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5501 Expr* PointerExpr, SourceLocation Loc,
5502 bool IsIntFirstExpr) {
5503 if (!PointerExpr->getType()->isPointerType() ||
5504 !Int.get()->getType()->isIntegerType())
5507 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5508 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5510 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5511 << Expr1->getType() << Expr2->getType()
5512 << Expr1->getSourceRange() << Expr2->getSourceRange();
5513 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5514 CK_IntegralToPointer);
5518 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5519 /// In that case, LHS = cond.
5521 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5522 ExprResult &RHS, ExprValueKind &VK,
5524 SourceLocation QuestionLoc) {
5526 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5527 if (!LHSResult.isUsable()) return QualType();
5530 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5531 if (!RHSResult.isUsable()) return QualType();
5534 // C++ is sufficiently different to merit its own checker.
5535 if (getLangOpts().CPlusPlus)
5536 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5541 // First, check the condition.
5542 Cond = UsualUnaryConversions(Cond.take());
5543 if (Cond.isInvalid())
5545 if (checkCondition(*this, Cond.get()))
5548 // Now check the two expressions.
5549 if (LHS.get()->getType()->isVectorType() ||
5550 RHS.get()->getType()->isVectorType())
5551 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5553 UsualArithmeticConversions(LHS, RHS);
5554 if (LHS.isInvalid() || RHS.isInvalid())
5557 QualType CondTy = Cond.get()->getType();
5558 QualType LHSTy = LHS.get()->getType();
5559 QualType RHSTy = RHS.get()->getType();
5561 // If the condition is a vector, and both operands are scalar,
5562 // attempt to implicity convert them to the vector type to act like the
5563 // built in select. (OpenCL v1.1 s6.3.i)
5564 if (getLangOpts().OpenCL && CondTy->isVectorType())
5565 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5568 // If both operands have arithmetic type, do the usual arithmetic conversions
5569 // to find a common type: C99 6.5.15p3,5.
5570 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5571 return LHS.get()->getType();
5573 // If both operands are the same structure or union type, the result is that
5575 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5576 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5577 if (LHSRT->getDecl() == RHSRT->getDecl())
5578 // "If both the operands have structure or union type, the result has
5579 // that type." This implies that CV qualifiers are dropped.
5580 return LHSTy.getUnqualifiedType();
5581 // FIXME: Type of conditional expression must be complete in C mode.
5584 // C99 6.5.15p5: "If both operands have void type, the result has void type."
5585 // The following || allows only one side to be void (a GCC-ism).
5586 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5587 return checkConditionalVoidType(*this, LHS, RHS);
5590 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5591 // the type of the other operand."
5592 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5593 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5595 // All objective-c pointer type analysis is done here.
5596 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5598 if (LHS.isInvalid() || RHS.isInvalid())
5600 if (!compositeType.isNull())
5601 return compositeType;
5604 // Handle block pointer types.
5605 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5606 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5609 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5610 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5611 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5614 // GCC compatibility: soften pointer/integer mismatch. Note that
5615 // null pointers have been filtered out by this point.
5616 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5617 /*isIntFirstExpr=*/true))
5619 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5620 /*isIntFirstExpr=*/false))
5623 // Emit a better diagnostic if one of the expressions is a null pointer
5624 // constant and the other is not a pointer type. In this case, the user most
5625 // likely forgot to take the address of the other expression.
5626 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5629 // Otherwise, the operands are not compatible.
5630 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5631 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5632 << RHS.get()->getSourceRange();
5636 /// FindCompositeObjCPointerType - Helper method to find composite type of
5637 /// two objective-c pointer types of the two input expressions.
5638 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5639 SourceLocation QuestionLoc) {
5640 QualType LHSTy = LHS.get()->getType();
5641 QualType RHSTy = RHS.get()->getType();
5643 // Handle things like Class and struct objc_class*. Here we case the result
5644 // to the pseudo-builtin, because that will be implicitly cast back to the
5645 // redefinition type if an attempt is made to access its fields.
5646 if (LHSTy->isObjCClassType() &&
5647 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5648 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5651 if (RHSTy->isObjCClassType() &&
5652 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5653 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5656 // And the same for struct objc_object* / id
5657 if (LHSTy->isObjCIdType() &&
5658 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5659 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5662 if (RHSTy->isObjCIdType() &&
5663 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5664 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5667 // And the same for struct objc_selector* / SEL
5668 if (Context.isObjCSelType(LHSTy) &&
5669 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5670 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5673 if (Context.isObjCSelType(RHSTy) &&
5674 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5675 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5678 // Check constraints for Objective-C object pointers types.
5679 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5681 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5682 // Two identical object pointer types are always compatible.
5685 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5686 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5687 QualType compositeType = LHSTy;
5689 // If both operands are interfaces and either operand can be
5690 // assigned to the other, use that type as the composite
5691 // type. This allows
5692 // xxx ? (A*) a : (B*) b
5693 // where B is a subclass of A.
5695 // Additionally, as for assignment, if either type is 'id'
5696 // allow silent coercion. Finally, if the types are
5697 // incompatible then make sure to use 'id' as the composite
5698 // type so the result is acceptable for sending messages to.
5700 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5701 // It could return the composite type.
5702 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5703 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5704 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5705 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5706 } else if ((LHSTy->isObjCQualifiedIdType() ||
5707 RHSTy->isObjCQualifiedIdType()) &&
5708 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5709 // Need to handle "id<xx>" explicitly.
5710 // GCC allows qualified id and any Objective-C type to devolve to
5711 // id. Currently localizing to here until clear this should be
5712 // part of ObjCQualifiedIdTypesAreCompatible.
5713 compositeType = Context.getObjCIdType();
5714 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5715 compositeType = Context.getObjCIdType();
5716 } else if (!(compositeType =
5717 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5720 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5722 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5723 QualType incompatTy = Context.getObjCIdType();
5724 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5725 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5728 // The object pointer types are compatible.
5729 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5730 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5731 return compositeType;
5733 // Check Objective-C object pointer types and 'void *'
5734 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5735 if (getLangOpts().ObjCAutoRefCount) {
5736 // ARC forbids the implicit conversion of object pointers to 'void *',
5737 // so these types are not compatible.
5738 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5743 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5744 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5745 QualType destPointee
5746 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5747 QualType destType = Context.getPointerType(destPointee);
5748 // Add qualifiers if necessary.
5749 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5750 // Promote to void*.
5751 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5754 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5755 if (getLangOpts().ObjCAutoRefCount) {
5756 // ARC forbids the implicit conversion of object pointers to 'void *',
5757 // so these types are not compatible.
5758 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5759 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5763 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5764 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5765 QualType destPointee
5766 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5767 QualType destType = Context.getPointerType(destPointee);
5768 // Add qualifiers if necessary.
5769 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5770 // Promote to void*.
5771 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5777 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5778 /// ParenRange in parentheses.
5779 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5780 const PartialDiagnostic &Note,
5781 SourceRange ParenRange) {
5782 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5783 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5785 Self.Diag(Loc, Note)
5786 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5787 << FixItHint::CreateInsertion(EndLoc, ")");
5789 // We can't display the parentheses, so just show the bare note.
5790 Self.Diag(Loc, Note) << ParenRange;
5794 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5795 return Opc >= BO_Mul && Opc <= BO_Shr;
5798 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5799 /// expression, either using a built-in or overloaded operator,
5800 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5802 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5804 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5805 E = E->IgnoreImpCasts();
5806 E = E->IgnoreConversionOperator();
5807 E = E->IgnoreImpCasts();
5809 // Built-in binary operator.
5810 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5811 if (IsArithmeticOp(OP->getOpcode())) {
5812 *Opcode = OP->getOpcode();
5813 *RHSExprs = OP->getRHS();
5818 // Overloaded operator.
5819 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5820 if (Call->getNumArgs() != 2)
5823 // Make sure this is really a binary operator that is safe to pass into
5824 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5825 OverloadedOperatorKind OO = Call->getOperator();
5826 if (OO < OO_Plus || OO > OO_Arrow ||
5827 OO == OO_PlusPlus || OO == OO_MinusMinus)
5830 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5831 if (IsArithmeticOp(OpKind)) {
5833 *RHSExprs = Call->getArg(1);
5841 static bool IsLogicOp(BinaryOperatorKind Opc) {
5842 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5845 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5846 /// or is a logical expression such as (x==y) which has int type, but is
5847 /// commonly interpreted as boolean.
5848 static bool ExprLooksBoolean(Expr *E) {
5849 E = E->IgnoreParenImpCasts();
5851 if (E->getType()->isBooleanType())
5853 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5854 return IsLogicOp(OP->getOpcode());
5855 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5856 return OP->getOpcode() == UO_LNot;
5861 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5862 /// and binary operator are mixed in a way that suggests the programmer assumed
5863 /// the conditional operator has higher precedence, for example:
5864 /// "int x = a + someBinaryCondition ? 1 : 2".
5865 static void DiagnoseConditionalPrecedence(Sema &Self,
5866 SourceLocation OpLoc,
5870 BinaryOperatorKind CondOpcode;
5873 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5875 if (!ExprLooksBoolean(CondRHS))
5878 // The condition is an arithmetic binary expression, with a right-
5879 // hand side that looks boolean, so warn.
5881 Self.Diag(OpLoc, diag::warn_precedence_conditional)
5882 << Condition->getSourceRange()
5883 << BinaryOperator::getOpcodeStr(CondOpcode);
5885 SuggestParentheses(Self, OpLoc,
5886 Self.PDiag(diag::note_precedence_silence)
5887 << BinaryOperator::getOpcodeStr(CondOpcode),
5888 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5890 SuggestParentheses(Self, OpLoc,
5891 Self.PDiag(diag::note_precedence_conditional_first),
5892 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5895 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5896 /// in the case of a the GNU conditional expr extension.
5897 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5898 SourceLocation ColonLoc,
5899 Expr *CondExpr, Expr *LHSExpr,
5901 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5902 // was the condition.
5903 OpaqueValueExpr *opaqueValue = 0;
5904 Expr *commonExpr = 0;
5906 commonExpr = CondExpr;
5907 // Lower out placeholder types first. This is important so that we don't
5908 // try to capture a placeholder. This happens in few cases in C++; such
5909 // as Objective-C++'s dictionary subscripting syntax.
5910 if (commonExpr->hasPlaceholderType()) {
5911 ExprResult result = CheckPlaceholderExpr(commonExpr);
5912 if (!result.isUsable()) return ExprError();
5913 commonExpr = result.take();
5915 // We usually want to apply unary conversions *before* saving, except
5916 // in the special case of a C++ l-value conditional.
5917 if (!(getLangOpts().CPlusPlus
5918 && !commonExpr->isTypeDependent()
5919 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5920 && commonExpr->isGLValue()
5921 && commonExpr->isOrdinaryOrBitFieldObject()
5922 && RHSExpr->isOrdinaryOrBitFieldObject()
5923 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5924 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5925 if (commonRes.isInvalid())
5927 commonExpr = commonRes.take();
5930 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5931 commonExpr->getType(),
5932 commonExpr->getValueKind(),
5933 commonExpr->getObjectKind(),
5935 LHSExpr = CondExpr = opaqueValue;
5938 ExprValueKind VK = VK_RValue;
5939 ExprObjectKind OK = OK_Ordinary;
5940 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5941 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5942 VK, OK, QuestionLoc);
5943 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5947 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5951 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5952 LHS.take(), ColonLoc,
5953 RHS.take(), result, VK, OK));
5955 return Owned(new (Context)
5956 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5957 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5961 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5962 // being closely modeled after the C99 spec:-). The odd characteristic of this
5963 // routine is it effectively iqnores the qualifiers on the top level pointee.
5964 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5965 // FIXME: add a couple examples in this comment.
5966 static Sema::AssignConvertType
5967 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5968 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5969 assert(RHSType.isCanonical() && "RHS not canonicalized!");
5971 // get the "pointed to" type (ignoring qualifiers at the top level)
5972 const Type *lhptee, *rhptee;
5973 Qualifiers lhq, rhq;
5974 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5975 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5977 Sema::AssignConvertType ConvTy = Sema::Compatible;
5979 // C99 6.5.16.1p1: This following citation is common to constraints
5980 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5981 // qualifiers of the type *pointed to* by the right;
5984 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5985 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5986 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5987 // Ignore lifetime for further calculation.
5988 lhq.removeObjCLifetime();
5989 rhq.removeObjCLifetime();
5992 if (!lhq.compatiblyIncludes(rhq)) {
5993 // Treat address-space mismatches as fatal. TODO: address subspaces
5994 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5995 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5997 // It's okay to add or remove GC or lifetime qualifiers when converting to
5999 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6000 .compatiblyIncludes(
6001 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6002 && (lhptee->isVoidType() || rhptee->isVoidType()))
6005 // Treat lifetime mismatches as fatal.
6006 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6007 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6009 // For GCC compatibility, other qualifier mismatches are treated
6010 // as still compatible in C.
6011 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6014 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6015 // incomplete type and the other is a pointer to a qualified or unqualified
6016 // version of void...
6017 if (lhptee->isVoidType()) {
6018 if (rhptee->isIncompleteOrObjectType())
6021 // As an extension, we allow cast to/from void* to function pointer.
6022 assert(rhptee->isFunctionType());
6023 return Sema::FunctionVoidPointer;
6026 if (rhptee->isVoidType()) {
6027 if (lhptee->isIncompleteOrObjectType())
6030 // As an extension, we allow cast to/from void* to function pointer.
6031 assert(lhptee->isFunctionType());
6032 return Sema::FunctionVoidPointer;
6035 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6036 // unqualified versions of compatible types, ...
6037 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6038 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6039 // Check if the pointee types are compatible ignoring the sign.
6040 // We explicitly check for char so that we catch "char" vs
6041 // "unsigned char" on systems where "char" is unsigned.
6042 if (lhptee->isCharType())
6043 ltrans = S.Context.UnsignedCharTy;
6044 else if (lhptee->hasSignedIntegerRepresentation())
6045 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6047 if (rhptee->isCharType())
6048 rtrans = S.Context.UnsignedCharTy;
6049 else if (rhptee->hasSignedIntegerRepresentation())
6050 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6052 if (ltrans == rtrans) {
6053 // Types are compatible ignoring the sign. Qualifier incompatibility
6054 // takes priority over sign incompatibility because the sign
6055 // warning can be disabled.
6056 if (ConvTy != Sema::Compatible)
6059 return Sema::IncompatiblePointerSign;
6062 // If we are a multi-level pointer, it's possible that our issue is simply
6063 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6064 // the eventual target type is the same and the pointers have the same
6065 // level of indirection, this must be the issue.
6066 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6068 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6069 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6070 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6072 if (lhptee == rhptee)
6073 return Sema::IncompatibleNestedPointerQualifiers;
6076 // General pointer incompatibility takes priority over qualifiers.
6077 return Sema::IncompatiblePointer;
6079 if (!S.getLangOpts().CPlusPlus &&
6080 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6081 return Sema::IncompatiblePointer;
6085 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6086 /// block pointer types are compatible or whether a block and normal pointer
6087 /// are compatible. It is more restrict than comparing two function pointer
6089 static Sema::AssignConvertType
6090 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6092 assert(LHSType.isCanonical() && "LHS not canonicalized!");
6093 assert(RHSType.isCanonical() && "RHS not canonicalized!");
6095 QualType lhptee, rhptee;
6097 // get the "pointed to" type (ignoring qualifiers at the top level)
6098 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6099 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6101 // In C++, the types have to match exactly.
6102 if (S.getLangOpts().CPlusPlus)
6103 return Sema::IncompatibleBlockPointer;
6105 Sema::AssignConvertType ConvTy = Sema::Compatible;
6107 // For blocks we enforce that qualifiers are identical.
6108 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6109 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6111 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6112 return Sema::IncompatibleBlockPointer;
6117 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6118 /// for assignment compatibility.
6119 static Sema::AssignConvertType
6120 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6122 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6123 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6125 if (LHSType->isObjCBuiltinType()) {
6126 // Class is not compatible with ObjC object pointers.
6127 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6128 !RHSType->isObjCQualifiedClassType())
6129 return Sema::IncompatiblePointer;
6130 return Sema::Compatible;
6132 if (RHSType->isObjCBuiltinType()) {
6133 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6134 !LHSType->isObjCQualifiedClassType())
6135 return Sema::IncompatiblePointer;
6136 return Sema::Compatible;
6138 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6139 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6141 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6142 // make an exception for id<P>
6143 !LHSType->isObjCQualifiedIdType())
6144 return Sema::CompatiblePointerDiscardsQualifiers;
6146 if (S.Context.typesAreCompatible(LHSType, RHSType))
6147 return Sema::Compatible;
6148 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6149 return Sema::IncompatibleObjCQualifiedId;
6150 return Sema::IncompatiblePointer;
6153 Sema::AssignConvertType
6154 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6155 QualType LHSType, QualType RHSType) {
6156 // Fake up an opaque expression. We don't actually care about what
6157 // cast operations are required, so if CheckAssignmentConstraints
6158 // adds casts to this they'll be wasted, but fortunately that doesn't
6159 // usually happen on valid code.
6160 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6161 ExprResult RHSPtr = &RHSExpr;
6162 CastKind K = CK_Invalid;
6164 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6167 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6168 /// has code to accommodate several GCC extensions when type checking
6169 /// pointers. Here are some objectionable examples that GCC considers warnings:
6173 /// struct foo *pfoo;
6175 /// pint = pshort; // warning: assignment from incompatible pointer type
6176 /// a = pint; // warning: assignment makes integer from pointer without a cast
6177 /// pint = a; // warning: assignment makes pointer from integer without a cast
6178 /// pint = pfoo; // warning: assignment from incompatible pointer type
6180 /// As a result, the code for dealing with pointers is more complex than the
6181 /// C99 spec dictates.
6183 /// Sets 'Kind' for any result kind except Incompatible.
6184 Sema::AssignConvertType
6185 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6187 QualType RHSType = RHS.get()->getType();
6188 QualType OrigLHSType = LHSType;
6190 // Get canonical types. We're not formatting these types, just comparing
6192 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6193 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6195 // Common case: no conversion required.
6196 if (LHSType == RHSType) {
6201 // If we have an atomic type, try a non-atomic assignment, then just add an
6202 // atomic qualification step.
6203 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6204 Sema::AssignConvertType result =
6205 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6206 if (result != Compatible)
6208 if (Kind != CK_NoOp)
6209 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6210 Kind = CK_NonAtomicToAtomic;
6214 // If the left-hand side is a reference type, then we are in a
6215 // (rare!) case where we've allowed the use of references in C,
6216 // e.g., as a parameter type in a built-in function. In this case,
6217 // just make sure that the type referenced is compatible with the
6218 // right-hand side type. The caller is responsible for adjusting
6219 // LHSType so that the resulting expression does not have reference
6221 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6222 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6223 Kind = CK_LValueBitCast;
6226 return Incompatible;
6229 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6230 // to the same ExtVector type.
6231 if (LHSType->isExtVectorType()) {
6232 if (RHSType->isExtVectorType())
6233 return Incompatible;
6234 if (RHSType->isArithmeticType()) {
6235 // CK_VectorSplat does T -> vector T, so first cast to the
6237 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6238 if (elType != RHSType) {
6239 Kind = PrepareScalarCast(RHS, elType);
6240 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
6242 Kind = CK_VectorSplat;
6247 // Conversions to or from vector type.
6248 if (LHSType->isVectorType() || RHSType->isVectorType()) {
6249 if (LHSType->isVectorType() && RHSType->isVectorType()) {
6250 // Allow assignments of an AltiVec vector type to an equivalent GCC
6251 // vector type and vice versa
6252 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6257 // If we are allowing lax vector conversions, and LHS and RHS are both
6258 // vectors, the total size only needs to be the same. This is a bitcast;
6259 // no bits are changed but the result type is different.
6260 if (getLangOpts().LaxVectorConversions &&
6261 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
6263 return IncompatibleVectors;
6266 return Incompatible;
6269 // Arithmetic conversions.
6270 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6271 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6272 Kind = PrepareScalarCast(RHS, LHSType);
6276 // Conversions to normal pointers.
6277 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6279 if (isa<PointerType>(RHSType)) {
6281 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6285 if (RHSType->isIntegerType()) {
6286 Kind = CK_IntegralToPointer; // FIXME: null?
6287 return IntToPointer;
6290 // C pointers are not compatible with ObjC object pointers,
6291 // with two exceptions:
6292 if (isa<ObjCObjectPointerType>(RHSType)) {
6293 // - conversions to void*
6294 if (LHSPointer->getPointeeType()->isVoidType()) {
6299 // - conversions from 'Class' to the redefinition type
6300 if (RHSType->isObjCClassType() &&
6301 Context.hasSameType(LHSType,
6302 Context.getObjCClassRedefinitionType())) {
6308 return IncompatiblePointer;
6312 if (RHSType->getAs<BlockPointerType>()) {
6313 if (LHSPointer->getPointeeType()->isVoidType()) {
6319 return Incompatible;
6322 // Conversions to block pointers.
6323 if (isa<BlockPointerType>(LHSType)) {
6325 if (RHSType->isBlockPointerType()) {
6327 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6330 // int or null -> T^
6331 if (RHSType->isIntegerType()) {
6332 Kind = CK_IntegralToPointer; // FIXME: null
6333 return IntToBlockPointer;
6337 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6338 Kind = CK_AnyPointerToBlockPointerCast;
6343 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6344 if (RHSPT->getPointeeType()->isVoidType()) {
6345 Kind = CK_AnyPointerToBlockPointerCast;
6349 return Incompatible;
6352 // Conversions to Objective-C pointers.
6353 if (isa<ObjCObjectPointerType>(LHSType)) {
6355 if (RHSType->isObjCObjectPointerType()) {
6357 Sema::AssignConvertType result =
6358 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6359 if (getLangOpts().ObjCAutoRefCount &&
6360 result == Compatible &&
6361 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6362 result = IncompatibleObjCWeakRef;
6366 // int or null -> A*
6367 if (RHSType->isIntegerType()) {
6368 Kind = CK_IntegralToPointer; // FIXME: null
6369 return IntToPointer;
6372 // In general, C pointers are not compatible with ObjC object pointers,
6373 // with two exceptions:
6374 if (isa<PointerType>(RHSType)) {
6375 Kind = CK_CPointerToObjCPointerCast;
6377 // - conversions from 'void*'
6378 if (RHSType->isVoidPointerType()) {
6382 // - conversions to 'Class' from its redefinition type
6383 if (LHSType->isObjCClassType() &&
6384 Context.hasSameType(RHSType,
6385 Context.getObjCClassRedefinitionType())) {
6389 return IncompatiblePointer;
6393 if (RHSType->isBlockPointerType()) {
6394 maybeExtendBlockObject(*this, RHS);
6395 Kind = CK_BlockPointerToObjCPointerCast;
6399 return Incompatible;
6402 // Conversions from pointers that are not covered by the above.
6403 if (isa<PointerType>(RHSType)) {
6405 if (LHSType == Context.BoolTy) {
6406 Kind = CK_PointerToBoolean;
6411 if (LHSType->isIntegerType()) {
6412 Kind = CK_PointerToIntegral;
6413 return PointerToInt;
6416 return Incompatible;
6419 // Conversions from Objective-C pointers that are not covered by the above.
6420 if (isa<ObjCObjectPointerType>(RHSType)) {
6422 if (LHSType == Context.BoolTy) {
6423 Kind = CK_PointerToBoolean;
6428 if (LHSType->isIntegerType()) {
6429 Kind = CK_PointerToIntegral;
6430 return PointerToInt;
6433 return Incompatible;
6436 // struct A -> struct B
6437 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6438 if (Context.typesAreCompatible(LHSType, RHSType)) {
6444 return Incompatible;
6447 /// \brief Constructs a transparent union from an expression that is
6448 /// used to initialize the transparent union.
6449 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6450 ExprResult &EResult, QualType UnionType,
6452 // Build an initializer list that designates the appropriate member
6453 // of the transparent union.
6454 Expr *E = EResult.take();
6455 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6456 E, SourceLocation());
6457 Initializer->setType(UnionType);
6458 Initializer->setInitializedFieldInUnion(Field);
6460 // Build a compound literal constructing a value of the transparent
6461 // union type from this initializer list.
6462 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6464 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6465 VK_RValue, Initializer, false));
6468 Sema::AssignConvertType
6469 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6471 QualType RHSType = RHS.get()->getType();
6473 // If the ArgType is a Union type, we want to handle a potential
6474 // transparent_union GCC extension.
6475 const RecordType *UT = ArgType->getAsUnionType();
6476 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6477 return Incompatible;
6479 // The field to initialize within the transparent union.
6480 RecordDecl *UD = UT->getDecl();
6481 FieldDecl *InitField = 0;
6482 // It's compatible if the expression matches any of the fields.
6483 for (RecordDecl::field_iterator it = UD->field_begin(),
6484 itend = UD->field_end();
6485 it != itend; ++it) {
6486 if (it->getType()->isPointerType()) {
6487 // If the transparent union contains a pointer type, we allow:
6489 // 2) null pointer constant
6490 if (RHSType->isPointerType())
6491 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6492 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6497 if (RHS.get()->isNullPointerConstant(Context,
6498 Expr::NPC_ValueDependentIsNull)) {
6499 RHS = ImpCastExprToType(RHS.take(), it->getType(),
6506 CastKind Kind = CK_Invalid;
6507 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6509 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6516 return Incompatible;
6518 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6522 Sema::AssignConvertType
6523 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6525 bool DiagnoseCFAudited) {
6526 if (getLangOpts().CPlusPlus) {
6527 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6528 // C++ 5.17p3: If the left operand is not of class type, the
6529 // expression is implicitly converted (C++ 4) to the
6530 // cv-unqualified type of the left operand.
6533 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6536 ImplicitConversionSequence ICS =
6537 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6538 /*SuppressUserConversions=*/false,
6539 /*AllowExplicit=*/false,
6540 /*InOverloadResolution=*/false,
6542 /*AllowObjCWritebackConversion=*/false);
6543 if (ICS.isFailure())
6544 return Incompatible;
6545 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6548 if (Res.isInvalid())
6549 return Incompatible;
6550 Sema::AssignConvertType result = Compatible;
6551 if (getLangOpts().ObjCAutoRefCount &&
6552 !CheckObjCARCUnavailableWeakConversion(LHSType,
6553 RHS.get()->getType()))
6554 result = IncompatibleObjCWeakRef;
6559 // FIXME: Currently, we fall through and treat C++ classes like C
6561 // FIXME: We also fall through for atomics; not sure what should
6562 // happen there, though.
6565 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6566 // a null pointer constant.
6567 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6568 LHSType->isBlockPointerType()) &&
6569 RHS.get()->isNullPointerConstant(Context,
6570 Expr::NPC_ValueDependentIsNull)) {
6573 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6574 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path);
6578 // This check seems unnatural, however it is necessary to ensure the proper
6579 // conversion of functions/arrays. If the conversion were done for all
6580 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6581 // expressions that suppress this implicit conversion (&, sizeof).
6583 // Suppress this for references: C++ 8.5.3p5.
6584 if (!LHSType->isReferenceType()) {
6585 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6586 if (RHS.isInvalid())
6587 return Incompatible;
6590 CastKind Kind = CK_Invalid;
6591 Sema::AssignConvertType result =
6592 CheckAssignmentConstraints(LHSType, RHS, Kind);
6594 // C99 6.5.16.1p2: The value of the right operand is converted to the
6595 // type of the assignment expression.
6596 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6597 // so that we can use references in built-in functions even in C.
6598 // The getNonReferenceType() call makes sure that the resulting expression
6599 // does not have reference type.
6600 if (result != Incompatible && RHS.get()->getType() != LHSType) {
6601 QualType Ty = LHSType.getNonLValueExprType(Context);
6602 Expr *E = RHS.take();
6603 if (getLangOpts().ObjCAutoRefCount)
6604 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6606 RHS = ImpCastExprToType(E, Ty, Kind);
6611 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6613 Diag(Loc, diag::err_typecheck_invalid_operands)
6614 << LHS.get()->getType() << RHS.get()->getType()
6615 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6619 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6620 SourceLocation Loc, bool IsCompAssign) {
6621 if (!IsCompAssign) {
6622 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6623 if (LHS.isInvalid())
6626 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6627 if (RHS.isInvalid())
6630 // For conversion purposes, we ignore any qualifiers.
6631 // For example, "const float" and "float" are equivalent.
6633 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6635 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6637 // If the vector types are identical, return.
6638 if (LHSType == RHSType)
6641 // Handle the case of equivalent AltiVec and GCC vector types
6642 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6643 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6644 if (LHSType->isExtVectorType()) {
6645 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6650 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6654 if (getLangOpts().LaxVectorConversions &&
6655 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6656 // If we are allowing lax vector conversions, and LHS and RHS are both
6657 // vectors, the total size only needs to be the same. This is a
6658 // bitcast; no bits are changed but the result type is different.
6659 // FIXME: Should we really be allowing this?
6660 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6664 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6665 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6666 bool swapped = false;
6667 if (RHSType->isExtVectorType() && !IsCompAssign) {
6669 std::swap(RHS, LHS);
6670 std::swap(RHSType, LHSType);
6673 // Handle the case of an ext vector and scalar.
6674 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6675 QualType EltTy = LV->getElementType();
6676 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6677 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6679 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6681 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6682 if (swapped) std::swap(RHS, LHS);
6686 if (EltTy->isRealFloatingType() && RHSType->isScalarType()) {
6687 if (RHSType->isRealFloatingType()) {
6688 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6690 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6692 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6693 if (swapped) std::swap(RHS, LHS);
6697 if (RHSType->isIntegralType(Context)) {
6698 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating);
6699 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6700 if (swapped) std::swap(RHS, LHS);
6706 // Vectors of different size or scalar and non-ext-vector are errors.
6707 if (swapped) std::swap(RHS, LHS);
6708 Diag(Loc, diag::err_typecheck_vector_not_convertable)
6709 << LHS.get()->getType() << RHS.get()->getType()
6710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6714 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6715 // expression. These are mainly cases where the null pointer is used as an
6716 // integer instead of a pointer.
6717 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6718 SourceLocation Loc, bool IsCompare) {
6719 // The canonical way to check for a GNU null is with isNullPointerConstant,
6720 // but we use a bit of a hack here for speed; this is a relatively
6721 // hot path, and isNullPointerConstant is slow.
6722 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6723 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6725 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6727 // Avoid analyzing cases where the result will either be invalid (and
6728 // diagnosed as such) or entirely valid and not something to warn about.
6729 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6730 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6733 // Comparison operations would not make sense with a null pointer no matter
6734 // what the other expression is.
6736 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6737 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6738 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6742 // The rest of the operations only make sense with a null pointer
6743 // if the other expression is a pointer.
6744 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6745 NonNullType->canDecayToPointerType())
6748 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6749 << LHSNull /* LHS is NULL */ << NonNullType
6750 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6753 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6755 bool IsCompAssign, bool IsDiv) {
6756 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6758 if (LHS.get()->getType()->isVectorType() ||
6759 RHS.get()->getType()->isVectorType())
6760 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6762 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6763 if (LHS.isInvalid() || RHS.isInvalid())
6767 if (compType.isNull() || !compType->isArithmeticType())
6768 return InvalidOperands(Loc, LHS, RHS);
6770 // Check for division by zero.
6771 llvm::APSInt RHSValue;
6772 if (IsDiv && !RHS.get()->isValueDependent() &&
6773 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6774 DiagRuntimeBehavior(Loc, RHS.get(),
6775 PDiag(diag::warn_division_by_zero)
6776 << RHS.get()->getSourceRange());
6781 QualType Sema::CheckRemainderOperands(
6782 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6783 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6785 if (LHS.get()->getType()->isVectorType() ||
6786 RHS.get()->getType()->isVectorType()) {
6787 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6788 RHS.get()->getType()->hasIntegerRepresentation())
6789 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6790 return InvalidOperands(Loc, LHS, RHS);
6793 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6794 if (LHS.isInvalid() || RHS.isInvalid())
6797 if (compType.isNull() || !compType->isIntegerType())
6798 return InvalidOperands(Loc, LHS, RHS);
6800 // Check for remainder by zero.
6801 llvm::APSInt RHSValue;
6802 if (!RHS.get()->isValueDependent() &&
6803 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6804 DiagRuntimeBehavior(Loc, RHS.get(),
6805 PDiag(diag::warn_remainder_by_zero)
6806 << RHS.get()->getSourceRange());
6811 /// \brief Diagnose invalid arithmetic on two void pointers.
6812 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6813 Expr *LHSExpr, Expr *RHSExpr) {
6814 S.Diag(Loc, S.getLangOpts().CPlusPlus
6815 ? diag::err_typecheck_pointer_arith_void_type
6816 : diag::ext_gnu_void_ptr)
6817 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6818 << RHSExpr->getSourceRange();
6821 /// \brief Diagnose invalid arithmetic on a void pointer.
6822 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6824 S.Diag(Loc, S.getLangOpts().CPlusPlus
6825 ? diag::err_typecheck_pointer_arith_void_type
6826 : diag::ext_gnu_void_ptr)
6827 << 0 /* one pointer */ << Pointer->getSourceRange();
6830 /// \brief Diagnose invalid arithmetic on two function pointers.
6831 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6832 Expr *LHS, Expr *RHS) {
6833 assert(LHS->getType()->isAnyPointerType());
6834 assert(RHS->getType()->isAnyPointerType());
6835 S.Diag(Loc, S.getLangOpts().CPlusPlus
6836 ? diag::err_typecheck_pointer_arith_function_type
6837 : diag::ext_gnu_ptr_func_arith)
6838 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6839 // We only show the second type if it differs from the first.
6840 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6842 << RHS->getType()->getPointeeType()
6843 << LHS->getSourceRange() << RHS->getSourceRange();
6846 /// \brief Diagnose invalid arithmetic on a function pointer.
6847 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6849 assert(Pointer->getType()->isAnyPointerType());
6850 S.Diag(Loc, S.getLangOpts().CPlusPlus
6851 ? diag::err_typecheck_pointer_arith_function_type
6852 : diag::ext_gnu_ptr_func_arith)
6853 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6854 << 0 /* one pointer, so only one type */
6855 << Pointer->getSourceRange();
6858 /// \brief Emit error if Operand is incomplete pointer type
6860 /// \returns True if pointer has incomplete type
6861 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6863 assert(Operand->getType()->isAnyPointerType() &&
6864 !Operand->getType()->isDependentType());
6865 QualType PointeeTy = Operand->getType()->getPointeeType();
6866 return S.RequireCompleteType(Loc, PointeeTy,
6867 diag::err_typecheck_arithmetic_incomplete_type,
6868 PointeeTy, Operand->getSourceRange());
6871 /// \brief Check the validity of an arithmetic pointer operand.
6873 /// If the operand has pointer type, this code will check for pointer types
6874 /// which are invalid in arithmetic operations. These will be diagnosed
6875 /// appropriately, including whether or not the use is supported as an
6878 /// \returns True when the operand is valid to use (even if as an extension).
6879 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6881 if (!Operand->getType()->isAnyPointerType()) return true;
6883 QualType PointeeTy = Operand->getType()->getPointeeType();
6884 if (PointeeTy->isVoidType()) {
6885 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6886 return !S.getLangOpts().CPlusPlus;
6888 if (PointeeTy->isFunctionType()) {
6889 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6890 return !S.getLangOpts().CPlusPlus;
6893 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6898 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6901 /// This routine will diagnose any invalid arithmetic on pointer operands much
6902 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6903 /// for emitting a single diagnostic even for operations where both LHS and RHS
6904 /// are (potentially problematic) pointers.
6906 /// \returns True when the operand is valid to use (even if as an extension).
6907 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6908 Expr *LHSExpr, Expr *RHSExpr) {
6909 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6910 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6911 if (!isLHSPointer && !isRHSPointer) return true;
6913 QualType LHSPointeeTy, RHSPointeeTy;
6914 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6915 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6917 // Check for arithmetic on pointers to incomplete types.
6918 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6919 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6920 if (isLHSVoidPtr || isRHSVoidPtr) {
6921 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6922 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6923 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6925 return !S.getLangOpts().CPlusPlus;
6928 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6929 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6930 if (isLHSFuncPtr || isRHSFuncPtr) {
6931 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6932 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6934 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6936 return !S.getLangOpts().CPlusPlus;
6939 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6941 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6947 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6949 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6950 Expr *LHSExpr, Expr *RHSExpr) {
6951 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6952 Expr* IndexExpr = RHSExpr;
6954 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6955 IndexExpr = LHSExpr;
6958 bool IsStringPlusInt = StrExpr &&
6959 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6960 if (!IsStringPlusInt)
6964 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6965 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6966 if (index.isNonNegative() &&
6967 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6968 index.isUnsigned()))
6972 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6973 Self.Diag(OpLoc, diag::warn_string_plus_int)
6974 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6976 // Only print a fixit for "str" + int, not for int + "str".
6977 if (IndexExpr == RHSExpr) {
6978 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6979 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
6980 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6981 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6982 << FixItHint::CreateInsertion(EndLoc, "]");
6984 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
6987 /// \brief Emit a warning when adding a char literal to a string.
6988 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
6989 Expr *LHSExpr, Expr *RHSExpr) {
6990 const DeclRefExpr *StringRefExpr =
6991 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
6992 const CharacterLiteral *CharExpr =
6993 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
6994 if (!StringRefExpr) {
6995 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
6996 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
6999 if (!CharExpr || !StringRefExpr)
7002 const QualType StringType = StringRefExpr->getType();
7004 // Return if not a PointerType.
7005 if (!StringType->isAnyPointerType())
7008 // Return if not a CharacterType.
7009 if (!StringType->getPointeeType()->isAnyCharacterType())
7012 ASTContext &Ctx = Self.getASTContext();
7013 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7015 const QualType CharType = CharExpr->getType();
7016 if (!CharType->isAnyCharacterType() &&
7017 CharType->isIntegerType() &&
7018 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7019 Self.Diag(OpLoc, diag::warn_string_plus_char)
7020 << DiagRange << Ctx.CharTy;
7022 Self.Diag(OpLoc, diag::warn_string_plus_char)
7023 << DiagRange << CharExpr->getType();
7026 // Only print a fixit for str + char, not for char + str.
7027 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7028 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7029 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7030 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7031 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7032 << FixItHint::CreateInsertion(EndLoc, "]");
7034 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7038 /// \brief Emit error when two pointers are incompatible.
7039 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7040 Expr *LHSExpr, Expr *RHSExpr) {
7041 assert(LHSExpr->getType()->isAnyPointerType());
7042 assert(RHSExpr->getType()->isAnyPointerType());
7043 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7044 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7045 << RHSExpr->getSourceRange();
7048 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7049 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7050 QualType* CompLHSTy) {
7051 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7053 if (LHS.get()->getType()->isVectorType() ||
7054 RHS.get()->getType()->isVectorType()) {
7055 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7056 if (CompLHSTy) *CompLHSTy = compType;
7060 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7061 if (LHS.isInvalid() || RHS.isInvalid())
7064 // Diagnose "string literal" '+' int and string '+' "char literal".
7065 if (Opc == BO_Add) {
7066 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7067 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7070 // handle the common case first (both operands are arithmetic).
7071 if (!compType.isNull() && compType->isArithmeticType()) {
7072 if (CompLHSTy) *CompLHSTy = compType;
7076 // Type-checking. Ultimately the pointer's going to be in PExp;
7077 // note that we bias towards the LHS being the pointer.
7078 Expr *PExp = LHS.get(), *IExp = RHS.get();
7081 if (PExp->getType()->isPointerType()) {
7082 isObjCPointer = false;
7083 } else if (PExp->getType()->isObjCObjectPointerType()) {
7084 isObjCPointer = true;
7086 std::swap(PExp, IExp);
7087 if (PExp->getType()->isPointerType()) {
7088 isObjCPointer = false;
7089 } else if (PExp->getType()->isObjCObjectPointerType()) {
7090 isObjCPointer = true;
7092 return InvalidOperands(Loc, LHS, RHS);
7095 assert(PExp->getType()->isAnyPointerType());
7097 if (!IExp->getType()->isIntegerType())
7098 return InvalidOperands(Loc, LHS, RHS);
7100 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7103 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7106 // Check array bounds for pointer arithemtic
7107 CheckArrayAccess(PExp, IExp);
7110 QualType LHSTy = Context.isPromotableBitField(LHS.get());
7111 if (LHSTy.isNull()) {
7112 LHSTy = LHS.get()->getType();
7113 if (LHSTy->isPromotableIntegerType())
7114 LHSTy = Context.getPromotedIntegerType(LHSTy);
7119 return PExp->getType();
7123 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7125 QualType* CompLHSTy) {
7126 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7128 if (LHS.get()->getType()->isVectorType() ||
7129 RHS.get()->getType()->isVectorType()) {
7130 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7131 if (CompLHSTy) *CompLHSTy = compType;
7135 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7136 if (LHS.isInvalid() || RHS.isInvalid())
7139 // Enforce type constraints: C99 6.5.6p3.
7141 // Handle the common case first (both operands are arithmetic).
7142 if (!compType.isNull() && compType->isArithmeticType()) {
7143 if (CompLHSTy) *CompLHSTy = compType;
7147 // Either ptr - int or ptr - ptr.
7148 if (LHS.get()->getType()->isAnyPointerType()) {
7149 QualType lpointee = LHS.get()->getType()->getPointeeType();
7151 // Diagnose bad cases where we step over interface counts.
7152 if (LHS.get()->getType()->isObjCObjectPointerType() &&
7153 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7156 // The result type of a pointer-int computation is the pointer type.
7157 if (RHS.get()->getType()->isIntegerType()) {
7158 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7161 // Check array bounds for pointer arithemtic
7162 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
7163 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7165 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7166 return LHS.get()->getType();
7169 // Handle pointer-pointer subtractions.
7170 if (const PointerType *RHSPTy
7171 = RHS.get()->getType()->getAs<PointerType>()) {
7172 QualType rpointee = RHSPTy->getPointeeType();
7174 if (getLangOpts().CPlusPlus) {
7175 // Pointee types must be the same: C++ [expr.add]
7176 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7177 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7180 // Pointee types must be compatible C99 6.5.6p3
7181 if (!Context.typesAreCompatible(
7182 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7183 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7184 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7189 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7190 LHS.get(), RHS.get()))
7193 // The pointee type may have zero size. As an extension, a structure or
7194 // union may have zero size or an array may have zero length. In this
7195 // case subtraction does not make sense.
7196 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7197 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7198 if (ElementSize.isZero()) {
7199 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7200 << rpointee.getUnqualifiedType()
7201 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7205 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7206 return Context.getPointerDiffType();
7210 return InvalidOperands(Loc, LHS, RHS);
7213 static bool isScopedEnumerationType(QualType T) {
7214 if (const EnumType *ET = dyn_cast<EnumType>(T))
7215 return ET->getDecl()->isScoped();
7219 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7220 SourceLocation Loc, unsigned Opc,
7222 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7223 // so skip remaining warnings as we don't want to modify values within Sema.
7224 if (S.getLangOpts().OpenCL)
7228 // Check right/shifter operand
7229 if (RHS.get()->isValueDependent() ||
7230 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7233 if (Right.isNegative()) {
7234 S.DiagRuntimeBehavior(Loc, RHS.get(),
7235 S.PDiag(diag::warn_shift_negative)
7236 << RHS.get()->getSourceRange());
7239 llvm::APInt LeftBits(Right.getBitWidth(),
7240 S.Context.getTypeSize(LHS.get()->getType()));
7241 if (Right.uge(LeftBits)) {
7242 S.DiagRuntimeBehavior(Loc, RHS.get(),
7243 S.PDiag(diag::warn_shift_gt_typewidth)
7244 << RHS.get()->getSourceRange());
7250 // When left shifting an ICE which is signed, we can check for overflow which
7251 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7252 // integers have defined behavior modulo one more than the maximum value
7253 // representable in the result type, so never warn for those.
7255 if (LHS.get()->isValueDependent() ||
7256 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7257 LHSType->hasUnsignedIntegerRepresentation())
7259 llvm::APInt ResultBits =
7260 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7261 if (LeftBits.uge(ResultBits))
7263 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7264 Result = Result.shl(Right);
7266 // Print the bit representation of the signed integer as an unsigned
7267 // hexadecimal number.
7268 SmallString<40> HexResult;
7269 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7271 // If we are only missing a sign bit, this is less likely to result in actual
7272 // bugs -- if the result is cast back to an unsigned type, it will have the
7273 // expected value. Thus we place this behind a different warning that can be
7274 // turned off separately if needed.
7275 if (LeftBits == ResultBits - 1) {
7276 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7277 << HexResult.str() << LHSType
7278 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7282 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7283 << HexResult.str() << Result.getMinSignedBits() << LHSType
7284 << Left.getBitWidth() << LHS.get()->getSourceRange()
7285 << RHS.get()->getSourceRange();
7289 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7290 SourceLocation Loc, unsigned Opc,
7291 bool IsCompAssign) {
7292 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7294 // Vector shifts promote their scalar inputs to vector type.
7295 if (LHS.get()->getType()->isVectorType() ||
7296 RHS.get()->getType()->isVectorType())
7297 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7299 // Shifts don't perform usual arithmetic conversions, they just do integer
7300 // promotions on each operand. C99 6.5.7p3
7302 // For the LHS, do usual unary conversions, but then reset them away
7303 // if this is a compound assignment.
7304 ExprResult OldLHS = LHS;
7305 LHS = UsualUnaryConversions(LHS.take());
7306 if (LHS.isInvalid())
7308 QualType LHSType = LHS.get()->getType();
7309 if (IsCompAssign) LHS = OldLHS;
7311 // The RHS is simpler.
7312 RHS = UsualUnaryConversions(RHS.take());
7313 if (RHS.isInvalid())
7315 QualType RHSType = RHS.get()->getType();
7317 // C99 6.5.7p2: Each of the operands shall have integer type.
7318 if (!LHSType->hasIntegerRepresentation() ||
7319 !RHSType->hasIntegerRepresentation())
7320 return InvalidOperands(Loc, LHS, RHS);
7322 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7323 // hasIntegerRepresentation() above instead of this.
7324 if (isScopedEnumerationType(LHSType) ||
7325 isScopedEnumerationType(RHSType)) {
7326 return InvalidOperands(Loc, LHS, RHS);
7328 // Sanity-check shift operands
7329 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7331 // "The type of the result is that of the promoted left operand."
7335 static bool IsWithinTemplateSpecialization(Decl *D) {
7336 if (DeclContext *DC = D->getDeclContext()) {
7337 if (isa<ClassTemplateSpecializationDecl>(DC))
7339 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7340 return FD->isFunctionTemplateSpecialization();
7345 /// If two different enums are compared, raise a warning.
7346 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7348 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7349 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7351 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7354 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7358 // Ignore anonymous enums.
7359 if (!LHSEnumType->getDecl()->getIdentifier())
7361 if (!RHSEnumType->getDecl()->getIdentifier())
7364 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7367 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7368 << LHSStrippedType << RHSStrippedType
7369 << LHS->getSourceRange() << RHS->getSourceRange();
7372 /// \brief Diagnose bad pointer comparisons.
7373 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7374 ExprResult &LHS, ExprResult &RHS,
7376 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7377 : diag::ext_typecheck_comparison_of_distinct_pointers)
7378 << LHS.get()->getType() << RHS.get()->getType()
7379 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7382 /// \brief Returns false if the pointers are converted to a composite type,
7384 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7385 ExprResult &LHS, ExprResult &RHS) {
7386 // C++ [expr.rel]p2:
7387 // [...] Pointer conversions (4.10) and qualification
7388 // conversions (4.4) are performed on pointer operands (or on
7389 // a pointer operand and a null pointer constant) to bring
7390 // them to their composite pointer type. [...]
7392 // C++ [expr.eq]p1 uses the same notion for (in)equality
7393 // comparisons of pointers.
7396 // In addition, pointers to members can be compared, or a pointer to
7397 // member and a null pointer constant. Pointer to member conversions
7398 // (4.11) and qualification conversions (4.4) are performed to bring
7399 // them to a common type. If one operand is a null pointer constant,
7400 // the common type is the type of the other operand. Otherwise, the
7401 // common type is a pointer to member type similar (4.4) to the type
7402 // of one of the operands, with a cv-qualification signature (4.4)
7403 // that is the union of the cv-qualification signatures of the operand
7406 QualType LHSType = LHS.get()->getType();
7407 QualType RHSType = RHS.get()->getType();
7408 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7409 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7411 bool NonStandardCompositeType = false;
7412 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7413 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7415 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7419 if (NonStandardCompositeType)
7420 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7421 << LHSType << RHSType << T << LHS.get()->getSourceRange()
7422 << RHS.get()->getSourceRange();
7424 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7425 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7429 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7433 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7434 : diag::ext_typecheck_comparison_of_fptr_to_void)
7435 << LHS.get()->getType() << RHS.get()->getType()
7436 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7439 static bool isObjCObjectLiteral(ExprResult &E) {
7440 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7441 case Stmt::ObjCArrayLiteralClass:
7442 case Stmt::ObjCDictionaryLiteralClass:
7443 case Stmt::ObjCStringLiteralClass:
7444 case Stmt::ObjCBoxedExprClass:
7447 // Note that ObjCBoolLiteral is NOT an object literal!
7452 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7453 const ObjCObjectPointerType *Type =
7454 LHS->getType()->getAs<ObjCObjectPointerType>();
7456 // If this is not actually an Objective-C object, bail out.
7460 // Get the LHS object's interface type.
7461 QualType InterfaceType = Type->getPointeeType();
7462 if (const ObjCObjectType *iQFaceTy =
7463 InterfaceType->getAsObjCQualifiedInterfaceType())
7464 InterfaceType = iQFaceTy->getBaseType();
7466 // If the RHS isn't an Objective-C object, bail out.
7467 if (!RHS->getType()->isObjCObjectPointerType())
7470 // Try to find the -isEqual: method.
7471 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7472 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7476 if (Type->isObjCIdType()) {
7477 // For 'id', just check the global pool.
7478 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7479 /*receiverId=*/true,
7483 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7491 QualType T = Method->param_begin()[0]->getType();
7492 if (!T->isObjCObjectPointerType())
7495 QualType R = Method->getResultType();
7496 if (!R->isScalarType())
7502 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7503 FromE = FromE->IgnoreParenImpCasts();
7504 switch (FromE->getStmtClass()) {
7507 case Stmt::ObjCStringLiteralClass:
7510 case Stmt::ObjCArrayLiteralClass:
7513 case Stmt::ObjCDictionaryLiteralClass:
7514 // "dictionary literal"
7515 return LK_Dictionary;
7516 case Stmt::BlockExprClass:
7518 case Stmt::ObjCBoxedExprClass: {
7519 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7520 switch (Inner->getStmtClass()) {
7521 case Stmt::IntegerLiteralClass:
7522 case Stmt::FloatingLiteralClass:
7523 case Stmt::CharacterLiteralClass:
7524 case Stmt::ObjCBoolLiteralExprClass:
7525 case Stmt::CXXBoolLiteralExprClass:
7526 // "numeric literal"
7528 case Stmt::ImplicitCastExprClass: {
7529 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7530 // Boolean literals can be represented by implicit casts.
7531 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7544 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7545 ExprResult &LHS, ExprResult &RHS,
7546 BinaryOperator::Opcode Opc){
7549 if (isObjCObjectLiteral(LHS)) {
7550 Literal = LHS.get();
7553 Literal = RHS.get();
7557 // Don't warn on comparisons against nil.
7558 Other = Other->IgnoreParenCasts();
7559 if (Other->isNullPointerConstant(S.getASTContext(),
7560 Expr::NPC_ValueDependentIsNotNull))
7563 // This should be kept in sync with warn_objc_literal_comparison.
7564 // LK_String should always be after the other literals, since it has its own
7566 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7567 assert(LiteralKind != Sema::LK_Block);
7568 if (LiteralKind == Sema::LK_None) {
7569 llvm_unreachable("Unknown Objective-C object literal kind");
7572 if (LiteralKind == Sema::LK_String)
7573 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7574 << Literal->getSourceRange();
7576 S.Diag(Loc, diag::warn_objc_literal_comparison)
7577 << LiteralKind << Literal->getSourceRange();
7579 if (BinaryOperator::isEqualityOp(Opc) &&
7580 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7581 SourceLocation Start = LHS.get()->getLocStart();
7582 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7583 CharSourceRange OpRange =
7584 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7586 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7587 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7588 << FixItHint::CreateReplacement(OpRange, " isEqual:")
7589 << FixItHint::CreateInsertion(End, "]");
7593 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7596 unsigned OpaqueOpc) {
7597 // This checking requires bools.
7598 if (!S.getLangOpts().Bool) return;
7600 // Check that left hand side is !something.
7601 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7602 if (!UO || UO->getOpcode() != UO_LNot) return;
7604 // Only check if the right hand side is non-bool arithmetic type.
7605 if (RHS.get()->getType()->isBooleanType()) return;
7607 // Make sure that the something in !something is not bool.
7608 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7609 if (SubExpr->getType()->isBooleanType()) return;
7612 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7615 // First note suggest !(x < y)
7616 SourceLocation FirstOpen = SubExpr->getLocStart();
7617 SourceLocation FirstClose = RHS.get()->getLocEnd();
7618 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7619 if (FirstClose.isInvalid())
7620 FirstOpen = SourceLocation();
7621 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7622 << FixItHint::CreateInsertion(FirstOpen, "(")
7623 << FixItHint::CreateInsertion(FirstClose, ")");
7625 // Second note suggests (!x) < y
7626 SourceLocation SecondOpen = LHS.get()->getLocStart();
7627 SourceLocation SecondClose = LHS.get()->getLocEnd();
7628 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7629 if (SecondClose.isInvalid())
7630 SecondOpen = SourceLocation();
7631 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7632 << FixItHint::CreateInsertion(SecondOpen, "(")
7633 << FixItHint::CreateInsertion(SecondClose, ")");
7636 // Get the decl for a simple expression: a reference to a variable,
7637 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7638 static ValueDecl *getCompareDecl(Expr *E) {
7639 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7640 return DR->getDecl();
7641 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7642 if (Ivar->isFreeIvar())
7643 return Ivar->getDecl();
7645 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7646 if (Mem->isImplicitAccess())
7647 return Mem->getMemberDecl();
7652 // C99 6.5.8, C++ [expr.rel]
7653 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7654 SourceLocation Loc, unsigned OpaqueOpc,
7655 bool IsRelational) {
7656 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7658 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7660 // Handle vector comparisons separately.
7661 if (LHS.get()->getType()->isVectorType() ||
7662 RHS.get()->getType()->isVectorType())
7663 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7665 QualType LHSType = LHS.get()->getType();
7666 QualType RHSType = RHS.get()->getType();
7668 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7669 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7671 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7672 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7674 if (!LHSType->hasFloatingRepresentation() &&
7675 !(LHSType->isBlockPointerType() && IsRelational) &&
7676 !LHS.get()->getLocStart().isMacroID() &&
7677 !RHS.get()->getLocStart().isMacroID() &&
7678 ActiveTemplateInstantiations.empty()) {
7679 // For non-floating point types, check for self-comparisons of the form
7680 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7681 // often indicate logic errors in the program.
7683 // NOTE: Don't warn about comparison expressions resulting from macro
7684 // expansion. Also don't warn about comparisons which are only self
7685 // comparisons within a template specialization. The warnings should catch
7686 // obvious cases in the definition of the template anyways. The idea is to
7687 // warn when the typed comparison operator will always evaluate to the same
7689 ValueDecl *DL = getCompareDecl(LHSStripped);
7690 ValueDecl *DR = getCompareDecl(RHSStripped);
7691 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7692 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7697 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7698 !DL->getType()->isReferenceType() &&
7699 !DR->getType()->isReferenceType()) {
7700 // what is it always going to eval to?
7701 char always_evals_to;
7703 case BO_EQ: // e.g. array1 == array2
7704 always_evals_to = 0; // false
7706 case BO_NE: // e.g. array1 != array2
7707 always_evals_to = 1; // true
7710 // best we can say is 'a constant'
7711 always_evals_to = 2; // e.g. array1 <= array2
7714 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7716 << always_evals_to);
7719 if (isa<CastExpr>(LHSStripped))
7720 LHSStripped = LHSStripped->IgnoreParenCasts();
7721 if (isa<CastExpr>(RHSStripped))
7722 RHSStripped = RHSStripped->IgnoreParenCasts();
7724 // Warn about comparisons against a string constant (unless the other
7725 // operand is null), the user probably wants strcmp.
7726 Expr *literalString = 0;
7727 Expr *literalStringStripped = 0;
7728 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7729 !RHSStripped->isNullPointerConstant(Context,
7730 Expr::NPC_ValueDependentIsNull)) {
7731 literalString = LHS.get();
7732 literalStringStripped = LHSStripped;
7733 } else if ((isa<StringLiteral>(RHSStripped) ||
7734 isa<ObjCEncodeExpr>(RHSStripped)) &&
7735 !LHSStripped->isNullPointerConstant(Context,
7736 Expr::NPC_ValueDependentIsNull)) {
7737 literalString = RHS.get();
7738 literalStringStripped = RHSStripped;
7741 if (literalString) {
7742 DiagRuntimeBehavior(Loc, 0,
7743 PDiag(diag::warn_stringcompare)
7744 << isa<ObjCEncodeExpr>(literalStringStripped)
7745 << literalString->getSourceRange());
7749 // C99 6.5.8p3 / C99 6.5.9p4
7750 UsualArithmeticConversions(LHS, RHS);
7751 if (LHS.isInvalid() || RHS.isInvalid())
7754 LHSType = LHS.get()->getType();
7755 RHSType = RHS.get()->getType();
7757 // The result of comparisons is 'bool' in C++, 'int' in C.
7758 QualType ResultTy = Context.getLogicalOperationType();
7761 if (LHSType->isRealType() && RHSType->isRealType())
7764 // Check for comparisons of floating point operands using != and ==.
7765 if (LHSType->hasFloatingRepresentation())
7766 CheckFloatComparison(Loc, LHS.get(), RHS.get());
7768 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7772 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7773 Expr::NPC_ValueDependentIsNull);
7774 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7775 Expr::NPC_ValueDependentIsNull);
7777 // All of the following pointer-related warnings are GCC extensions, except
7778 // when handling null pointer constants.
7779 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7780 QualType LCanPointeeTy =
7781 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7782 QualType RCanPointeeTy =
7783 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7785 if (getLangOpts().CPlusPlus) {
7786 if (LCanPointeeTy == RCanPointeeTy)
7788 if (!IsRelational &&
7789 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7790 // Valid unless comparison between non-null pointer and function pointer
7791 // This is a gcc extension compatibility comparison.
7792 // In a SFINAE context, we treat this as a hard error to maintain
7793 // conformance with the C++ standard.
7794 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7795 && !LHSIsNull && !RHSIsNull) {
7796 diagnoseFunctionPointerToVoidComparison(
7797 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7799 if (isSFINAEContext())
7802 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7807 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7812 // C99 6.5.9p2 and C99 6.5.8p2
7813 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7814 RCanPointeeTy.getUnqualifiedType())) {
7815 // Valid unless a relational comparison of function pointers
7816 if (IsRelational && LCanPointeeTy->isFunctionType()) {
7817 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7818 << LHSType << RHSType << LHS.get()->getSourceRange()
7819 << RHS.get()->getSourceRange();
7821 } else if (!IsRelational &&
7822 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7823 // Valid unless comparison between non-null pointer and function pointer
7824 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7825 && !LHSIsNull && !RHSIsNull)
7826 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7830 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7832 if (LCanPointeeTy != RCanPointeeTy) {
7833 if (LHSIsNull && !RHSIsNull)
7834 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7836 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7841 if (getLangOpts().CPlusPlus) {
7842 // Comparison of nullptr_t with itself.
7843 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7846 // Comparison of pointers with null pointer constants and equality
7847 // comparisons of member pointers to null pointer constants.
7849 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7851 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7852 RHS = ImpCastExprToType(RHS.take(), LHSType,
7853 LHSType->isMemberPointerType()
7854 ? CK_NullToMemberPointer
7855 : CK_NullToPointer);
7859 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7861 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7862 LHS = ImpCastExprToType(LHS.take(), RHSType,
7863 RHSType->isMemberPointerType()
7864 ? CK_NullToMemberPointer
7865 : CK_NullToPointer);
7869 // Comparison of member pointers.
7870 if (!IsRelational &&
7871 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7872 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7878 // Handle scoped enumeration types specifically, since they don't promote
7880 if (LHS.get()->getType()->isEnumeralType() &&
7881 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7882 RHS.get()->getType()))
7886 // Handle block pointer types.
7887 if (!IsRelational && LHSType->isBlockPointerType() &&
7888 RHSType->isBlockPointerType()) {
7889 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7890 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7892 if (!LHSIsNull && !RHSIsNull &&
7893 !Context.typesAreCompatible(lpointee, rpointee)) {
7894 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7895 << LHSType << RHSType << LHS.get()->getSourceRange()
7896 << RHS.get()->getSourceRange();
7898 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7902 // Allow block pointers to be compared with null pointer constants.
7904 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7905 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7906 if (!LHSIsNull && !RHSIsNull) {
7907 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7908 ->getPointeeType()->isVoidType())
7909 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7910 ->getPointeeType()->isVoidType())))
7911 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7912 << LHSType << RHSType << LHS.get()->getSourceRange()
7913 << RHS.get()->getSourceRange();
7915 if (LHSIsNull && !RHSIsNull)
7916 LHS = ImpCastExprToType(LHS.take(), RHSType,
7917 RHSType->isPointerType() ? CK_BitCast
7918 : CK_AnyPointerToBlockPointerCast);
7920 RHS = ImpCastExprToType(RHS.take(), LHSType,
7921 LHSType->isPointerType() ? CK_BitCast
7922 : CK_AnyPointerToBlockPointerCast);
7926 if (LHSType->isObjCObjectPointerType() ||
7927 RHSType->isObjCObjectPointerType()) {
7928 const PointerType *LPT = LHSType->getAs<PointerType>();
7929 const PointerType *RPT = RHSType->getAs<PointerType>();
7931 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7932 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7934 if (!LPtrToVoid && !RPtrToVoid &&
7935 !Context.typesAreCompatible(LHSType, RHSType)) {
7936 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7939 if (LHSIsNull && !RHSIsNull) {
7940 Expr *E = LHS.take();
7941 if (getLangOpts().ObjCAutoRefCount)
7942 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
7943 LHS = ImpCastExprToType(E, RHSType,
7944 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7947 Expr *E = RHS.take();
7948 if (getLangOpts().ObjCAutoRefCount)
7949 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
7950 RHS = ImpCastExprToType(E, LHSType,
7951 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7955 if (LHSType->isObjCObjectPointerType() &&
7956 RHSType->isObjCObjectPointerType()) {
7957 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7958 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7960 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7961 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7963 if (LHSIsNull && !RHSIsNull)
7964 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7966 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7970 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7971 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7972 unsigned DiagID = 0;
7973 bool isError = false;
7974 if (LangOpts.DebuggerSupport) {
7975 // Under a debugger, allow the comparison of pointers to integers,
7976 // since users tend to want to compare addresses.
7977 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7978 (RHSIsNull && RHSType->isIntegerType())) {
7979 if (IsRelational && !getLangOpts().CPlusPlus)
7980 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7981 } else if (IsRelational && !getLangOpts().CPlusPlus)
7982 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7983 else if (getLangOpts().CPlusPlus) {
7984 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7987 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7991 << LHSType << RHSType << LHS.get()->getSourceRange()
7992 << RHS.get()->getSourceRange();
7997 if (LHSType->isIntegerType())
7998 LHS = ImpCastExprToType(LHS.take(), RHSType,
7999 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8001 RHS = ImpCastExprToType(RHS.take(), LHSType,
8002 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8006 // Handle block pointers.
8007 if (!IsRelational && RHSIsNull
8008 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8009 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
8012 if (!IsRelational && LHSIsNull
8013 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8014 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
8018 return InvalidOperands(Loc, LHS, RHS);
8022 // Return a signed type that is of identical size and number of elements.
8023 // For floating point vectors, return an integer type of identical size
8024 // and number of elements.
8025 QualType Sema::GetSignedVectorType(QualType V) {
8026 const VectorType *VTy = V->getAs<VectorType>();
8027 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8028 if (TypeSize == Context.getTypeSize(Context.CharTy))
8029 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8030 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8031 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8032 else if (TypeSize == Context.getTypeSize(Context.IntTy))
8033 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8034 else if (TypeSize == Context.getTypeSize(Context.LongTy))
8035 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8036 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8037 "Unhandled vector element size in vector compare");
8038 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8041 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8042 /// operates on extended vector types. Instead of producing an IntTy result,
8043 /// like a scalar comparison, a vector comparison produces a vector of integer
8045 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8047 bool IsRelational) {
8048 // Check to make sure we're operating on vectors of the same type and width,
8049 // Allowing one side to be a scalar of element type.
8050 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8054 QualType LHSType = LHS.get()->getType();
8056 // If AltiVec, the comparison results in a numeric type, i.e.
8057 // bool for C++, int for C
8058 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8059 return Context.getLogicalOperationType();
8061 // For non-floating point types, check for self-comparisons of the form
8062 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
8063 // often indicate logic errors in the program.
8064 if (!LHSType->hasFloatingRepresentation() &&
8065 ActiveTemplateInstantiations.empty()) {
8066 if (DeclRefExpr* DRL
8067 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8068 if (DeclRefExpr* DRR
8069 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8070 if (DRL->getDecl() == DRR->getDecl())
8071 DiagRuntimeBehavior(Loc, 0,
8072 PDiag(diag::warn_comparison_always)
8074 << 2 // "a constant"
8078 // Check for comparisons of floating point operands using != and ==.
8079 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8080 assert (RHS.get()->getType()->hasFloatingRepresentation());
8081 CheckFloatComparison(Loc, LHS.get(), RHS.get());
8084 // Return a signed type for the vector.
8085 return GetSignedVectorType(LHSType);
8088 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8089 SourceLocation Loc) {
8090 // Ensure that either both operands are of the same vector type, or
8091 // one operand is of a vector type and the other is of its element type.
8092 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8094 return InvalidOperands(Loc, LHS, RHS);
8095 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8096 vType->hasFloatingRepresentation())
8097 return InvalidOperands(Loc, LHS, RHS);
8099 return GetSignedVectorType(LHS.get()->getType());
8102 inline QualType Sema::CheckBitwiseOperands(
8103 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8104 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8106 if (LHS.get()->getType()->isVectorType() ||
8107 RHS.get()->getType()->isVectorType()) {
8108 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8109 RHS.get()->getType()->hasIntegerRepresentation())
8110 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8112 return InvalidOperands(Loc, LHS, RHS);
8115 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
8116 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8118 if (LHSResult.isInvalid() || RHSResult.isInvalid())
8120 LHS = LHSResult.take();
8121 RHS = RHSResult.take();
8123 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8125 return InvalidOperands(Loc, LHS, RHS);
8128 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8129 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8131 // Check vector operands differently.
8132 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8133 return CheckVectorLogicalOperands(LHS, RHS, Loc);
8135 // Diagnose cases where the user write a logical and/or but probably meant a
8136 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
8138 if (LHS.get()->getType()->isIntegerType() &&
8139 !LHS.get()->getType()->isBooleanType() &&
8140 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8141 // Don't warn in macros or template instantiations.
8142 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8143 // If the RHS can be constant folded, and if it constant folds to something
8144 // that isn't 0 or 1 (which indicate a potential logical operation that
8145 // happened to fold to true/false) then warn.
8146 // Parens on the RHS are ignored.
8147 llvm::APSInt Result;
8148 if (RHS.get()->EvaluateAsInt(Result, Context))
8149 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
8150 (Result != 0 && Result != 1)) {
8151 Diag(Loc, diag::warn_logical_instead_of_bitwise)
8152 << RHS.get()->getSourceRange()
8153 << (Opc == BO_LAnd ? "&&" : "||");
8154 // Suggest replacing the logical operator with the bitwise version
8155 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8156 << (Opc == BO_LAnd ? "&" : "|")
8157 << FixItHint::CreateReplacement(SourceRange(
8158 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8160 Opc == BO_LAnd ? "&" : "|");
8162 // Suggest replacing "Foo() && kNonZero" with "Foo()"
8163 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8164 << FixItHint::CreateRemoval(
8166 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8167 0, getSourceManager(),
8169 RHS.get()->getLocEnd()));
8173 if (!Context.getLangOpts().CPlusPlus) {
8174 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8175 // not operate on the built-in scalar and vector float types.
8176 if (Context.getLangOpts().OpenCL &&
8177 Context.getLangOpts().OpenCLVersion < 120) {
8178 if (LHS.get()->getType()->isFloatingType() ||
8179 RHS.get()->getType()->isFloatingType())
8180 return InvalidOperands(Loc, LHS, RHS);
8183 LHS = UsualUnaryConversions(LHS.take());
8184 if (LHS.isInvalid())
8187 RHS = UsualUnaryConversions(RHS.take());
8188 if (RHS.isInvalid())
8191 if (!LHS.get()->getType()->isScalarType() ||
8192 !RHS.get()->getType()->isScalarType())
8193 return InvalidOperands(Loc, LHS, RHS);
8195 return Context.IntTy;
8198 // The following is safe because we only use this method for
8199 // non-overloadable operands.
8201 // C++ [expr.log.and]p1
8202 // C++ [expr.log.or]p1
8203 // The operands are both contextually converted to type bool.
8204 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8205 if (LHSRes.isInvalid())
8206 return InvalidOperands(Loc, LHS, RHS);
8209 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8210 if (RHSRes.isInvalid())
8211 return InvalidOperands(Loc, LHS, RHS);
8214 // C++ [expr.log.and]p2
8215 // C++ [expr.log.or]p2
8216 // The result is a bool.
8217 return Context.BoolTy;
8220 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8221 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8222 if (!ME) return false;
8223 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8224 ObjCMessageExpr *Base =
8225 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8226 if (!Base) return false;
8227 return Base->getMethodDecl() != 0;
8230 /// Is the given expression (which must be 'const') a reference to a
8231 /// variable which was originally non-const, but which has become
8232 /// 'const' due to being captured within a block?
8233 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8234 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8235 assert(E->isLValue() && E->getType().isConstQualified());
8236 E = E->IgnoreParens();
8238 // Must be a reference to a declaration from an enclosing scope.
8239 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8240 if (!DRE) return NCCK_None;
8241 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8243 // The declaration must be a variable which is not declared 'const'.
8244 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8245 if (!var) return NCCK_None;
8246 if (var->getType().isConstQualified()) return NCCK_None;
8247 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8249 // Decide whether the first capture was for a block or a lambda.
8250 DeclContext *DC = S.CurContext, *Prev = 0;
8251 while (DC != var->getDeclContext()) {
8253 DC = DC->getParent();
8255 // Unless we have an init-capture, we've gone one step too far.
8256 if (!var->isInitCapture())
8258 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8261 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
8262 /// emit an error and return true. If so, return false.
8263 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8264 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8265 SourceLocation OrigLoc = Loc;
8266 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8268 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8269 IsLV = Expr::MLV_InvalidMessageExpression;
8270 if (IsLV == Expr::MLV_Valid)
8274 bool NeedType = false;
8275 switch (IsLV) { // C99 6.5.16p2
8276 case Expr::MLV_ConstQualified:
8277 Diag = diag::err_typecheck_assign_const;
8279 // Use a specialized diagnostic when we're assigning to an object
8280 // from an enclosing function or block.
8281 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8282 if (NCCK == NCCK_Block)
8283 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8285 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8289 // In ARC, use some specialized diagnostics for occasions where we
8290 // infer 'const'. These are always pseudo-strong variables.
8291 if (S.getLangOpts().ObjCAutoRefCount) {
8292 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8293 if (declRef && isa<VarDecl>(declRef->getDecl())) {
8294 VarDecl *var = cast<VarDecl>(declRef->getDecl());
8296 // Use the normal diagnostic if it's pseudo-__strong but the
8297 // user actually wrote 'const'.
8298 if (var->isARCPseudoStrong() &&
8299 (!var->getTypeSourceInfo() ||
8300 !var->getTypeSourceInfo()->getType().isConstQualified())) {
8301 // There are two pseudo-strong cases:
8303 ObjCMethodDecl *method = S.getCurMethodDecl();
8304 if (method && var == method->getSelfDecl())
8305 Diag = method->isClassMethod()
8306 ? diag::err_typecheck_arc_assign_self_class_method
8307 : diag::err_typecheck_arc_assign_self;
8309 // - fast enumeration variables
8311 Diag = diag::err_typecheck_arr_assign_enumeration;
8315 Assign = SourceRange(OrigLoc, OrigLoc);
8316 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8317 // We need to preserve the AST regardless, so migration tool
8325 case Expr::MLV_ArrayType:
8326 case Expr::MLV_ArrayTemporary:
8327 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8330 case Expr::MLV_NotObjectType:
8331 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8334 case Expr::MLV_LValueCast:
8335 Diag = diag::err_typecheck_lvalue_casts_not_supported;
8337 case Expr::MLV_Valid:
8338 llvm_unreachable("did not take early return for MLV_Valid");
8339 case Expr::MLV_InvalidExpression:
8340 case Expr::MLV_MemberFunction:
8341 case Expr::MLV_ClassTemporary:
8342 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8344 case Expr::MLV_IncompleteType:
8345 case Expr::MLV_IncompleteVoidType:
8346 return S.RequireCompleteType(Loc, E->getType(),
8347 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8348 case Expr::MLV_DuplicateVectorComponents:
8349 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8351 case Expr::MLV_NoSetterProperty:
8352 llvm_unreachable("readonly properties should be processed differently");
8353 case Expr::MLV_InvalidMessageExpression:
8354 Diag = diag::error_readonly_message_assignment;
8356 case Expr::MLV_SubObjCPropertySetting:
8357 Diag = diag::error_no_subobject_property_setting;
8363 Assign = SourceRange(OrigLoc, OrigLoc);
8365 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8367 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8371 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8375 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8376 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8377 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8378 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8379 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8382 // Objective-C instance variables
8383 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8384 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8385 if (OL && OR && OL->getDecl() == OR->getDecl()) {
8386 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8387 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8388 if (RL && RR && RL->getDecl() == RR->getDecl())
8389 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8394 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8396 QualType CompoundType) {
8397 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8399 // Verify that LHS is a modifiable lvalue, and emit error if not.
8400 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8403 QualType LHSType = LHSExpr->getType();
8404 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8406 AssignConvertType ConvTy;
8407 if (CompoundType.isNull()) {
8408 Expr *RHSCheck = RHS.get();
8410 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8412 QualType LHSTy(LHSType);
8413 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8414 if (RHS.isInvalid())
8416 // Special case of NSObject attributes on c-style pointer types.
8417 if (ConvTy == IncompatiblePointer &&
8418 ((Context.isObjCNSObjectType(LHSType) &&
8419 RHSType->isObjCObjectPointerType()) ||
8420 (Context.isObjCNSObjectType(RHSType) &&
8421 LHSType->isObjCObjectPointerType())))
8422 ConvTy = Compatible;
8424 if (ConvTy == Compatible &&
8425 LHSType->isObjCObjectType())
8426 Diag(Loc, diag::err_objc_object_assignment)
8429 // If the RHS is a unary plus or minus, check to see if they = and + are
8430 // right next to each other. If so, the user may have typo'd "x =+ 4"
8431 // instead of "x += 4".
8432 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8433 RHSCheck = ICE->getSubExpr();
8434 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8435 if ((UO->getOpcode() == UO_Plus ||
8436 UO->getOpcode() == UO_Minus) &&
8437 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8438 // Only if the two operators are exactly adjacent.
8439 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8440 // And there is a space or other character before the subexpr of the
8441 // unary +/-. We don't want to warn on "x=-1".
8442 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8443 UO->getSubExpr()->getLocStart().isFileID()) {
8444 Diag(Loc, diag::warn_not_compound_assign)
8445 << (UO->getOpcode() == UO_Plus ? "+" : "-")
8446 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8450 if (ConvTy == Compatible) {
8451 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8452 // Warn about retain cycles where a block captures the LHS, but
8453 // not if the LHS is a simple variable into which the block is
8454 // being stored...unless that variable can be captured by reference!
8455 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8456 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8457 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8458 checkRetainCycles(LHSExpr, RHS.get());
8460 // It is safe to assign a weak reference into a strong variable.
8461 // Although this code can still have problems:
8462 // id x = self.weakProp;
8463 // id y = self.weakProp;
8464 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8465 // paths through the function. This should be revisited if
8466 // -Wrepeated-use-of-weak is made flow-sensitive.
8467 DiagnosticsEngine::Level Level =
8468 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8469 RHS.get()->getLocStart());
8470 if (Level != DiagnosticsEngine::Ignored)
8471 getCurFunction()->markSafeWeakUse(RHS.get());
8473 } else if (getLangOpts().ObjCAutoRefCount) {
8474 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8478 // Compound assignment "x += y"
8479 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8482 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8483 RHS.get(), AA_Assigning))
8486 CheckForNullPointerDereference(*this, LHSExpr);
8488 // C99 6.5.16p3: The type of an assignment expression is the type of the
8489 // left operand unless the left operand has qualified type, in which case
8490 // it is the unqualified version of the type of the left operand.
8491 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8492 // is converted to the type of the assignment expression (above).
8493 // C++ 5.17p1: the type of the assignment expression is that of its left
8495 return (getLangOpts().CPlusPlus
8496 ? LHSType : LHSType.getUnqualifiedType());
8500 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8501 SourceLocation Loc) {
8502 LHS = S.CheckPlaceholderExpr(LHS.take());
8503 RHS = S.CheckPlaceholderExpr(RHS.take());
8504 if (LHS.isInvalid() || RHS.isInvalid())
8507 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8508 // operands, but not unary promotions.
8509 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8511 // So we treat the LHS as a ignored value, and in C++ we allow the
8512 // containing site to determine what should be done with the RHS.
8513 LHS = S.IgnoredValueConversions(LHS.take());
8514 if (LHS.isInvalid())
8517 S.DiagnoseUnusedExprResult(LHS.get());
8519 if (!S.getLangOpts().CPlusPlus) {
8520 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8521 if (RHS.isInvalid())
8523 if (!RHS.get()->getType()->isVoidType())
8524 S.RequireCompleteType(Loc, RHS.get()->getType(),
8525 diag::err_incomplete_type);
8528 return RHS.get()->getType();
8531 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8532 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8533 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8535 SourceLocation OpLoc,
8536 bool IsInc, bool IsPrefix) {
8537 if (Op->isTypeDependent())
8538 return S.Context.DependentTy;
8540 QualType ResType = Op->getType();
8541 // Atomic types can be used for increment / decrement where the non-atomic
8542 // versions can, so ignore the _Atomic() specifier for the purpose of
8544 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8545 ResType = ResAtomicType->getValueType();
8547 assert(!ResType.isNull() && "no type for increment/decrement expression");
8549 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8550 // Decrement of bool is not allowed.
8552 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8555 // Increment of bool sets it to true, but is deprecated.
8556 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8557 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8558 // Error on enum increments and decrements in C++ mode
8559 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8561 } else if (ResType->isRealType()) {
8563 } else if (ResType->isPointerType()) {
8564 // C99 6.5.2.4p2, 6.5.6p2
8565 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8567 } else if (ResType->isObjCObjectPointerType()) {
8568 // On modern runtimes, ObjC pointer arithmetic is forbidden.
8569 // Otherwise, we just need a complete type.
8570 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8571 checkArithmeticOnObjCPointer(S, OpLoc, Op))
8573 } else if (ResType->isAnyComplexType()) {
8574 // C99 does not support ++/-- on complex types, we allow as an extension.
8575 S.Diag(OpLoc, diag::ext_integer_increment_complex)
8576 << ResType << Op->getSourceRange();
8577 } else if (ResType->isPlaceholderType()) {
8578 ExprResult PR = S.CheckPlaceholderExpr(Op);
8579 if (PR.isInvalid()) return QualType();
8580 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8582 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8583 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8584 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8585 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8586 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8588 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8589 << ResType << int(IsInc) << Op->getSourceRange();
8592 // At this point, we know we have a real, complex or pointer type.
8593 // Now make sure the operand is a modifiable lvalue.
8594 if (CheckForModifiableLvalue(Op, OpLoc, S))
8596 // In C++, a prefix increment is the same type as the operand. Otherwise
8597 // (in C or with postfix), the increment is the unqualified type of the
8599 if (IsPrefix && S.getLangOpts().CPlusPlus) {
8604 return ResType.getUnqualifiedType();
8609 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8610 /// This routine allows us to typecheck complex/recursive expressions
8611 /// where the declaration is needed for type checking. We only need to
8612 /// handle cases when the expression references a function designator
8613 /// or is an lvalue. Here are some examples:
8615 /// - &*****f => f for f a function designator.
8617 /// - &s.zz[1].yy -> s, if zz is an array
8618 /// - *(x + 1) -> x, if x is an array
8619 /// - &"123"[2] -> 0
8620 /// - & __real__ x -> x
8621 static ValueDecl *getPrimaryDecl(Expr *E) {
8622 switch (E->getStmtClass()) {
8623 case Stmt::DeclRefExprClass:
8624 return cast<DeclRefExpr>(E)->getDecl();
8625 case Stmt::MemberExprClass:
8626 // If this is an arrow operator, the address is an offset from
8627 // the base's value, so the object the base refers to is
8629 if (cast<MemberExpr>(E)->isArrow())
8631 // Otherwise, the expression refers to a part of the base
8632 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8633 case Stmt::ArraySubscriptExprClass: {
8634 // FIXME: This code shouldn't be necessary! We should catch the implicit
8635 // promotion of register arrays earlier.
8636 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8637 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8638 if (ICE->getSubExpr()->getType()->isArrayType())
8639 return getPrimaryDecl(ICE->getSubExpr());
8643 case Stmt::UnaryOperatorClass: {
8644 UnaryOperator *UO = cast<UnaryOperator>(E);
8646 switch(UO->getOpcode()) {
8650 return getPrimaryDecl(UO->getSubExpr());
8655 case Stmt::ParenExprClass:
8656 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8657 case Stmt::ImplicitCastExprClass:
8658 // If the result of an implicit cast is an l-value, we care about
8659 // the sub-expression; otherwise, the result here doesn't matter.
8660 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8669 AO_Vector_Element = 1,
8670 AO_Property_Expansion = 2,
8671 AO_Register_Variable = 3,
8675 /// \brief Diagnose invalid operand for address of operations.
8677 /// \param Type The type of operand which cannot have its address taken.
8678 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8679 Expr *E, unsigned Type) {
8680 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8683 /// CheckAddressOfOperand - The operand of & must be either a function
8684 /// designator or an lvalue designating an object. If it is an lvalue, the
8685 /// object cannot be declared with storage class register or be a bit field.
8686 /// Note: The usual conversions are *not* applied to the operand of the &
8687 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8688 /// In C++, the operand might be an overloaded function name, in which case
8689 /// we allow the '&' but retain the overloaded-function type.
8690 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8691 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8692 if (PTy->getKind() == BuiltinType::Overload) {
8693 Expr *E = OrigOp.get()->IgnoreParens();
8694 if (!isa<OverloadExpr>(E)) {
8695 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8696 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8697 << OrigOp.get()->getSourceRange();
8701 OverloadExpr *Ovl = cast<OverloadExpr>(E);
8702 if (isa<UnresolvedMemberExpr>(Ovl))
8703 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8704 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8705 << OrigOp.get()->getSourceRange();
8709 return Context.OverloadTy;
8712 if (PTy->getKind() == BuiltinType::UnknownAny)
8713 return Context.UnknownAnyTy;
8715 if (PTy->getKind() == BuiltinType::BoundMember) {
8716 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8717 << OrigOp.get()->getSourceRange();
8721 OrigOp = CheckPlaceholderExpr(OrigOp.take());
8722 if (OrigOp.isInvalid()) return QualType();
8725 if (OrigOp.get()->isTypeDependent())
8726 return Context.DependentTy;
8728 assert(!OrigOp.get()->getType()->isPlaceholderType());
8730 // Make sure to ignore parentheses in subsequent checks
8731 Expr *op = OrigOp.get()->IgnoreParens();
8733 if (getLangOpts().C99) {
8734 // Implement C99-only parts of addressof rules.
8735 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8736 if (uOp->getOpcode() == UO_Deref)
8737 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8738 // (assuming the deref expression is valid).
8739 return uOp->getSubExpr()->getType();
8741 // Technically, there should be a check for array subscript
8742 // expressions here, but the result of one is always an lvalue anyway.
8744 ValueDecl *dcl = getPrimaryDecl(op);
8745 Expr::LValueClassification lval = op->ClassifyLValue(Context);
8746 unsigned AddressOfError = AO_No_Error;
8748 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8749 bool sfinae = (bool)isSFINAEContext();
8750 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8751 : diag::ext_typecheck_addrof_temporary)
8752 << op->getType() << op->getSourceRange();
8755 // Materialize the temporary as an lvalue so that we can take its address.
8756 OrigOp = op = new (Context)
8757 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8758 } else if (isa<ObjCSelectorExpr>(op)) {
8759 return Context.getPointerType(op->getType());
8760 } else if (lval == Expr::LV_MemberFunction) {
8761 // If it's an instance method, make a member pointer.
8762 // The expression must have exactly the form &A::foo.
8764 // If the underlying expression isn't a decl ref, give up.
8765 if (!isa<DeclRefExpr>(op)) {
8766 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8767 << OrigOp.get()->getSourceRange();
8770 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8771 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8773 // The id-expression was parenthesized.
8774 if (OrigOp.get() != DRE) {
8775 Diag(OpLoc, diag::err_parens_pointer_member_function)
8776 << OrigOp.get()->getSourceRange();
8778 // The method was named without a qualifier.
8779 } else if (!DRE->getQualifier()) {
8780 if (MD->getParent()->getName().empty())
8781 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8782 << op->getSourceRange();
8784 SmallString<32> Str;
8785 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8786 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8787 << op->getSourceRange()
8788 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8792 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
8793 if (isa<CXXDestructorDecl>(MD))
8794 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
8796 return Context.getMemberPointerType(op->getType(),
8797 Context.getTypeDeclType(MD->getParent()).getTypePtr());
8798 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8800 // The operand must be either an l-value or a function designator
8801 if (!op->getType()->isFunctionType()) {
8802 // Use a special diagnostic for loads from property references.
8803 if (isa<PseudoObjectExpr>(op)) {
8804 AddressOfError = AO_Property_Expansion;
8806 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8807 << op->getType() << op->getSourceRange();
8811 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8812 // The operand cannot be a bit-field
8813 AddressOfError = AO_Bit_Field;
8814 } else if (op->getObjectKind() == OK_VectorComponent) {
8815 // The operand cannot be an element of a vector
8816 AddressOfError = AO_Vector_Element;
8817 } else if (dcl) { // C99 6.5.3.2p1
8818 // We have an lvalue with a decl. Make sure the decl is not declared
8819 // with the register storage-class specifier.
8820 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8821 // in C++ it is not error to take address of a register
8822 // variable (c++03 7.1.1P3)
8823 if (vd->getStorageClass() == SC_Register &&
8824 !getLangOpts().CPlusPlus) {
8825 AddressOfError = AO_Register_Variable;
8827 } else if (isa<FunctionTemplateDecl>(dcl)) {
8828 return Context.OverloadTy;
8829 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8830 // Okay: we can take the address of a field.
8831 // Could be a pointer to member, though, if there is an explicit
8832 // scope qualifier for the class.
8833 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8834 DeclContext *Ctx = dcl->getDeclContext();
8835 if (Ctx && Ctx->isRecord()) {
8836 if (dcl->getType()->isReferenceType()) {
8838 diag::err_cannot_form_pointer_to_member_of_reference_type)
8839 << dcl->getDeclName() << dcl->getType();
8843 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8844 Ctx = Ctx->getParent();
8845 return Context.getMemberPointerType(op->getType(),
8846 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8849 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8850 llvm_unreachable("Unknown/unexpected decl type");
8853 if (AddressOfError != AO_No_Error) {
8854 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8858 if (lval == Expr::LV_IncompleteVoidType) {
8859 // Taking the address of a void variable is technically illegal, but we
8860 // allow it in cases which are otherwise valid.
8861 // Example: "extern void x; void* y = &x;".
8862 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8865 // If the operand has type "type", the result has type "pointer to type".
8866 if (op->getType()->isObjCObjectType())
8867 return Context.getObjCObjectPointerType(op->getType());
8868 return Context.getPointerType(op->getType());
8871 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8872 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8873 SourceLocation OpLoc) {
8874 if (Op->isTypeDependent())
8875 return S.Context.DependentTy;
8877 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8878 if (ConvResult.isInvalid())
8880 Op = ConvResult.take();
8881 QualType OpTy = Op->getType();
8884 if (isa<CXXReinterpretCastExpr>(Op)) {
8885 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8886 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8887 Op->getSourceRange());
8890 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8891 // is an incomplete type or void. It would be possible to warn about
8892 // dereferencing a void pointer, but it's completely well-defined, and such a
8893 // warning is unlikely to catch any mistakes.
8894 if (const PointerType *PT = OpTy->getAs<PointerType>())
8895 Result = PT->getPointeeType();
8896 else if (const ObjCObjectPointerType *OPT =
8897 OpTy->getAs<ObjCObjectPointerType>())
8898 Result = OPT->getPointeeType();
8900 ExprResult PR = S.CheckPlaceholderExpr(Op);
8901 if (PR.isInvalid()) return QualType();
8902 if (PR.take() != Op)
8903 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8906 if (Result.isNull()) {
8907 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8908 << OpTy << Op->getSourceRange();
8912 // Dereferences are usually l-values...
8915 // ...except that certain expressions are never l-values in C.
8916 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8922 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8923 tok::TokenKind Kind) {
8924 BinaryOperatorKind Opc;
8926 default: llvm_unreachable("Unknown binop!");
8927 case tok::periodstar: Opc = BO_PtrMemD; break;
8928 case tok::arrowstar: Opc = BO_PtrMemI; break;
8929 case tok::star: Opc = BO_Mul; break;
8930 case tok::slash: Opc = BO_Div; break;
8931 case tok::percent: Opc = BO_Rem; break;
8932 case tok::plus: Opc = BO_Add; break;
8933 case tok::minus: Opc = BO_Sub; break;
8934 case tok::lessless: Opc = BO_Shl; break;
8935 case tok::greatergreater: Opc = BO_Shr; break;
8936 case tok::lessequal: Opc = BO_LE; break;
8937 case tok::less: Opc = BO_LT; break;
8938 case tok::greaterequal: Opc = BO_GE; break;
8939 case tok::greater: Opc = BO_GT; break;
8940 case tok::exclaimequal: Opc = BO_NE; break;
8941 case tok::equalequal: Opc = BO_EQ; break;
8942 case tok::amp: Opc = BO_And; break;
8943 case tok::caret: Opc = BO_Xor; break;
8944 case tok::pipe: Opc = BO_Or; break;
8945 case tok::ampamp: Opc = BO_LAnd; break;
8946 case tok::pipepipe: Opc = BO_LOr; break;
8947 case tok::equal: Opc = BO_Assign; break;
8948 case tok::starequal: Opc = BO_MulAssign; break;
8949 case tok::slashequal: Opc = BO_DivAssign; break;
8950 case tok::percentequal: Opc = BO_RemAssign; break;
8951 case tok::plusequal: Opc = BO_AddAssign; break;
8952 case tok::minusequal: Opc = BO_SubAssign; break;
8953 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8954 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8955 case tok::ampequal: Opc = BO_AndAssign; break;
8956 case tok::caretequal: Opc = BO_XorAssign; break;
8957 case tok::pipeequal: Opc = BO_OrAssign; break;
8958 case tok::comma: Opc = BO_Comma; break;
8963 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8964 tok::TokenKind Kind) {
8965 UnaryOperatorKind Opc;
8967 default: llvm_unreachable("Unknown unary op!");
8968 case tok::plusplus: Opc = UO_PreInc; break;
8969 case tok::minusminus: Opc = UO_PreDec; break;
8970 case tok::amp: Opc = UO_AddrOf; break;
8971 case tok::star: Opc = UO_Deref; break;
8972 case tok::plus: Opc = UO_Plus; break;
8973 case tok::minus: Opc = UO_Minus; break;
8974 case tok::tilde: Opc = UO_Not; break;
8975 case tok::exclaim: Opc = UO_LNot; break;
8976 case tok::kw___real: Opc = UO_Real; break;
8977 case tok::kw___imag: Opc = UO_Imag; break;
8978 case tok::kw___extension__: Opc = UO_Extension; break;
8983 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8984 /// This warning is only emitted for builtin assignment operations. It is also
8985 /// suppressed in the event of macro expansions.
8986 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8987 SourceLocation OpLoc) {
8988 if (!S.ActiveTemplateInstantiations.empty())
8990 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8992 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8993 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8994 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8995 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8996 if (!LHSDeclRef || !RHSDeclRef ||
8997 LHSDeclRef->getLocation().isMacroID() ||
8998 RHSDeclRef->getLocation().isMacroID())
9000 const ValueDecl *LHSDecl =
9001 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9002 const ValueDecl *RHSDecl =
9003 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9004 if (LHSDecl != RHSDecl)
9006 if (LHSDecl->getType().isVolatileQualified())
9008 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9009 if (RefTy->getPointeeType().isVolatileQualified())
9012 S.Diag(OpLoc, diag::warn_self_assignment)
9013 << LHSDeclRef->getType()
9014 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9017 /// Check if a bitwise-& is performed on an Objective-C pointer. This
9018 /// is usually indicative of introspection within the Objective-C pointer.
9019 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9020 SourceLocation OpLoc) {
9021 if (!S.getLangOpts().ObjC1)
9024 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
9025 const Expr *LHS = L.get();
9026 const Expr *RHS = R.get();
9028 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9029 ObjCPointerExpr = LHS;
9032 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9033 ObjCPointerExpr = RHS;
9037 // This warning is deliberately made very specific to reduce false
9038 // positives with logic that uses '&' for hashing. This logic mainly
9039 // looks for code trying to introspect into tagged pointers, which
9040 // code should generally never do.
9041 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9042 unsigned Diag = diag::warn_objc_pointer_masking;
9043 // Determine if we are introspecting the result of performSelectorXXX.
9044 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9045 // Special case messages to -performSelector and friends, which
9046 // can return non-pointer values boxed in a pointer value.
9047 // Some clients may wish to silence warnings in this subcase.
9048 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9049 Selector S = ME->getSelector();
9050 StringRef SelArg0 = S.getNameForSlot(0);
9051 if (SelArg0.startswith("performSelector"))
9052 Diag = diag::warn_objc_pointer_masking_performSelector;
9056 << ObjCPointerExpr->getSourceRange();
9060 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9061 /// operator @p Opc at location @c TokLoc. This routine only supports
9062 /// built-in operations; ActOnBinOp handles overloaded operators.
9063 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9064 BinaryOperatorKind Opc,
9065 Expr *LHSExpr, Expr *RHSExpr) {
9066 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9067 // The syntax only allows initializer lists on the RHS of assignment,
9068 // so we don't need to worry about accepting invalid code for
9069 // non-assignment operators.
9071 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9072 // of x = {} is x = T().
9073 InitializationKind Kind =
9074 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9075 InitializedEntity Entity =
9076 InitializedEntity::InitializeTemporary(LHSExpr->getType());
9077 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9078 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9079 if (Init.isInvalid())
9081 RHSExpr = Init.take();
9084 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
9085 QualType ResultTy; // Result type of the binary operator.
9086 // The following two variables are used for compound assignment operators
9087 QualType CompLHSTy; // Type of LHS after promotions for computation
9088 QualType CompResultTy; // Type of computation result
9089 ExprValueKind VK = VK_RValue;
9090 ExprObjectKind OK = OK_Ordinary;
9094 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9095 if (getLangOpts().CPlusPlus &&
9096 LHS.get()->getObjectKind() != OK_ObjCProperty) {
9097 VK = LHS.get()->getValueKind();
9098 OK = LHS.get()->getObjectKind();
9100 if (!ResultTy.isNull())
9101 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9105 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9110 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9114 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9117 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9120 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9124 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9130 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9134 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9137 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9140 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9144 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9148 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9149 Opc == BO_DivAssign);
9150 CompLHSTy = CompResultTy;
9151 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9152 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9155 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9156 CompLHSTy = CompResultTy;
9157 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9158 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9161 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9162 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9163 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9166 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9167 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9168 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9172 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9173 CompLHSTy = CompResultTy;
9174 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9175 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9180 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9181 CompLHSTy = CompResultTy;
9182 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9183 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9186 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9187 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9188 VK = RHS.get()->getValueKind();
9189 OK = RHS.get()->getObjectKind();
9193 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9196 // Check for array bounds violations for both sides of the BinaryOperator
9197 CheckArrayAccess(LHS.get());
9198 CheckArrayAccess(RHS.get());
9200 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9201 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9202 &Context.Idents.get("object_setClass"),
9203 SourceLocation(), LookupOrdinaryName);
9204 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9205 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9206 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9207 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9208 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9209 FixItHint::CreateInsertion(RHSLocEnd, ")");
9212 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9214 else if (const ObjCIvarRefExpr *OIRE =
9215 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9216 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9218 if (CompResultTy.isNull())
9219 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
9220 ResultTy, VK, OK, OpLoc,
9221 FPFeatures.fp_contract));
9222 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9225 OK = LHS.get()->getObjectKind();
9227 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
9228 ResultTy, VK, OK, CompLHSTy,
9229 CompResultTy, OpLoc,
9230 FPFeatures.fp_contract));
9233 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9234 /// operators are mixed in a way that suggests that the programmer forgot that
9235 /// comparison operators have higher precedence. The most typical example of
9236 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9237 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9238 SourceLocation OpLoc, Expr *LHSExpr,
9240 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9241 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9243 // Check that one of the sides is a comparison operator.
9244 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9245 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9246 if (!isLeftComp && !isRightComp)
9249 // Bitwise operations are sometimes used as eager logical ops.
9250 // Don't diagnose this.
9251 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9252 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9253 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9256 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9258 : SourceRange(OpLoc, RHSExpr->getLocEnd());
9259 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9260 SourceRange ParensRange = isLeftComp ?
9261 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9262 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9264 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9265 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9266 SuggestParentheses(Self, OpLoc,
9267 Self.PDiag(diag::note_precedence_silence) << OpStr,
9268 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9269 SuggestParentheses(Self, OpLoc,
9270 Self.PDiag(diag::note_precedence_bitwise_first)
9271 << BinaryOperator::getOpcodeStr(Opc),
9275 /// \brief It accepts a '&' expr that is inside a '|' one.
9276 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9279 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9280 BinaryOperator *Bop) {
9281 assert(Bop->getOpcode() == BO_And);
9282 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9283 << Bop->getSourceRange() << OpLoc;
9284 SuggestParentheses(Self, Bop->getOperatorLoc(),
9285 Self.PDiag(diag::note_precedence_silence)
9286 << Bop->getOpcodeStr(),
9287 Bop->getSourceRange());
9290 /// \brief It accepts a '&&' expr that is inside a '||' one.
9291 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9294 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9295 BinaryOperator *Bop) {
9296 assert(Bop->getOpcode() == BO_LAnd);
9297 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9298 << Bop->getSourceRange() << OpLoc;
9299 SuggestParentheses(Self, Bop->getOperatorLoc(),
9300 Self.PDiag(diag::note_precedence_silence)
9301 << Bop->getOpcodeStr(),
9302 Bop->getSourceRange());
9305 /// \brief Returns true if the given expression can be evaluated as a constant
9307 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9309 return !E->isValueDependent() &&
9310 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9313 /// \brief Returns true if the given expression can be evaluated as a constant
9315 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9317 return !E->isValueDependent() &&
9318 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9321 /// \brief Look for '&&' in the left hand of a '||' expr.
9322 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9323 Expr *LHSExpr, Expr *RHSExpr) {
9324 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9325 if (Bop->getOpcode() == BO_LAnd) {
9326 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9327 if (EvaluatesAsFalse(S, RHSExpr))
9329 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9330 if (!EvaluatesAsTrue(S, Bop->getLHS()))
9331 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9332 } else if (Bop->getOpcode() == BO_LOr) {
9333 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9334 // If it's "a || b && 1 || c" we didn't warn earlier for
9335 // "a || b && 1", but warn now.
9336 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9337 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9343 /// \brief Look for '&&' in the right hand of a '||' expr.
9344 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9345 Expr *LHSExpr, Expr *RHSExpr) {
9346 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9347 if (Bop->getOpcode() == BO_LAnd) {
9348 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9349 if (EvaluatesAsFalse(S, LHSExpr))
9351 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9352 if (!EvaluatesAsTrue(S, Bop->getRHS()))
9353 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9358 /// \brief Look for '&' in the left or right hand of a '|' expr.
9359 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9361 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9362 if (Bop->getOpcode() == BO_And)
9363 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9367 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9368 Expr *SubExpr, StringRef Shift) {
9369 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9370 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9371 StringRef Op = Bop->getOpcodeStr();
9372 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9373 << Bop->getSourceRange() << OpLoc << Shift << Op;
9374 SuggestParentheses(S, Bop->getOperatorLoc(),
9375 S.PDiag(diag::note_precedence_silence) << Op,
9376 Bop->getSourceRange());
9381 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9382 Expr *LHSExpr, Expr *RHSExpr) {
9383 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9387 FunctionDecl *FD = OCE->getDirectCallee();
9388 if (!FD || !FD->isOverloadedOperator())
9391 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9392 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9395 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9396 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9397 << (Kind == OO_LessLess);
9398 SuggestParentheses(S, OCE->getOperatorLoc(),
9399 S.PDiag(diag::note_precedence_silence)
9400 << (Kind == OO_LessLess ? "<<" : ">>"),
9401 OCE->getSourceRange());
9402 SuggestParentheses(S, OpLoc,
9403 S.PDiag(diag::note_evaluate_comparison_first),
9404 SourceRange(OCE->getArg(1)->getLocStart(),
9405 RHSExpr->getLocEnd()));
9408 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9410 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9411 SourceLocation OpLoc, Expr *LHSExpr,
9413 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9414 if (BinaryOperator::isBitwiseOp(Opc))
9415 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9417 // Diagnose "arg1 & arg2 | arg3"
9418 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9419 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9420 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9423 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9424 // We don't warn for 'assert(a || b && "bad")' since this is safe.
9425 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9426 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9427 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9430 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9432 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9433 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9434 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9437 // Warn on overloaded shift operators and comparisons, such as:
9439 if (BinaryOperator::isComparisonOp(Opc))
9440 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9443 // Binary Operators. 'Tok' is the token for the operator.
9444 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9445 tok::TokenKind Kind,
9446 Expr *LHSExpr, Expr *RHSExpr) {
9447 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9448 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9449 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9451 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9452 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9454 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9457 /// Build an overloaded binary operator expression in the given scope.
9458 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9459 BinaryOperatorKind Opc,
9460 Expr *LHS, Expr *RHS) {
9461 // Find all of the overloaded operators visible from this
9462 // point. We perform both an operator-name lookup from the local
9463 // scope and an argument-dependent lookup based on the types of
9465 UnresolvedSet<16> Functions;
9466 OverloadedOperatorKind OverOp
9467 = BinaryOperator::getOverloadedOperator(Opc);
9468 if (Sc && OverOp != OO_None)
9469 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9470 RHS->getType(), Functions);
9472 // Build the (potentially-overloaded, potentially-dependent)
9473 // binary operation.
9474 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9477 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9478 BinaryOperatorKind Opc,
9479 Expr *LHSExpr, Expr *RHSExpr) {
9480 // We want to end up calling one of checkPseudoObjectAssignment
9481 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9482 // both expressions are overloadable or either is type-dependent),
9483 // or CreateBuiltinBinOp (in any other case). We also want to get
9484 // any placeholder types out of the way.
9486 // Handle pseudo-objects in the LHS.
9487 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9488 // Assignments with a pseudo-object l-value need special analysis.
9489 if (pty->getKind() == BuiltinType::PseudoObject &&
9490 BinaryOperator::isAssignmentOp(Opc))
9491 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9493 // Don't resolve overloads if the other type is overloadable.
9494 if (pty->getKind() == BuiltinType::Overload) {
9495 // We can't actually test that if we still have a placeholder,
9496 // though. Fortunately, none of the exceptions we see in that
9497 // code below are valid when the LHS is an overload set. Note
9498 // that an overload set can be dependently-typed, but it never
9499 // instantiates to having an overloadable type.
9500 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9501 if (resolvedRHS.isInvalid()) return ExprError();
9502 RHSExpr = resolvedRHS.take();
9504 if (RHSExpr->isTypeDependent() ||
9505 RHSExpr->getType()->isOverloadableType())
9506 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9509 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9510 if (LHS.isInvalid()) return ExprError();
9511 LHSExpr = LHS.take();
9514 // Handle pseudo-objects in the RHS.
9515 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9516 // An overload in the RHS can potentially be resolved by the type
9517 // being assigned to.
9518 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9519 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9520 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9522 if (LHSExpr->getType()->isOverloadableType())
9523 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9525 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9528 // Don't resolve overloads if the other type is overloadable.
9529 if (pty->getKind() == BuiltinType::Overload &&
9530 LHSExpr->getType()->isOverloadableType())
9531 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9533 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9534 if (!resolvedRHS.isUsable()) return ExprError();
9535 RHSExpr = resolvedRHS.take();
9538 if (getLangOpts().CPlusPlus) {
9539 // If either expression is type-dependent, always build an
9541 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9542 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9544 // Otherwise, build an overloaded op if either expression has an
9545 // overloadable type.
9546 if (LHSExpr->getType()->isOverloadableType() ||
9547 RHSExpr->getType()->isOverloadableType())
9548 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9551 // Build a built-in binary operation.
9552 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9555 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9556 UnaryOperatorKind Opc,
9558 ExprResult Input = Owned(InputExpr);
9559 ExprValueKind VK = VK_RValue;
9560 ExprObjectKind OK = OK_Ordinary;
9561 QualType resultType;
9567 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9574 resultType = CheckAddressOfOperand(Input, OpLoc);
9577 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9578 if (Input.isInvalid()) return ExprError();
9579 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9584 Input = UsualUnaryConversions(Input.take());
9585 if (Input.isInvalid()) return ExprError();
9586 resultType = Input.get()->getType();
9587 if (resultType->isDependentType())
9589 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9590 resultType->isVectorType())
9592 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9594 resultType->isPointerType())
9597 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9598 << resultType << Input.get()->getSourceRange());
9600 case UO_Not: // bitwise complement
9601 Input = UsualUnaryConversions(Input.take());
9602 if (Input.isInvalid())
9604 resultType = Input.get()->getType();
9605 if (resultType->isDependentType())
9607 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9608 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9609 // C99 does not support '~' for complex conjugation.
9610 Diag(OpLoc, diag::ext_integer_complement_complex)
9611 << resultType << Input.get()->getSourceRange();
9612 else if (resultType->hasIntegerRepresentation())
9614 else if (resultType->isExtVectorType()) {
9615 if (Context.getLangOpts().OpenCL) {
9616 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9617 // on vector float types.
9618 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9619 if (!T->isIntegerType())
9620 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9621 << resultType << Input.get()->getSourceRange());
9625 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9626 << resultType << Input.get()->getSourceRange());
9630 case UO_LNot: // logical negation
9631 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9632 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9633 if (Input.isInvalid()) return ExprError();
9634 resultType = Input.get()->getType();
9636 // Though we still have to promote half FP to float...
9637 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9638 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9639 resultType = Context.FloatTy;
9642 if (resultType->isDependentType())
9644 if (resultType->isScalarType()) {
9645 // C99 6.5.3.3p1: ok, fallthrough;
9646 if (Context.getLangOpts().CPlusPlus) {
9647 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9648 // operand contextually converted to bool.
9649 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9650 ScalarTypeToBooleanCastKind(resultType));
9651 } else if (Context.getLangOpts().OpenCL &&
9652 Context.getLangOpts().OpenCLVersion < 120) {
9653 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9654 // operate on scalar float types.
9655 if (!resultType->isIntegerType())
9656 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9657 << resultType << Input.get()->getSourceRange());
9659 } else if (resultType->isExtVectorType()) {
9660 if (Context.getLangOpts().OpenCL &&
9661 Context.getLangOpts().OpenCLVersion < 120) {
9662 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9663 // operate on vector float types.
9664 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9665 if (!T->isIntegerType())
9666 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9667 << resultType << Input.get()->getSourceRange());
9669 // Vector logical not returns the signed variant of the operand type.
9670 resultType = GetSignedVectorType(resultType);
9673 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9674 << resultType << Input.get()->getSourceRange());
9677 // LNot always has type int. C99 6.5.3.3p5.
9678 // In C++, it's bool. C++ 5.3.1p8
9679 resultType = Context.getLogicalOperationType();
9683 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9684 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9685 // complex l-values to ordinary l-values and all other values to r-values.
9686 if (Input.isInvalid()) return ExprError();
9687 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9688 if (Input.get()->getValueKind() != VK_RValue &&
9689 Input.get()->getObjectKind() == OK_Ordinary)
9690 VK = Input.get()->getValueKind();
9691 } else if (!getLangOpts().CPlusPlus) {
9692 // In C, a volatile scalar is read by __imag. In C++, it is not.
9693 Input = DefaultLvalueConversion(Input.take());
9697 resultType = Input.get()->getType();
9698 VK = Input.get()->getValueKind();
9699 OK = Input.get()->getObjectKind();
9702 if (resultType.isNull() || Input.isInvalid())
9705 // Check for array bounds violations in the operand of the UnaryOperator,
9706 // except for the '*' and '&' operators that have to be handled specially
9707 // by CheckArrayAccess (as there are special cases like &array[arraysize]
9708 // that are explicitly defined as valid by the standard).
9709 if (Opc != UO_AddrOf && Opc != UO_Deref)
9710 CheckArrayAccess(Input.get());
9712 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9716 /// \brief Determine whether the given expression is a qualified member
9717 /// access expression, of a form that could be turned into a pointer to member
9718 /// with the address-of operator.
9719 static bool isQualifiedMemberAccess(Expr *E) {
9720 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9721 if (!DRE->getQualifier())
9724 ValueDecl *VD = DRE->getDecl();
9725 if (!VD->isCXXClassMember())
9728 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9731 return Method->isInstance();
9736 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9737 if (!ULE->getQualifier())
9740 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9741 DEnd = ULE->decls_end();
9743 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9744 if (Method->isInstance())
9747 // Overload set does not contain methods.
9758 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9759 UnaryOperatorKind Opc, Expr *Input) {
9760 // First things first: handle placeholders so that the
9761 // overloaded-operator check considers the right type.
9762 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9763 // Increment and decrement of pseudo-object references.
9764 if (pty->getKind() == BuiltinType::PseudoObject &&
9765 UnaryOperator::isIncrementDecrementOp(Opc))
9766 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9768 // extension is always a builtin operator.
9769 if (Opc == UO_Extension)
9770 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9772 // & gets special logic for several kinds of placeholder.
9773 // The builtin code knows what to do.
9774 if (Opc == UO_AddrOf &&
9775 (pty->getKind() == BuiltinType::Overload ||
9776 pty->getKind() == BuiltinType::UnknownAny ||
9777 pty->getKind() == BuiltinType::BoundMember))
9778 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9780 // Anything else needs to be handled now.
9781 ExprResult Result = CheckPlaceholderExpr(Input);
9782 if (Result.isInvalid()) return ExprError();
9783 Input = Result.take();
9786 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9787 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9788 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9789 // Find all of the overloaded operators visible from this
9790 // point. We perform both an operator-name lookup from the local
9791 // scope and an argument-dependent lookup based on the types of
9793 UnresolvedSet<16> Functions;
9794 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9795 if (S && OverOp != OO_None)
9796 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9799 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9802 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9805 // Unary Operators. 'Tok' is the token for the operator.
9806 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9807 tok::TokenKind Op, Expr *Input) {
9808 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9811 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9812 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9813 LabelDecl *TheDecl) {
9814 TheDecl->markUsed(Context);
9815 // Create the AST node. The address of a label always has type 'void*'.
9816 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9817 Context.getPointerType(Context.VoidTy)));
9820 /// Given the last statement in a statement-expression, check whether
9821 /// the result is a producing expression (like a call to an
9822 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9823 /// release out of the full-expression. Otherwise, return null.
9825 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9826 // Should always be wrapped with one of these.
9827 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9828 if (!cleanups) return 0;
9830 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9831 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9834 // Splice out the cast. This shouldn't modify any interesting
9835 // features of the statement.
9836 Expr *producer = cast->getSubExpr();
9837 assert(producer->getType() == cast->getType());
9838 assert(producer->getValueKind() == cast->getValueKind());
9839 cleanups->setSubExpr(producer);
9843 void Sema::ActOnStartStmtExpr() {
9844 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9847 void Sema::ActOnStmtExprError() {
9848 // Note that function is also called by TreeTransform when leaving a
9849 // StmtExpr scope without rebuilding anything.
9851 DiscardCleanupsInEvaluationContext();
9852 PopExpressionEvaluationContext();
9856 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9857 SourceLocation RPLoc) { // "({..})"
9858 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9859 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9861 if (hasAnyUnrecoverableErrorsInThisFunction())
9862 DiscardCleanupsInEvaluationContext();
9863 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9864 PopExpressionEvaluationContext();
9867 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9869 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9871 // FIXME: there are a variety of strange constraints to enforce here, for
9872 // example, it is not possible to goto into a stmt expression apparently.
9873 // More semantic analysis is needed.
9875 // If there are sub stmts in the compound stmt, take the type of the last one
9876 // as the type of the stmtexpr.
9877 QualType Ty = Context.VoidTy;
9878 bool StmtExprMayBindToTemp = false;
9879 if (!Compound->body_empty()) {
9880 Stmt *LastStmt = Compound->body_back();
9881 LabelStmt *LastLabelStmt = 0;
9882 // If LastStmt is a label, skip down through into the body.
9883 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9884 LastLabelStmt = Label;
9885 LastStmt = Label->getSubStmt();
9888 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9889 // Do function/array conversion on the last expression, but not
9890 // lvalue-to-rvalue. However, initialize an unqualified type.
9891 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9892 if (LastExpr.isInvalid())
9894 Ty = LastExpr.get()->getType().getUnqualifiedType();
9896 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9897 // In ARC, if the final expression ends in a consume, splice
9898 // the consume out and bind it later. In the alternate case
9899 // (when dealing with a retainable type), the result
9900 // initialization will create a produce. In both cases the
9901 // result will be +1, and we'll need to balance that out with
9903 if (Expr *rebuiltLastStmt
9904 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9905 LastExpr = rebuiltLastStmt;
9907 LastExpr = PerformCopyInitialization(
9908 InitializedEntity::InitializeResult(LPLoc,
9915 if (LastExpr.isInvalid())
9917 if (LastExpr.get() != 0) {
9919 Compound->setLastStmt(LastExpr.take());
9921 LastLabelStmt->setSubStmt(LastExpr.take());
9922 StmtExprMayBindToTemp = true;
9928 // FIXME: Check that expression type is complete/non-abstract; statement
9929 // expressions are not lvalues.
9930 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9931 if (StmtExprMayBindToTemp)
9932 return MaybeBindToTemporary(ResStmtExpr);
9933 return Owned(ResStmtExpr);
9936 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9937 TypeSourceInfo *TInfo,
9938 OffsetOfComponent *CompPtr,
9939 unsigned NumComponents,
9940 SourceLocation RParenLoc) {
9941 QualType ArgTy = TInfo->getType();
9942 bool Dependent = ArgTy->isDependentType();
9943 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9945 // We must have at least one component that refers to the type, and the first
9946 // one is known to be a field designator. Verify that the ArgTy represents
9947 // a struct/union/class.
9948 if (!Dependent && !ArgTy->isRecordType())
9949 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9950 << ArgTy << TypeRange);
9952 // Type must be complete per C99 7.17p3 because a declaring a variable
9953 // with an incomplete type would be ill-formed.
9955 && RequireCompleteType(BuiltinLoc, ArgTy,
9956 diag::err_offsetof_incomplete_type, TypeRange))
9959 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9960 // GCC extension, diagnose them.
9961 // FIXME: This diagnostic isn't actually visible because the location is in
9963 if (NumComponents != 1)
9964 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9965 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9967 bool DidWarnAboutNonPOD = false;
9968 QualType CurrentType = ArgTy;
9969 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9970 SmallVector<OffsetOfNode, 4> Comps;
9971 SmallVector<Expr*, 4> Exprs;
9972 for (unsigned i = 0; i != NumComponents; ++i) {
9973 const OffsetOfComponent &OC = CompPtr[i];
9974 if (OC.isBrackets) {
9975 // Offset of an array sub-field. TODO: Should we allow vector elements?
9976 if (!CurrentType->isDependentType()) {
9977 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9979 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9981 CurrentType = AT->getElementType();
9983 CurrentType = Context.DependentTy;
9985 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9986 if (IdxRval.isInvalid())
9988 Expr *Idx = IdxRval.take();
9990 // The expression must be an integral expression.
9991 // FIXME: An integral constant expression?
9992 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9993 !Idx->getType()->isIntegerType())
9994 return ExprError(Diag(Idx->getLocStart(),
9995 diag::err_typecheck_subscript_not_integer)
9996 << Idx->getSourceRange());
9998 // Record this array index.
9999 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10000 Exprs.push_back(Idx);
10004 // Offset of a field.
10005 if (CurrentType->isDependentType()) {
10006 // We have the offset of a field, but we can't look into the dependent
10007 // type. Just record the identifier of the field.
10008 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10009 CurrentType = Context.DependentTy;
10013 // We need to have a complete type to look into.
10014 if (RequireCompleteType(OC.LocStart, CurrentType,
10015 diag::err_offsetof_incomplete_type))
10016 return ExprError();
10018 // Look for the designated field.
10019 const RecordType *RC = CurrentType->getAs<RecordType>();
10021 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10023 RecordDecl *RD = RC->getDecl();
10025 // C++ [lib.support.types]p5:
10026 // The macro offsetof accepts a restricted set of type arguments in this
10027 // International Standard. type shall be a POD structure or a POD union
10029 // C++11 [support.types]p4:
10030 // If type is not a standard-layout class (Clause 9), the results are
10032 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10033 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10035 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10036 : diag::warn_offsetof_non_pod_type;
10038 if (!IsSafe && !DidWarnAboutNonPOD &&
10039 DiagRuntimeBehavior(BuiltinLoc, 0,
10041 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10043 DidWarnAboutNonPOD = true;
10046 // Look for the field.
10047 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10048 LookupQualifiedName(R, RD);
10049 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10050 IndirectFieldDecl *IndirectMemberDecl = 0;
10052 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10053 MemberDecl = IndirectMemberDecl->getAnonField();
10057 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10058 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10062 // (If the specified member is a bit-field, the behavior is undefined.)
10064 // We diagnose this as an error.
10065 if (MemberDecl->isBitField()) {
10066 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10067 << MemberDecl->getDeclName()
10068 << SourceRange(BuiltinLoc, RParenLoc);
10069 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10070 return ExprError();
10073 RecordDecl *Parent = MemberDecl->getParent();
10074 if (IndirectMemberDecl)
10075 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10077 // If the member was found in a base class, introduce OffsetOfNodes for
10078 // the base class indirections.
10079 CXXBasePaths Paths;
10080 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10081 if (Paths.getDetectedVirtual()) {
10082 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10083 << MemberDecl->getDeclName()
10084 << SourceRange(BuiltinLoc, RParenLoc);
10085 return ExprError();
10088 CXXBasePath &Path = Paths.front();
10089 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10091 Comps.push_back(OffsetOfNode(B->Base));
10094 if (IndirectMemberDecl) {
10095 for (IndirectFieldDecl::chain_iterator FI =
10096 IndirectMemberDecl->chain_begin(),
10097 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
10098 assert(isa<FieldDecl>(*FI));
10099 Comps.push_back(OffsetOfNode(OC.LocStart,
10100 cast<FieldDecl>(*FI), OC.LocEnd));
10103 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10105 CurrentType = MemberDecl->getType().getNonReferenceType();
10108 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
10109 TInfo, Comps, Exprs, RParenLoc));
10112 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10113 SourceLocation BuiltinLoc,
10114 SourceLocation TypeLoc,
10115 ParsedType ParsedArgTy,
10116 OffsetOfComponent *CompPtr,
10117 unsigned NumComponents,
10118 SourceLocation RParenLoc) {
10120 TypeSourceInfo *ArgTInfo;
10121 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10122 if (ArgTy.isNull())
10123 return ExprError();
10126 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10128 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10133 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10135 Expr *LHSExpr, Expr *RHSExpr,
10136 SourceLocation RPLoc) {
10137 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10139 ExprValueKind VK = VK_RValue;
10140 ExprObjectKind OK = OK_Ordinary;
10142 bool ValueDependent = false;
10143 bool CondIsTrue = false;
10144 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10145 resType = Context.DependentTy;
10146 ValueDependent = true;
10148 // The conditional expression is required to be a constant expression.
10149 llvm::APSInt condEval(32);
10151 = VerifyIntegerConstantExpression(CondExpr, &condEval,
10152 diag::err_typecheck_choose_expr_requires_constant, false);
10153 if (CondICE.isInvalid())
10154 return ExprError();
10155 CondExpr = CondICE.take();
10156 CondIsTrue = condEval.getZExtValue();
10158 // If the condition is > zero, then the AST type is the same as the LSHExpr.
10159 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10161 resType = ActiveExpr->getType();
10162 ValueDependent = ActiveExpr->isValueDependent();
10163 VK = ActiveExpr->getValueKind();
10164 OK = ActiveExpr->getObjectKind();
10167 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
10168 resType, VK, OK, RPLoc, CondIsTrue,
10169 resType->isDependentType(),
10173 //===----------------------------------------------------------------------===//
10174 // Clang Extensions.
10175 //===----------------------------------------------------------------------===//
10177 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10178 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10179 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10181 if (LangOpts.CPlusPlus) {
10182 Decl *ManglingContextDecl;
10183 if (MangleNumberingContext *MCtx =
10184 getCurrentMangleNumberContext(Block->getDeclContext(),
10185 ManglingContextDecl)) {
10186 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10187 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10191 PushBlockScope(CurScope, Block);
10192 CurContext->addDecl(Block);
10194 PushDeclContext(CurScope, Block);
10196 CurContext = Block;
10198 getCurBlock()->HasImplicitReturnType = true;
10200 // Enter a new evaluation context to insulate the block from any
10201 // cleanups from the enclosing full-expression.
10202 PushExpressionEvaluationContext(PotentiallyEvaluated);
10205 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10207 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
10208 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10209 BlockScopeInfo *CurBlock = getCurBlock();
10211 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10212 QualType T = Sig->getType();
10214 // FIXME: We should allow unexpanded parameter packs here, but that would,
10215 // in turn, make the block expression contain unexpanded parameter packs.
10216 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10217 // Drop the parameters.
10218 FunctionProtoType::ExtProtoInfo EPI;
10219 EPI.HasTrailingReturn = false;
10220 EPI.TypeQuals |= DeclSpec::TQ_const;
10221 T = Context.getFunctionType(Context.DependentTy, None, EPI);
10222 Sig = Context.getTrivialTypeSourceInfo(T);
10225 // GetTypeForDeclarator always produces a function type for a block
10226 // literal signature. Furthermore, it is always a FunctionProtoType
10227 // unless the function was written with a typedef.
10228 assert(T->isFunctionType() &&
10229 "GetTypeForDeclarator made a non-function block signature");
10231 // Look for an explicit signature in that function type.
10232 FunctionProtoTypeLoc ExplicitSignature;
10234 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10235 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10237 // Check whether that explicit signature was synthesized by
10238 // GetTypeForDeclarator. If so, don't save that as part of the
10239 // written signature.
10240 if (ExplicitSignature.getLocalRangeBegin() ==
10241 ExplicitSignature.getLocalRangeEnd()) {
10242 // This would be much cheaper if we stored TypeLocs instead of
10243 // TypeSourceInfos.
10244 TypeLoc Result = ExplicitSignature.getResultLoc();
10245 unsigned Size = Result.getFullDataSize();
10246 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10247 Sig->getTypeLoc().initializeFullCopy(Result, Size);
10249 ExplicitSignature = FunctionProtoTypeLoc();
10253 CurBlock->TheDecl->setSignatureAsWritten(Sig);
10254 CurBlock->FunctionType = T;
10256 const FunctionType *Fn = T->getAs<FunctionType>();
10257 QualType RetTy = Fn->getResultType();
10259 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10261 CurBlock->TheDecl->setIsVariadic(isVariadic);
10263 // Context.DependentTy is used as a placeholder for a missing block
10264 // return type. TODO: what should we do with declarators like:
10266 // If the answer is "apply template argument deduction"....
10267 if (RetTy != Context.DependentTy) {
10268 CurBlock->ReturnType = RetTy;
10269 CurBlock->TheDecl->setBlockMissingReturnType(false);
10270 CurBlock->HasImplicitReturnType = false;
10273 // Push block parameters from the declarator if we had them.
10274 SmallVector<ParmVarDecl*, 8> Params;
10275 if (ExplicitSignature) {
10276 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
10277 ParmVarDecl *Param = ExplicitSignature.getArg(I);
10278 if (Param->getIdentifier() == 0 &&
10279 !Param->isImplicit() &&
10280 !Param->isInvalidDecl() &&
10281 !getLangOpts().CPlusPlus)
10282 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10283 Params.push_back(Param);
10286 // Fake up parameter variables if we have a typedef, like
10287 // ^ fntype { ... }
10288 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10289 for (FunctionProtoType::arg_type_iterator
10290 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
10291 ParmVarDecl *Param =
10292 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
10293 ParamInfo.getLocStart(),
10295 Params.push_back(Param);
10299 // Set the parameters on the block decl.
10300 if (!Params.empty()) {
10301 CurBlock->TheDecl->setParams(Params);
10302 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10303 CurBlock->TheDecl->param_end(),
10304 /*CheckParameterNames=*/false);
10307 // Finally we can process decl attributes.
10308 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10310 // Put the parameter variables in scope.
10311 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
10312 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
10313 (*AI)->setOwningFunction(CurBlock->TheDecl);
10315 // If this has an identifier, add it to the scope stack.
10316 if ((*AI)->getIdentifier()) {
10317 CheckShadow(CurBlock->TheScope, *AI);
10319 PushOnScopeChains(*AI, CurBlock->TheScope);
10324 /// ActOnBlockError - If there is an error parsing a block, this callback
10325 /// is invoked to pop the information about the block from the action impl.
10326 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10327 // Leave the expression-evaluation context.
10328 DiscardCleanupsInEvaluationContext();
10329 PopExpressionEvaluationContext();
10331 // Pop off CurBlock, handle nested blocks.
10333 PopFunctionScopeInfo();
10336 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10337 /// literal was successfully completed. ^(int x){...}
10338 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10339 Stmt *Body, Scope *CurScope) {
10340 // If blocks are disabled, emit an error.
10341 if (!LangOpts.Blocks)
10342 Diag(CaretLoc, diag::err_blocks_disable);
10344 // Leave the expression-evaluation context.
10345 if (hasAnyUnrecoverableErrorsInThisFunction())
10346 DiscardCleanupsInEvaluationContext();
10347 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10348 PopExpressionEvaluationContext();
10350 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10352 if (BSI->HasImplicitReturnType)
10353 deduceClosureReturnType(*BSI);
10357 QualType RetTy = Context.VoidTy;
10358 if (!BSI->ReturnType.isNull())
10359 RetTy = BSI->ReturnType;
10361 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
10364 // Set the captured variables on the block.
10365 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10366 SmallVector<BlockDecl::Capture, 4> Captures;
10367 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10368 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10369 if (Cap.isThisCapture())
10371 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10372 Cap.isNested(), Cap.getInitExpr());
10373 Captures.push_back(NewCap);
10375 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10376 BSI->CXXThisCaptureIndex != 0);
10378 // If the user wrote a function type in some form, try to use that.
10379 if (!BSI->FunctionType.isNull()) {
10380 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10382 FunctionType::ExtInfo Ext = FTy->getExtInfo();
10383 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10385 // Turn protoless block types into nullary block types.
10386 if (isa<FunctionNoProtoType>(FTy)) {
10387 FunctionProtoType::ExtProtoInfo EPI;
10389 BlockTy = Context.getFunctionType(RetTy, None, EPI);
10391 // Otherwise, if we don't need to change anything about the function type,
10392 // preserve its sugar structure.
10393 } else if (FTy->getResultType() == RetTy &&
10394 (!NoReturn || FTy->getNoReturnAttr())) {
10395 BlockTy = BSI->FunctionType;
10397 // Otherwise, make the minimal modifications to the function type.
10399 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10400 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10401 EPI.TypeQuals = 0; // FIXME: silently?
10403 BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI);
10406 // If we don't have a function type, just build one from nothing.
10408 FunctionProtoType::ExtProtoInfo EPI;
10409 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10410 BlockTy = Context.getFunctionType(RetTy, None, EPI);
10413 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10414 BSI->TheDecl->param_end());
10415 BlockTy = Context.getBlockPointerType(BlockTy);
10417 // If needed, diagnose invalid gotos and switches in the block.
10418 if (getCurFunction()->NeedsScopeChecking() &&
10419 !hasAnyUnrecoverableErrorsInThisFunction() &&
10420 !PP.isCodeCompletionEnabled())
10421 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10423 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10425 // Try to apply the named return value optimization. We have to check again
10426 // if we can do this, though, because blocks keep return statements around
10427 // to deduce an implicit return type.
10428 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10429 !BSI->TheDecl->isDependentContext())
10430 computeNRVO(Body, getCurBlock());
10432 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10433 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10434 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10436 // If the block isn't obviously global, i.e. it captures anything at
10437 // all, then we need to do a few things in the surrounding context:
10438 if (Result->getBlockDecl()->hasCaptures()) {
10439 // First, this expression has a new cleanup object.
10440 ExprCleanupObjects.push_back(Result->getBlockDecl());
10441 ExprNeedsCleanups = true;
10443 // It also gets a branch-protected scope if any of the captured
10444 // variables needs destruction.
10445 for (BlockDecl::capture_const_iterator
10446 ci = Result->getBlockDecl()->capture_begin(),
10447 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10448 const VarDecl *var = ci->getVariable();
10449 if (var->getType().isDestructedType() != QualType::DK_none) {
10450 getCurFunction()->setHasBranchProtectedScope();
10456 return Owned(Result);
10459 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10460 Expr *E, ParsedType Ty,
10461 SourceLocation RPLoc) {
10462 TypeSourceInfo *TInfo;
10463 GetTypeFromParser(Ty, &TInfo);
10464 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10467 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10468 Expr *E, TypeSourceInfo *TInfo,
10469 SourceLocation RPLoc) {
10470 Expr *OrigExpr = E;
10472 // Get the va_list type
10473 QualType VaListType = Context.getBuiltinVaListType();
10474 if (VaListType->isArrayType()) {
10475 // Deal with implicit array decay; for example, on x86-64,
10476 // va_list is an array, but it's supposed to decay to
10477 // a pointer for va_arg.
10478 VaListType = Context.getArrayDecayedType(VaListType);
10479 // Make sure the input expression also decays appropriately.
10480 ExprResult Result = UsualUnaryConversions(E);
10481 if (Result.isInvalid())
10482 return ExprError();
10484 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10485 // If va_list is a record type and we are compiling in C++ mode,
10486 // check the argument using reference binding.
10487 InitializedEntity Entity
10488 = InitializedEntity::InitializeParameter(Context,
10489 Context.getLValueReferenceType(VaListType), false);
10490 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10491 if (Init.isInvalid())
10492 return ExprError();
10493 E = Init.takeAs<Expr>();
10495 // Otherwise, the va_list argument must be an l-value because
10496 // it is modified by va_arg.
10497 if (!E->isTypeDependent() &&
10498 CheckForModifiableLvalue(E, BuiltinLoc, *this))
10499 return ExprError();
10502 if (!E->isTypeDependent() &&
10503 !Context.hasSameType(VaListType, E->getType())) {
10504 return ExprError(Diag(E->getLocStart(),
10505 diag::err_first_argument_to_va_arg_not_of_type_va_list)
10506 << OrigExpr->getType() << E->getSourceRange());
10509 if (!TInfo->getType()->isDependentType()) {
10510 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10511 diag::err_second_parameter_to_va_arg_incomplete,
10512 TInfo->getTypeLoc()))
10513 return ExprError();
10515 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10517 diag::err_second_parameter_to_va_arg_abstract,
10518 TInfo->getTypeLoc()))
10519 return ExprError();
10521 if (!TInfo->getType().isPODType(Context)) {
10522 Diag(TInfo->getTypeLoc().getBeginLoc(),
10523 TInfo->getType()->isObjCLifetimeType()
10524 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10525 : diag::warn_second_parameter_to_va_arg_not_pod)
10526 << TInfo->getType()
10527 << TInfo->getTypeLoc().getSourceRange();
10530 // Check for va_arg where arguments of the given type will be promoted
10531 // (i.e. this va_arg is guaranteed to have undefined behavior).
10532 QualType PromoteType;
10533 if (TInfo->getType()->isPromotableIntegerType()) {
10534 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10535 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10536 PromoteType = QualType();
10538 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10539 PromoteType = Context.DoubleTy;
10540 if (!PromoteType.isNull())
10541 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10542 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10543 << TInfo->getType()
10545 << TInfo->getTypeLoc().getSourceRange());
10548 QualType T = TInfo->getType().getNonLValueExprType(Context);
10549 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10552 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10553 // The type of __null will be int or long, depending on the size of
10554 // pointers on the target.
10556 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10557 if (pw == Context.getTargetInfo().getIntWidth())
10558 Ty = Context.IntTy;
10559 else if (pw == Context.getTargetInfo().getLongWidth())
10560 Ty = Context.LongTy;
10561 else if (pw == Context.getTargetInfo().getLongLongWidth())
10562 Ty = Context.LongLongTy;
10564 llvm_unreachable("I don't know size of pointer!");
10567 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10570 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
10571 Expr *SrcExpr, FixItHint &Hint,
10572 bool &IsNSString) {
10573 if (!SemaRef.getLangOpts().ObjC1)
10576 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10580 // Check if the destination is of type 'id'.
10581 if (!PT->isObjCIdType()) {
10582 // Check if the destination is the 'NSString' interface.
10583 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10584 if (!ID || !ID->getIdentifier()->isStr("NSString"))
10589 // Ignore any parens, implicit casts (should only be
10590 // array-to-pointer decays), and not-so-opaque values. The last is
10591 // important for making this trigger for property assignments.
10592 SrcExpr = SrcExpr->IgnoreParenImpCasts();
10593 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10594 if (OV->getSourceExpr())
10595 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10597 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10598 if (!SL || !SL->isAscii())
10601 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10604 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10605 SourceLocation Loc,
10606 QualType DstType, QualType SrcType,
10607 Expr *SrcExpr, AssignmentAction Action,
10608 bool *Complained) {
10610 *Complained = false;
10612 // Decode the result (notice that AST's are still created for extensions).
10613 bool CheckInferredResultType = false;
10614 bool isInvalid = false;
10615 unsigned DiagKind = 0;
10617 ConversionFixItGenerator ConvHints;
10618 bool MayHaveConvFixit = false;
10619 bool MayHaveFunctionDiff = false;
10620 bool IsNSString = false;
10624 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10628 DiagKind = diag::ext_typecheck_convert_pointer_int;
10629 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10630 MayHaveConvFixit = true;
10633 DiagKind = diag::ext_typecheck_convert_int_pointer;
10634 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10635 MayHaveConvFixit = true;
10637 case IncompatiblePointer:
10638 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString);
10640 (Action == AA_Passing_CFAudited ?
10641 diag::err_arc_typecheck_convert_incompatible_pointer :
10642 diag::ext_typecheck_convert_incompatible_pointer);
10643 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10644 SrcType->isObjCObjectPointerType();
10645 if (Hint.isNull() && !CheckInferredResultType) {
10646 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10648 else if (CheckInferredResultType) {
10649 SrcType = SrcType.getUnqualifiedType();
10650 DstType = DstType.getUnqualifiedType();
10652 else if (IsNSString && !Hint.isNull())
10653 DiagKind = diag::warn_missing_atsign_prefix;
10654 MayHaveConvFixit = true;
10656 case IncompatiblePointerSign:
10657 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10659 case FunctionVoidPointer:
10660 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10662 case IncompatiblePointerDiscardsQualifiers: {
10663 // Perform array-to-pointer decay if necessary.
10664 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10666 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10667 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10668 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10669 DiagKind = diag::err_typecheck_incompatible_address_space;
10673 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10674 DiagKind = diag::err_typecheck_incompatible_ownership;
10678 llvm_unreachable("unknown error case for discarding qualifiers!");
10681 case CompatiblePointerDiscardsQualifiers:
10682 // If the qualifiers lost were because we were applying the
10683 // (deprecated) C++ conversion from a string literal to a char*
10684 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
10685 // Ideally, this check would be performed in
10686 // checkPointerTypesForAssignment. However, that would require a
10687 // bit of refactoring (so that the second argument is an
10688 // expression, rather than a type), which should be done as part
10689 // of a larger effort to fix checkPointerTypesForAssignment for
10691 if (getLangOpts().CPlusPlus &&
10692 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10694 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10696 case IncompatibleNestedPointerQualifiers:
10697 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10699 case IntToBlockPointer:
10700 DiagKind = diag::err_int_to_block_pointer;
10702 case IncompatibleBlockPointer:
10703 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10705 case IncompatibleObjCQualifiedId:
10706 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10707 // it can give a more specific diagnostic.
10708 DiagKind = diag::warn_incompatible_qualified_id;
10710 case IncompatibleVectors:
10711 DiagKind = diag::warn_incompatible_vectors;
10713 case IncompatibleObjCWeakRef:
10714 DiagKind = diag::err_arc_weak_unavailable_assign;
10717 DiagKind = diag::err_typecheck_convert_incompatible;
10718 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10719 MayHaveConvFixit = true;
10721 MayHaveFunctionDiff = true;
10725 QualType FirstType, SecondType;
10728 case AA_Initializing:
10729 // The destination type comes first.
10730 FirstType = DstType;
10731 SecondType = SrcType;
10736 case AA_Passing_CFAudited:
10737 case AA_Converting:
10740 // The source type comes first.
10741 FirstType = SrcType;
10742 SecondType = DstType;
10746 PartialDiagnostic FDiag = PDiag(DiagKind);
10747 if (Action == AA_Passing_CFAudited)
10748 FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10750 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10752 // If we can fix the conversion, suggest the FixIts.
10753 assert(ConvHints.isNull() || Hint.isNull());
10754 if (!ConvHints.isNull()) {
10755 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10756 HE = ConvHints.Hints.end(); HI != HE; ++HI)
10761 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10763 if (MayHaveFunctionDiff)
10764 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10768 if (SecondType == Context.OverloadTy)
10769 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10772 if (CheckInferredResultType)
10773 EmitRelatedResultTypeNote(SrcExpr);
10775 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10776 EmitRelatedResultTypeNoteForReturn(DstType);
10779 *Complained = true;
10783 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10784 llvm::APSInt *Result) {
10785 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10787 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10788 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10792 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10795 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10796 llvm::APSInt *Result,
10799 class IDDiagnoser : public VerifyICEDiagnoser {
10803 IDDiagnoser(unsigned DiagID)
10804 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10806 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10807 S.Diag(Loc, DiagID) << SR;
10809 } Diagnoser(DiagID);
10811 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10814 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10816 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10820 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10821 VerifyICEDiagnoser &Diagnoser,
10823 SourceLocation DiagLoc = E->getLocStart();
10825 if (getLangOpts().CPlusPlus11) {
10826 // C++11 [expr.const]p5:
10827 // If an expression of literal class type is used in a context where an
10828 // integral constant expression is required, then that class type shall
10829 // have a single non-explicit conversion function to an integral or
10830 // unscoped enumeration type
10831 ExprResult Converted;
10832 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10834 CXX11ConvertDiagnoser(bool Silent)
10835 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10838 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10840 return S.Diag(Loc, diag::err_ice_not_integral) << T;
10843 virtual SemaDiagnosticBuilder diagnoseIncomplete(
10844 Sema &S, SourceLocation Loc, QualType T) {
10845 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10848 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
10849 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10850 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10853 virtual SemaDiagnosticBuilder noteExplicitConv(
10854 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10855 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10856 << ConvTy->isEnumeralType() << ConvTy;
10859 virtual SemaDiagnosticBuilder diagnoseAmbiguous(
10860 Sema &S, SourceLocation Loc, QualType T) {
10861 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10864 virtual SemaDiagnosticBuilder noteAmbiguous(
10865 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10866 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10867 << ConvTy->isEnumeralType() << ConvTy;
10870 virtual SemaDiagnosticBuilder diagnoseConversion(
10871 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10872 llvm_unreachable("conversion functions are permitted");
10874 } ConvertDiagnoser(Diagnoser.Suppress);
10876 Converted = PerformContextualImplicitConversion(DiagLoc, E,
10878 if (Converted.isInvalid())
10880 E = Converted.take();
10881 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10882 return ExprError();
10883 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10884 // An ICE must be of integral or unscoped enumeration type.
10885 if (!Diagnoser.Suppress)
10886 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10887 return ExprError();
10890 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10891 // in the non-ICE case.
10892 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10894 *Result = E->EvaluateKnownConstInt(Context);
10898 Expr::EvalResult EvalResult;
10899 SmallVector<PartialDiagnosticAt, 8> Notes;
10900 EvalResult.Diag = &Notes;
10902 // Try to evaluate the expression, and produce diagnostics explaining why it's
10903 // not a constant expression as a side-effect.
10904 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10905 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10907 // In C++11, we can rely on diagnostics being produced for any expression
10908 // which is not a constant expression. If no diagnostics were produced, then
10909 // this is a constant expression.
10910 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10912 *Result = EvalResult.Val.getInt();
10916 // If our only note is the usual "invalid subexpression" note, just point
10917 // the caret at its location rather than producing an essentially
10919 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10920 diag::note_invalid_subexpr_in_const_expr) {
10921 DiagLoc = Notes[0].first;
10925 if (!Folded || !AllowFold) {
10926 if (!Diagnoser.Suppress) {
10927 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10928 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10929 Diag(Notes[I].first, Notes[I].second);
10932 return ExprError();
10935 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10936 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10937 Diag(Notes[I].first, Notes[I].second);
10940 *Result = EvalResult.Val.getInt();
10945 // Handle the case where we conclude a expression which we speculatively
10946 // considered to be unevaluated is actually evaluated.
10947 class TransformToPE : public TreeTransform<TransformToPE> {
10948 typedef TreeTransform<TransformToPE> BaseTransform;
10951 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10953 // Make sure we redo semantic analysis
10954 bool AlwaysRebuild() { return true; }
10956 // Make sure we handle LabelStmts correctly.
10957 // FIXME: This does the right thing, but maybe we need a more general
10958 // fix to TreeTransform?
10959 StmtResult TransformLabelStmt(LabelStmt *S) {
10960 S->getDecl()->setStmt(0);
10961 return BaseTransform::TransformLabelStmt(S);
10964 // We need to special-case DeclRefExprs referring to FieldDecls which
10965 // are not part of a member pointer formation; normal TreeTransforming
10966 // doesn't catch this case because of the way we represent them in the AST.
10967 // FIXME: This is a bit ugly; is it really the best way to handle this
10970 // Error on DeclRefExprs referring to FieldDecls.
10971 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10972 if (isa<FieldDecl>(E->getDecl()) &&
10973 !SemaRef.isUnevaluatedContext())
10974 return SemaRef.Diag(E->getLocation(),
10975 diag::err_invalid_non_static_member_use)
10976 << E->getDecl() << E->getSourceRange();
10978 return BaseTransform::TransformDeclRefExpr(E);
10981 // Exception: filter out member pointer formation
10982 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10983 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10986 return BaseTransform::TransformUnaryOperator(E);
10989 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10990 // Lambdas never need to be transformed.
10996 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10997 assert(isUnevaluatedContext() &&
10998 "Should only transform unevaluated expressions");
10999 ExprEvalContexts.back().Context =
11000 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11001 if (isUnevaluatedContext())
11003 return TransformToPE(*this).TransformExpr(E);
11007 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11008 Decl *LambdaContextDecl,
11010 ExprEvalContexts.push_back(
11011 ExpressionEvaluationContextRecord(NewContext,
11012 ExprCleanupObjects.size(),
11016 ExprNeedsCleanups = false;
11017 if (!MaybeODRUseExprs.empty())
11018 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11022 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11023 ReuseLambdaContextDecl_t,
11025 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11026 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11029 void Sema::PopExpressionEvaluationContext() {
11030 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11032 if (!Rec.Lambdas.empty()) {
11033 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11035 if (Rec.isUnevaluated()) {
11036 // C++11 [expr.prim.lambda]p2:
11037 // A lambda-expression shall not appear in an unevaluated operand
11039 D = diag::err_lambda_unevaluated_operand;
11041 // C++1y [expr.const]p2:
11042 // A conditional-expression e is a core constant expression unless the
11043 // evaluation of e, following the rules of the abstract machine, would
11044 // evaluate [...] a lambda-expression.
11045 D = diag::err_lambda_in_constant_expression;
11047 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11048 Diag(Rec.Lambdas[I]->getLocStart(), D);
11050 // Mark the capture expressions odr-used. This was deferred
11051 // during lambda expression creation.
11052 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11053 LambdaExpr *Lambda = Rec.Lambdas[I];
11054 for (LambdaExpr::capture_init_iterator
11055 C = Lambda->capture_init_begin(),
11056 CEnd = Lambda->capture_init_end();
11058 MarkDeclarationsReferencedInExpr(*C);
11064 // When are coming out of an unevaluated context, clear out any
11065 // temporaries that we may have created as part of the evaluation of
11066 // the expression in that context: they aren't relevant because they
11067 // will never be constructed.
11068 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11069 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11070 ExprCleanupObjects.end());
11071 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11072 CleanupVarDeclMarking();
11073 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11074 // Otherwise, merge the contexts together.
11076 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11077 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11078 Rec.SavedMaybeODRUseExprs.end());
11081 // Pop the current expression evaluation context off the stack.
11082 ExprEvalContexts.pop_back();
11085 void Sema::DiscardCleanupsInEvaluationContext() {
11086 ExprCleanupObjects.erase(
11087 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11088 ExprCleanupObjects.end());
11089 ExprNeedsCleanups = false;
11090 MaybeODRUseExprs.clear();
11093 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11094 if (!E->getType()->isVariablyModifiedType())
11096 return TransformToPotentiallyEvaluated(E);
11099 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11100 // Do not mark anything as "used" within a dependent context; wait for
11101 // an instantiation.
11102 if (SemaRef.CurContext->isDependentContext())
11105 switch (SemaRef.ExprEvalContexts.back().Context) {
11106 case Sema::Unevaluated:
11107 case Sema::UnevaluatedAbstract:
11108 // We are in an expression that is not potentially evaluated; do nothing.
11109 // (Depending on how you read the standard, we actually do need to do
11110 // something here for null pointer constants, but the standard's
11111 // definition of a null pointer constant is completely crazy.)
11114 case Sema::ConstantEvaluated:
11115 case Sema::PotentiallyEvaluated:
11116 // We are in a potentially evaluated expression (or a constant-expression
11117 // in C++03); we need to do implicit template instantiation, implicitly
11118 // define class members, and mark most declarations as used.
11121 case Sema::PotentiallyEvaluatedIfUsed:
11122 // Referenced declarations will only be used if the construct in the
11123 // containing expression is used.
11126 llvm_unreachable("Invalid context");
11129 /// \brief Mark a function referenced, and check whether it is odr-used
11130 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11131 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11132 assert(Func && "No function?");
11134 Func->setReferenced();
11136 // C++11 [basic.def.odr]p3:
11137 // A function whose name appears as a potentially-evaluated expression is
11138 // odr-used if it is the unique lookup result or the selected member of a
11139 // set of overloaded functions [...].
11141 // We (incorrectly) mark overload resolution as an unevaluated context, so we
11142 // can just check that here. Skip the rest of this function if we've already
11143 // marked the function as used.
11144 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11145 // C++11 [temp.inst]p3:
11146 // Unless a function template specialization has been explicitly
11147 // instantiated or explicitly specialized, the function template
11148 // specialization is implicitly instantiated when the specialization is
11149 // referenced in a context that requires a function definition to exist.
11151 // We consider constexpr function templates to be referenced in a context
11152 // that requires a definition to exist whenever they are referenced.
11154 // FIXME: This instantiates constexpr functions too frequently. If this is
11155 // really an unevaluated context (and we're not just in the definition of a
11156 // function template or overload resolution or other cases which we
11157 // incorrectly consider to be unevaluated contexts), and we're not in a
11158 // subexpression which we actually need to evaluate (for instance, a
11159 // template argument, array bound or an expression in a braced-init-list),
11160 // we are not permitted to instantiate this constexpr function definition.
11162 // FIXME: This also implicitly defines special members too frequently. They
11163 // are only supposed to be implicitly defined if they are odr-used, but they
11164 // are not odr-used from constant expressions in unevaluated contexts.
11165 // However, they cannot be referenced if they are deleted, and they are
11166 // deleted whenever the implicit definition of the special member would
11168 if (!Func->isConstexpr() || Func->getBody())
11170 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11171 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11175 // Note that this declaration has been used.
11176 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11177 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11178 if (Constructor->isDefaultConstructor()) {
11179 if (Constructor->isTrivial())
11181 if (!Constructor->isUsed(false))
11182 DefineImplicitDefaultConstructor(Loc, Constructor);
11183 } else if (Constructor->isCopyConstructor()) {
11184 if (!Constructor->isUsed(false))
11185 DefineImplicitCopyConstructor(Loc, Constructor);
11186 } else if (Constructor->isMoveConstructor()) {
11187 if (!Constructor->isUsed(false))
11188 DefineImplicitMoveConstructor(Loc, Constructor);
11190 } else if (Constructor->getInheritedConstructor()) {
11191 if (!Constructor->isUsed(false))
11192 DefineInheritingConstructor(Loc, Constructor);
11195 MarkVTableUsed(Loc, Constructor->getParent());
11196 } else if (CXXDestructorDecl *Destructor =
11197 dyn_cast<CXXDestructorDecl>(Func)) {
11198 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
11199 !Destructor->isUsed(false))
11200 DefineImplicitDestructor(Loc, Destructor);
11201 if (Destructor->isVirtual())
11202 MarkVTableUsed(Loc, Destructor->getParent());
11203 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11204 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
11205 MethodDecl->isOverloadedOperator() &&
11206 MethodDecl->getOverloadedOperator() == OO_Equal) {
11207 if (!MethodDecl->isUsed(false)) {
11208 if (MethodDecl->isCopyAssignmentOperator())
11209 DefineImplicitCopyAssignment(Loc, MethodDecl);
11211 DefineImplicitMoveAssignment(Loc, MethodDecl);
11213 } else if (isa<CXXConversionDecl>(MethodDecl) &&
11214 MethodDecl->getParent()->isLambda()) {
11215 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
11216 if (Conversion->isLambdaToBlockPointerConversion())
11217 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11219 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11220 } else if (MethodDecl->isVirtual())
11221 MarkVTableUsed(Loc, MethodDecl->getParent());
11224 // Recursive functions should be marked when used from another function.
11225 // FIXME: Is this really right?
11226 if (CurContext == Func) return;
11228 // Resolve the exception specification for any function which is
11229 // used: CodeGen will need it.
11230 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11231 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11232 ResolveExceptionSpec(Loc, FPT);
11234 // Implicit instantiation of function templates and member functions of
11235 // class templates.
11236 if (Func->isImplicitlyInstantiable()) {
11237 bool AlreadyInstantiated = false;
11238 SourceLocation PointOfInstantiation = Loc;
11239 if (FunctionTemplateSpecializationInfo *SpecInfo
11240 = Func->getTemplateSpecializationInfo()) {
11241 if (SpecInfo->getPointOfInstantiation().isInvalid())
11242 SpecInfo->setPointOfInstantiation(Loc);
11243 else if (SpecInfo->getTemplateSpecializationKind()
11244 == TSK_ImplicitInstantiation) {
11245 AlreadyInstantiated = true;
11246 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11248 } else if (MemberSpecializationInfo *MSInfo
11249 = Func->getMemberSpecializationInfo()) {
11250 if (MSInfo->getPointOfInstantiation().isInvalid())
11251 MSInfo->setPointOfInstantiation(Loc);
11252 else if (MSInfo->getTemplateSpecializationKind()
11253 == TSK_ImplicitInstantiation) {
11254 AlreadyInstantiated = true;
11255 PointOfInstantiation = MSInfo->getPointOfInstantiation();
11259 if (!AlreadyInstantiated || Func->isConstexpr()) {
11260 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11261 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11262 ActiveTemplateInstantiations.size())
11263 PendingLocalImplicitInstantiations.push_back(
11264 std::make_pair(Func, PointOfInstantiation));
11265 else if (Func->isConstexpr())
11266 // Do not defer instantiations of constexpr functions, to avoid the
11267 // expression evaluator needing to call back into Sema if it sees a
11268 // call to such a function.
11269 InstantiateFunctionDefinition(PointOfInstantiation, Func);
11271 PendingInstantiations.push_back(std::make_pair(Func,
11272 PointOfInstantiation));
11273 // Notify the consumer that a function was implicitly instantiated.
11274 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11278 // Walk redefinitions, as some of them may be instantiable.
11279 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
11280 e(Func->redecls_end()); i != e; ++i) {
11281 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11282 MarkFunctionReferenced(Loc, *i);
11286 // Keep track of used but undefined functions.
11287 if (!Func->isDefined()) {
11288 if (mightHaveNonExternalLinkage(Func))
11289 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11290 else if (Func->getMostRecentDecl()->isInlined() &&
11291 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11292 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11293 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11296 // Normally the most current decl is marked used while processing the use and
11297 // any subsequent decls are marked used by decl merging. This fails with
11298 // template instantiation since marking can happen at the end of the file
11299 // and, because of the two phase lookup, this function is called with at
11300 // decl in the middle of a decl chain. We loop to maintain the invariant
11301 // that once a decl is used, all decls after it are also used.
11302 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11303 F->markUsed(Context);
11310 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11311 VarDecl *var, DeclContext *DC) {
11312 DeclContext *VarDC = var->getDeclContext();
11314 // If the parameter still belongs to the translation unit, then
11315 // we're actually just using one parameter in the declaration of
11317 if (isa<ParmVarDecl>(var) &&
11318 isa<TranslationUnitDecl>(VarDC))
11321 // For C code, don't diagnose about capture if we're not actually in code
11322 // right now; it's impossible to write a non-constant expression outside of
11323 // function context, so we'll get other (more useful) diagnostics later.
11325 // For C++, things get a bit more nasty... it would be nice to suppress this
11326 // diagnostic for certain cases like using a local variable in an array bound
11327 // for a member of a local class, but the correct predicate is not obvious.
11328 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11331 if (isa<CXXMethodDecl>(VarDC) &&
11332 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11333 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11334 << var->getIdentifier();
11335 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11336 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11337 << var->getIdentifier() << fn->getDeclName();
11338 } else if (isa<BlockDecl>(VarDC)) {
11339 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11340 << var->getIdentifier();
11342 // FIXME: Is there any other context where a local variable can be
11344 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11345 << var->getIdentifier();
11348 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11349 << var->getIdentifier();
11351 // FIXME: Add additional diagnostic info about class etc. which prevents
11356 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11357 bool &SubCapturesAreNested,
11358 QualType &CaptureType,
11359 QualType &DeclRefType) {
11360 // Check whether we've already captured it.
11361 if (CSI->CaptureMap.count(Var)) {
11362 // If we found a capture, any subcaptures are nested.
11363 SubCapturesAreNested = true;
11365 // Retrieve the capture type for this variable.
11366 CaptureType = CSI->getCapture(Var).getCaptureType();
11368 // Compute the type of an expression that refers to this variable.
11369 DeclRefType = CaptureType.getNonReferenceType();
11371 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11372 if (Cap.isCopyCapture() &&
11373 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11374 DeclRefType.addConst();
11380 // Only block literals, captured statements, and lambda expressions can
11381 // capture; other scopes don't work.
11382 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11383 SourceLocation Loc,
11384 const bool Diagnose, Sema &S) {
11385 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11386 return getLambdaAwareParentOfDeclContext(DC);
11389 diagnoseUncapturableValueReference(S, Loc, Var, DC);
11394 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11395 // certain types of variables (unnamed, variably modified types etc.)
11396 // so check for eligibility.
11397 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11398 SourceLocation Loc,
11399 const bool Diagnose, Sema &S) {
11401 bool IsBlock = isa<BlockScopeInfo>(CSI);
11402 bool IsLambda = isa<LambdaScopeInfo>(CSI);
11404 // Lambdas are not allowed to capture unnamed variables
11405 // (e.g. anonymous unions).
11406 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11407 // assuming that's the intent.
11408 if (IsLambda && !Var->getDeclName()) {
11410 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11411 S.Diag(Var->getLocation(), diag::note_declared_at);
11416 // Prohibit variably-modified types; they're difficult to deal with.
11417 if (Var->getType()->isVariablyModifiedType()) {
11420 S.Diag(Loc, diag::err_ref_vm_type);
11422 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11423 S.Diag(Var->getLocation(), diag::note_previous_decl)
11424 << Var->getDeclName();
11428 // Prohibit structs with flexible array members too.
11429 // We cannot capture what is in the tail end of the struct.
11430 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11431 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11434 S.Diag(Loc, diag::err_ref_flexarray_type);
11436 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11437 << Var->getDeclName();
11438 S.Diag(Var->getLocation(), diag::note_previous_decl)
11439 << Var->getDeclName();
11444 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11445 // Lambdas and captured statements are not allowed to capture __block
11446 // variables; they don't support the expected semantics.
11447 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11449 S.Diag(Loc, diag::err_capture_block_variable)
11450 << Var->getDeclName() << !IsLambda;
11451 S.Diag(Var->getLocation(), diag::note_previous_decl)
11452 << Var->getDeclName();
11460 // Returns true if the capture by block was successful.
11461 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11462 SourceLocation Loc,
11463 const bool BuildAndDiagnose,
11464 QualType &CaptureType,
11465 QualType &DeclRefType,
11468 Expr *CopyExpr = 0;
11469 bool ByRef = false;
11471 // Blocks are not allowed to capture arrays.
11472 if (CaptureType->isArrayType()) {
11473 if (BuildAndDiagnose) {
11474 S.Diag(Loc, diag::err_ref_array_type);
11475 S.Diag(Var->getLocation(), diag::note_previous_decl)
11476 << Var->getDeclName();
11481 // Forbid the block-capture of autoreleasing variables.
11482 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11483 if (BuildAndDiagnose) {
11484 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11486 S.Diag(Var->getLocation(), diag::note_previous_decl)
11487 << Var->getDeclName();
11491 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11492 if (HasBlocksAttr || CaptureType->isReferenceType()) {
11493 // Block capture by reference does not change the capture or
11494 // declaration reference types.
11497 // Block capture by copy introduces 'const'.
11498 CaptureType = CaptureType.getNonReferenceType().withConst();
11499 DeclRefType = CaptureType;
11501 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11502 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11503 // The capture logic needs the destructor, so make sure we mark it.
11504 // Usually this is unnecessary because most local variables have
11505 // their destructors marked at declaration time, but parameters are
11506 // an exception because it's technically only the call site that
11507 // actually requires the destructor.
11508 if (isa<ParmVarDecl>(Var))
11509 S.FinalizeVarWithDestructor(Var, Record);
11511 // Enter a new evaluation context to insulate the copy
11512 // full-expression.
11513 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11515 // According to the blocks spec, the capture of a variable from
11516 // the stack requires a const copy constructor. This is not true
11517 // of the copy/move done to move a __block variable to the heap.
11518 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11519 DeclRefType.withConst(),
11523 = S.PerformCopyInitialization(
11524 InitializedEntity::InitializeBlock(Var->getLocation(),
11525 CaptureType, false),
11526 Loc, S.Owned(DeclRef));
11528 // Build a full-expression copy expression if initialization
11529 // succeeded and used a non-trivial constructor. Recover from
11530 // errors by pretending that the copy isn't necessary.
11531 if (!Result.isInvalid() &&
11532 !cast<CXXConstructExpr>(Result.get())->getConstructor()
11534 Result = S.MaybeCreateExprWithCleanups(Result);
11535 CopyExpr = Result.take();
11541 // Actually capture the variable.
11542 if (BuildAndDiagnose)
11543 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11544 SourceLocation(), CaptureType, CopyExpr);
11551 /// \brief Capture the given variable in the captured region.
11552 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11554 SourceLocation Loc,
11555 const bool BuildAndDiagnose,
11556 QualType &CaptureType,
11557 QualType &DeclRefType,
11558 const bool RefersToEnclosingLocal,
11561 // By default, capture variables by reference.
11563 // Using an LValue reference type is consistent with Lambdas (see below).
11564 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11565 Expr *CopyExpr = 0;
11566 if (BuildAndDiagnose) {
11567 // The current implementation assumes that all variables are captured
11568 // by references. Since there is no capture by copy, no expression evaluation
11571 RecordDecl *RD = RSI->TheRecordDecl;
11574 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType,
11575 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11576 0, false, ICIS_NoInit);
11577 Field->setImplicit(true);
11578 Field->setAccess(AS_private);
11579 RD->addDecl(Field);
11581 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11582 DeclRefType, VK_LValue, Loc);
11583 Var->setReferenced(true);
11584 Var->markUsed(S.Context);
11587 // Actually capture the variable.
11588 if (BuildAndDiagnose)
11589 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11590 SourceLocation(), CaptureType, CopyExpr);
11596 /// \brief Create a field within the lambda class for the variable
11597 /// being captured. Handle Array captures.
11598 static ExprResult addAsFieldToClosureType(Sema &S,
11599 LambdaScopeInfo *LSI,
11600 VarDecl *Var, QualType FieldType,
11601 QualType DeclRefType,
11602 SourceLocation Loc,
11603 bool RefersToEnclosingLocal) {
11604 CXXRecordDecl *Lambda = LSI->Lambda;
11606 // Build the non-static data member.
11608 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11609 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11610 0, false, ICIS_NoInit);
11611 Field->setImplicit(true);
11612 Field->setAccess(AS_private);
11613 Lambda->addDecl(Field);
11615 // C++11 [expr.prim.lambda]p21:
11616 // When the lambda-expression is evaluated, the entities that
11617 // are captured by copy are used to direct-initialize each
11618 // corresponding non-static data member of the resulting closure
11619 // object. (For array members, the array elements are
11620 // direct-initialized in increasing subscript order.) These
11621 // initializations are performed in the (unspecified) order in
11622 // which the non-static data members are declared.
11624 // Introduce a new evaluation context for the initialization, so
11625 // that temporaries introduced as part of the capture are retained
11626 // to be re-"exported" from the lambda expression itself.
11627 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11629 // C++ [expr.prim.labda]p12:
11630 // An entity captured by a lambda-expression is odr-used (3.2) in
11631 // the scope containing the lambda-expression.
11632 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11633 DeclRefType, VK_LValue, Loc);
11634 Var->setReferenced(true);
11635 Var->markUsed(S.Context);
11637 // When the field has array type, create index variables for each
11638 // dimension of the array. We use these index variables to subscript
11639 // the source array, and other clients (e.g., CodeGen) will perform
11640 // the necessary iteration with these index variables.
11641 SmallVector<VarDecl *, 4> IndexVariables;
11642 QualType BaseType = FieldType;
11643 QualType SizeType = S.Context.getSizeType();
11644 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11645 while (const ConstantArrayType *Array
11646 = S.Context.getAsConstantArrayType(BaseType)) {
11647 // Create the iteration variable for this array index.
11648 IdentifierInfo *IterationVarName = 0;
11650 SmallString<8> Str;
11651 llvm::raw_svector_ostream OS(Str);
11652 OS << "__i" << IndexVariables.size();
11653 IterationVarName = &S.Context.Idents.get(OS.str());
11655 VarDecl *IterationVar
11656 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11657 IterationVarName, SizeType,
11658 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11660 IndexVariables.push_back(IterationVar);
11661 LSI->ArrayIndexVars.push_back(IterationVar);
11663 // Create a reference to the iteration variable.
11664 ExprResult IterationVarRef
11665 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11666 assert(!IterationVarRef.isInvalid() &&
11667 "Reference to invented variable cannot fail!");
11668 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11669 assert(!IterationVarRef.isInvalid() &&
11670 "Conversion of invented variable cannot fail!");
11672 // Subscript the array with this iteration variable.
11673 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11674 Ref, Loc, IterationVarRef.take(), Loc);
11675 if (Subscript.isInvalid()) {
11676 S.CleanupVarDeclMarking();
11677 S.DiscardCleanupsInEvaluationContext();
11678 return ExprError();
11681 Ref = Subscript.take();
11682 BaseType = Array->getElementType();
11685 // Construct the entity that we will be initializing. For an array, this
11686 // will be first element in the array, which may require several levels
11687 // of array-subscript entities.
11688 SmallVector<InitializedEntity, 4> Entities;
11689 Entities.reserve(1 + IndexVariables.size());
11690 Entities.push_back(
11691 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11692 Field->getType(), Loc));
11693 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11694 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11698 InitializationKind InitKind
11699 = InitializationKind::CreateDirect(Loc, Loc, Loc);
11700 InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11701 ExprResult Result(true);
11702 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11703 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11705 // If this initialization requires any cleanups (e.g., due to a
11706 // default argument to a copy constructor), note that for the
11708 if (S.ExprNeedsCleanups)
11709 LSI->ExprNeedsCleanups = true;
11711 // Exit the expression evaluation context used for the capture.
11712 S.CleanupVarDeclMarking();
11713 S.DiscardCleanupsInEvaluationContext();
11719 /// \brief Capture the given variable in the lambda.
11720 static bool captureInLambda(LambdaScopeInfo *LSI,
11722 SourceLocation Loc,
11723 const bool BuildAndDiagnose,
11724 QualType &CaptureType,
11725 QualType &DeclRefType,
11726 const bool RefersToEnclosingLocal,
11727 const Sema::TryCaptureKind Kind,
11728 SourceLocation EllipsisLoc,
11729 const bool IsTopScope,
11732 // Determine whether we are capturing by reference or by value.
11733 bool ByRef = false;
11734 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11735 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11737 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11740 // Compute the type of the field that will capture this variable.
11742 // C++11 [expr.prim.lambda]p15:
11743 // An entity is captured by reference if it is implicitly or
11744 // explicitly captured but not captured by copy. It is
11745 // unspecified whether additional unnamed non-static data
11746 // members are declared in the closure type for entities
11747 // captured by reference.
11749 // FIXME: It is not clear whether we want to build an lvalue reference
11750 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11751 // to do the former, while EDG does the latter. Core issue 1249 will
11752 // clarify, but for now we follow GCC because it's a more permissive and
11753 // easily defensible position.
11754 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11756 // C++11 [expr.prim.lambda]p14:
11757 // For each entity captured by copy, an unnamed non-static
11758 // data member is declared in the closure type. The
11759 // declaration order of these members is unspecified. The type
11760 // of such a data member is the type of the corresponding
11761 // captured entity if the entity is not a reference to an
11762 // object, or the referenced type otherwise. [Note: If the
11763 // captured entity is a reference to a function, the
11764 // corresponding data member is also a reference to a
11765 // function. - end note ]
11766 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11767 if (!RefType->getPointeeType()->isFunctionType())
11768 CaptureType = RefType->getPointeeType();
11771 // Forbid the lambda copy-capture of autoreleasing variables.
11772 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11773 if (BuildAndDiagnose) {
11774 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11775 S.Diag(Var->getLocation(), diag::note_previous_decl)
11776 << Var->getDeclName();
11781 if (S.RequireNonAbstractType(Loc, CaptureType,
11782 diag::err_capture_of_abstract_type))
11786 // Capture this variable in the lambda.
11787 Expr *CopyExpr = 0;
11788 if (BuildAndDiagnose) {
11789 ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
11790 CaptureType, DeclRefType, Loc,
11791 RefersToEnclosingLocal);
11792 if (!Result.isInvalid())
11793 CopyExpr = Result.take();
11796 // Compute the type of a reference to this captured variable.
11798 DeclRefType = CaptureType.getNonReferenceType();
11800 // C++ [expr.prim.lambda]p5:
11801 // The closure type for a lambda-expression has a public inline
11802 // function call operator [...]. This function call operator is
11803 // declared const (9.3.1) if and only if the lambda-expression’s
11804 // parameter-declaration-clause is not followed by mutable.
11805 DeclRefType = CaptureType.getNonReferenceType();
11806 if (!LSI->Mutable && !CaptureType->isReferenceType())
11807 DeclRefType.addConst();
11810 // Add the capture.
11811 if (BuildAndDiagnose)
11812 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
11813 Loc, EllipsisLoc, CaptureType, CopyExpr);
11819 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
11820 TryCaptureKind Kind, SourceLocation EllipsisLoc,
11821 bool BuildAndDiagnose,
11822 QualType &CaptureType,
11823 QualType &DeclRefType,
11824 const unsigned *const FunctionScopeIndexToStopAt) {
11825 bool Nested = false;
11827 DeclContext *DC = CurContext;
11828 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
11829 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
11830 // We need to sync up the Declaration Context with the
11831 // FunctionScopeIndexToStopAt
11832 if (FunctionScopeIndexToStopAt) {
11833 unsigned FSIndex = FunctionScopes.size() - 1;
11834 while (FSIndex != MaxFunctionScopesIndex) {
11835 DC = getLambdaAwareParentOfDeclContext(DC);
11841 // If the variable is declared in the current context (and is not an
11842 // init-capture), there is no need to capture it.
11843 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
11844 if (!Var->hasLocalStorage()) return true;
11846 // Walk up the stack to determine whether we can capture the variable,
11847 // performing the "simple" checks that don't depend on type. We stop when
11848 // we've either hit the declared scope of the variable or find an existing
11849 // capture of that variable. We start from the innermost capturing-entity
11850 // (the DC) and ensure that all intervening capturing-entities
11851 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
11852 // declcontext can either capture the variable or have already captured
11854 CaptureType = Var->getType();
11855 DeclRefType = CaptureType.getNonReferenceType();
11856 bool Explicit = (Kind != TryCapture_Implicit);
11857 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
11859 // Only block literals, captured statements, and lambda expressions can
11860 // capture; other scopes don't work.
11861 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
11865 if (!ParentDC) return true;
11867 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
11868 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
11871 // Check whether we've already captured it.
11872 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
11875 // If we are instantiating a generic lambda call operator body,
11876 // we do not want to capture new variables. What was captured
11877 // during either a lambdas transformation or initial parsing
11879 if (isGenericLambdaCallOperatorSpecialization(DC)) {
11880 if (BuildAndDiagnose) {
11881 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11882 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
11883 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
11884 Diag(Var->getLocation(), diag::note_previous_decl)
11885 << Var->getDeclName();
11886 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
11888 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
11892 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11893 // certain types of variables (unnamed, variably modified types etc.)
11894 // so check for eligibility.
11895 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
11898 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11899 // No capture-default, and this is not an explicit capture
11900 // so cannot capture this variable.
11901 if (BuildAndDiagnose) {
11902 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
11903 Diag(Var->getLocation(), diag::note_previous_decl)
11904 << Var->getDeclName();
11905 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11906 diag::note_lambda_decl);
11907 // FIXME: If we error out because an outer lambda can not implicitly
11908 // capture a variable that an inner lambda explicitly captures, we
11909 // should have the inner lambda do the explicit capture - because
11910 // it makes for cleaner diagnostics later. This would purely be done
11911 // so that the diagnostic does not misleadingly claim that a variable
11912 // can not be captured by a lambda implicitly even though it is captured
11913 // explicitly. Suggestion:
11914 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
11915 // at the function head
11916 // - cache the StartingDeclContext - this must be a lambda
11917 // - captureInLambda in the innermost lambda the variable.
11922 FunctionScopesIndex--;
11925 } while (!Var->getDeclContext()->Equals(DC));
11927 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
11928 // computing the type of the capture at each step, checking type-specific
11929 // requirements, and adding captures if requested.
11930 // If the variable had already been captured previously, we start capturing
11931 // at the lambda nested within that one.
11932 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
11934 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
11936 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
11937 if (!captureInBlock(BSI, Var, ExprLoc,
11938 BuildAndDiagnose, CaptureType,
11939 DeclRefType, Nested, *this))
11942 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
11943 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
11944 BuildAndDiagnose, CaptureType,
11945 DeclRefType, Nested, *this))
11949 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11950 if (!captureInLambda(LSI, Var, ExprLoc,
11951 BuildAndDiagnose, CaptureType,
11952 DeclRefType, Nested, Kind, EllipsisLoc,
11953 /*IsTopScope*/I == N - 1, *this))
11961 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11962 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11963 QualType CaptureType;
11964 QualType DeclRefType;
11965 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11966 /*BuildAndDiagnose=*/true, CaptureType,
11970 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11971 QualType CaptureType;
11972 QualType DeclRefType;
11974 // Determine whether we can capture this variable.
11975 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11976 /*BuildAndDiagnose=*/false, CaptureType,
11980 return DeclRefType;
11985 // If either the type of the variable or the initializer is dependent,
11986 // return false. Otherwise, determine whether the variable is a constant
11987 // expression. Use this if you need to know if a variable that might or
11988 // might not be dependent is truly a constant expression.
11989 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
11990 ASTContext &Context) {
11992 if (Var->getType()->isDependentType())
11994 const VarDecl *DefVD = 0;
11995 Var->getAnyInitializer(DefVD);
11998 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
11999 Expr *Init = cast<Expr>(Eval->Value);
12000 if (Init->isValueDependent())
12002 return IsVariableAConstantExpression(Var, Context);
12006 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12007 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12008 // an object that satisfies the requirements for appearing in a
12009 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12010 // is immediately applied." This function handles the lvalue-to-rvalue
12011 // conversion part.
12012 MaybeODRUseExprs.erase(E->IgnoreParens());
12014 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12015 // to a variable that is a constant expression, and if so, identify it as
12016 // a reference to a variable that does not involve an odr-use of that
12018 if (LambdaScopeInfo *LSI = getCurLambda()) {
12019 Expr *SansParensExpr = E->IgnoreParens();
12021 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12022 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12023 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12024 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12026 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12027 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12031 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12032 if (!Res.isUsable())
12035 // If a constant-expression is a reference to a variable where we delay
12036 // deciding whether it is an odr-use, just assume we will apply the
12037 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
12038 // (a non-type template argument), we have special handling anyway.
12039 UpdateMarkingForLValueToRValue(Res.get());
12043 void Sema::CleanupVarDeclMarking() {
12044 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12045 e = MaybeODRUseExprs.end();
12048 SourceLocation Loc;
12049 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12050 Var = cast<VarDecl>(DRE->getDecl());
12051 Loc = DRE->getLocation();
12052 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12053 Var = cast<VarDecl>(ME->getMemberDecl());
12054 Loc = ME->getMemberLoc();
12056 llvm_unreachable("Unexpcted expression");
12059 MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0);
12062 MaybeODRUseExprs.clear();
12066 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12067 VarDecl *Var, Expr *E) {
12068 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12069 "Invalid Expr argument to DoMarkVarDeclReferenced");
12070 Var->setReferenced();
12072 // If the context is not PotentiallyEvaluated and not Unevaluated
12073 // (i.e PotentiallyEvaluatedIfUsed) do not bother to consider variables
12074 // in this context for odr-use unless we are within a lambda.
12075 // If we don't know whether the context is potentially evaluated or not
12076 // (for e.g., if we're in a generic lambda), we want to add a potential
12077 // capture and eventually analyze for odr-use.
12078 // We should also be able to analyze certain constructs in a non-generic
12079 // lambda setting for potential odr-use and capture violation:
12080 // template<class T> void foo(T t) {
12081 // auto L = [](int i) { return t; };
12084 if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12086 if (SemaRef.isUnevaluatedContext()) return;
12088 const bool refersToEnclosingScope =
12089 (SemaRef.CurContext != Var->getDeclContext() &&
12090 Var->getDeclContext()->isFunctionOrMethod());
12091 if (!refersToEnclosingScope) return;
12093 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12094 // If a variable could potentially be odr-used, defer marking it so
12095 // until we finish analyzing the full expression for any lvalue-to-rvalue
12096 // or discarded value conversions that would obviate odr-use.
12097 // Add it to the list of potential captures that will be analyzed
12098 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12099 // unless the variable is a reference that was initialized by a constant
12100 // expression (this will never need to be captured or odr-used).
12101 const bool IsConstantExpr = IsVariableNonDependentAndAConstantExpression(
12102 Var, SemaRef.Context);
12103 assert(E && "Capture variable should be used in an expression.");
12104 if (!IsConstantExpr || !Var->getType()->isReferenceType())
12105 LSI->addPotentialCapture(E->IgnoreParens());
12110 VarTemplateSpecializationDecl *VarSpec =
12111 dyn_cast<VarTemplateSpecializationDecl>(Var);
12112 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12113 "Can't instantiate a partial template specialization.");
12115 // Implicit instantiation of static data members, static data member
12116 // templates of class templates, and variable template specializations.
12117 // Delay instantiations of variable templates, except for those
12118 // that could be used in a constant expression.
12119 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12120 if (isTemplateInstantiation(TSK)) {
12121 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12123 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12124 if (Var->getPointOfInstantiation().isInvalid()) {
12125 // This is a modification of an existing AST node. Notify listeners.
12126 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12127 L->StaticDataMemberInstantiated(Var);
12128 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12129 // Don't bother trying to instantiate it again, unless we might need
12130 // its initializer before we get to the end of the TU.
12131 TryInstantiating = false;
12134 if (Var->getPointOfInstantiation().isInvalid())
12135 Var->setTemplateSpecializationKind(TSK, Loc);
12137 if (TryInstantiating) {
12138 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12139 bool InstantiationDependent = false;
12140 bool IsNonDependent =
12141 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12142 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12145 // Do not instantiate specializations that are still type-dependent.
12146 if (IsNonDependent) {
12147 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12148 // Do not defer instantiations of variables which could be used in a
12149 // constant expression.
12150 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12152 SemaRef.PendingInstantiations
12153 .push_back(std::make_pair(Var, PointOfInstantiation));
12158 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12159 // the requirements for appearing in a constant expression (5.19) and, if
12160 // it is an object, the lvalue-to-rvalue conversion (4.1)
12161 // is immediately applied." We check the first part here, and
12162 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12163 // Note that we use the C++11 definition everywhere because nothing in
12164 // C++03 depends on whether we get the C++03 version correct. The second
12165 // part does not apply to references, since they are not objects.
12166 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12167 // A reference initialized by a constant expression can never be
12168 // odr-used, so simply ignore it.
12169 // But a non-reference might get odr-used if it doesn't undergo
12170 // an lvalue-to-rvalue or is discarded, so track it.
12171 if (!Var->getType()->isReferenceType())
12172 SemaRef.MaybeODRUseExprs.insert(E);
12175 MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0);
12178 /// \brief Mark a variable referenced, and check whether it is odr-used
12179 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
12180 /// used directly for normal expressions referring to VarDecl.
12181 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12182 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
12185 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12186 Decl *D, Expr *E, bool OdrUse) {
12187 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12188 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12192 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12194 // If this is a call to a method via a cast, also mark the method in the
12195 // derived class used in case codegen can devirtualize the call.
12196 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12199 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12202 const Expr *Base = ME->getBase();
12203 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12204 if (!MostDerivedClassDecl)
12206 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12207 if (!DM || DM->isPure())
12209 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12212 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12213 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12214 // TODO: update this with DR# once a defect report is filed.
12215 // C++11 defect. The address of a pure member should not be an ODR use, even
12216 // if it's a qualified reference.
12217 bool OdrUse = true;
12218 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12219 if (Method->isVirtual())
12221 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12224 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12225 void Sema::MarkMemberReferenced(MemberExpr *E) {
12226 // C++11 [basic.def.odr]p2:
12227 // A non-overloaded function whose name appears as a potentially-evaluated
12228 // expression or a member of a set of candidate functions, if selected by
12229 // overload resolution when referred to from a potentially-evaluated
12230 // expression, is odr-used, unless it is a pure virtual function and its
12231 // name is not explicitly qualified.
12232 bool OdrUse = true;
12233 if (!E->hasQualifier()) {
12234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12235 if (Method->isPure())
12238 SourceLocation Loc = E->getMemberLoc().isValid() ?
12239 E->getMemberLoc() : E->getLocStart();
12240 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12243 /// \brief Perform marking for a reference to an arbitrary declaration. It
12244 /// marks the declaration referenced, and performs odr-use checking for functions
12245 /// and variables. This method should not be used when building an normal
12246 /// expression which refers to a variable.
12247 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12249 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12250 MarkVariableReferenced(Loc, VD);
12253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12254 MarkFunctionReferenced(Loc, FD);
12258 D->setReferenced();
12262 // Mark all of the declarations referenced
12263 // FIXME: Not fully implemented yet! We need to have a better understanding
12264 // of when we're entering
12265 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12267 SourceLocation Loc;
12270 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12272 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12274 bool TraverseTemplateArgument(const TemplateArgument &Arg);
12275 bool TraverseRecordType(RecordType *T);
12279 bool MarkReferencedDecls::TraverseTemplateArgument(
12280 const TemplateArgument &Arg) {
12281 if (Arg.getKind() == TemplateArgument::Declaration) {
12282 if (Decl *D = Arg.getAsDecl())
12283 S.MarkAnyDeclReferenced(Loc, D, true);
12286 return Inherited::TraverseTemplateArgument(Arg);
12289 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12290 if (ClassTemplateSpecializationDecl *Spec
12291 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12292 const TemplateArgumentList &Args = Spec->getTemplateArgs();
12293 return TraverseTemplateArguments(Args.data(), Args.size());
12299 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12300 MarkReferencedDecls Marker(*this, Loc);
12301 Marker.TraverseType(Context.getCanonicalType(T));
12305 /// \brief Helper class that marks all of the declarations referenced by
12306 /// potentially-evaluated subexpressions as "referenced".
12307 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12309 bool SkipLocalVariables;
12312 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12314 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12315 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12317 void VisitDeclRefExpr(DeclRefExpr *E) {
12318 // If we were asked not to visit local variables, don't.
12319 if (SkipLocalVariables) {
12320 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12321 if (VD->hasLocalStorage())
12325 S.MarkDeclRefReferenced(E);
12328 void VisitMemberExpr(MemberExpr *E) {
12329 S.MarkMemberReferenced(E);
12330 Inherited::VisitMemberExpr(E);
12333 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12334 S.MarkFunctionReferenced(E->getLocStart(),
12335 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12336 Visit(E->getSubExpr());
12339 void VisitCXXNewExpr(CXXNewExpr *E) {
12340 if (E->getOperatorNew())
12341 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12342 if (E->getOperatorDelete())
12343 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12344 Inherited::VisitCXXNewExpr(E);
12347 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12348 if (E->getOperatorDelete())
12349 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12350 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12351 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12352 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12353 S.MarkFunctionReferenced(E->getLocStart(),
12354 S.LookupDestructor(Record));
12357 Inherited::VisitCXXDeleteExpr(E);
12360 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12361 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12362 Inherited::VisitCXXConstructExpr(E);
12365 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12366 Visit(E->getExpr());
12369 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12370 Inherited::VisitImplicitCastExpr(E);
12372 if (E->getCastKind() == CK_LValueToRValue)
12373 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12378 /// \brief Mark any declarations that appear within this expression or any
12379 /// potentially-evaluated subexpressions as "referenced".
12381 /// \param SkipLocalVariables If true, don't mark local variables as
12383 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12384 bool SkipLocalVariables) {
12385 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12388 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12389 /// of the program being compiled.
12391 /// This routine emits the given diagnostic when the code currently being
12392 /// type-checked is "potentially evaluated", meaning that there is a
12393 /// possibility that the code will actually be executable. Code in sizeof()
12394 /// expressions, code used only during overload resolution, etc., are not
12395 /// potentially evaluated. This routine will suppress such diagnostics or,
12396 /// in the absolutely nutty case of potentially potentially evaluated
12397 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12400 /// This routine should be used for all diagnostics that describe the run-time
12401 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12402 /// Failure to do so will likely result in spurious diagnostics or failures
12403 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12404 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12405 const PartialDiagnostic &PD) {
12406 switch (ExprEvalContexts.back().Context) {
12408 case UnevaluatedAbstract:
12409 // The argument will never be evaluated, so don't complain.
12412 case ConstantEvaluated:
12413 // Relevant diagnostics should be produced by constant evaluation.
12416 case PotentiallyEvaluated:
12417 case PotentiallyEvaluatedIfUsed:
12418 if (Statement && getCurFunctionOrMethodDecl()) {
12419 FunctionScopes.back()->PossiblyUnreachableDiags.
12420 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12431 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12432 CallExpr *CE, FunctionDecl *FD) {
12433 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12436 // If we're inside a decltype's expression, don't check for a valid return
12437 // type or construct temporaries until we know whether this is the last call.
12438 if (ExprEvalContexts.back().IsDecltype) {
12439 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12443 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12448 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12449 : FD(FD), CE(CE) { }
12451 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
12453 S.Diag(Loc, diag::err_call_incomplete_return)
12454 << T << CE->getSourceRange();
12458 S.Diag(Loc, diag::err_call_function_incomplete_return)
12459 << CE->getSourceRange() << FD->getDeclName() << T;
12460 S.Diag(FD->getLocation(),
12461 diag::note_function_with_incomplete_return_type_declared_here)
12462 << FD->getDeclName();
12464 } Diagnoser(FD, CE);
12466 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12472 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12473 // will prevent this condition from triggering, which is what we want.
12474 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12475 SourceLocation Loc;
12477 unsigned diagnostic = diag::warn_condition_is_assignment;
12478 bool IsOrAssign = false;
12480 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12481 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12484 IsOrAssign = Op->getOpcode() == BO_OrAssign;
12486 // Greylist some idioms by putting them into a warning subcategory.
12487 if (ObjCMessageExpr *ME
12488 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12489 Selector Sel = ME->getSelector();
12491 // self = [<foo> init...]
12492 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12493 diagnostic = diag::warn_condition_is_idiomatic_assignment;
12495 // <foo> = [<bar> nextObject]
12496 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12497 diagnostic = diag::warn_condition_is_idiomatic_assignment;
12500 Loc = Op->getOperatorLoc();
12501 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12502 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12505 IsOrAssign = Op->getOperator() == OO_PipeEqual;
12506 Loc = Op->getOperatorLoc();
12507 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12508 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12510 // Not an assignment.
12514 Diag(Loc, diagnostic) << E->getSourceRange();
12516 SourceLocation Open = E->getLocStart();
12517 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12518 Diag(Loc, diag::note_condition_assign_silence)
12519 << FixItHint::CreateInsertion(Open, "(")
12520 << FixItHint::CreateInsertion(Close, ")");
12523 Diag(Loc, diag::note_condition_or_assign_to_comparison)
12524 << FixItHint::CreateReplacement(Loc, "!=");
12526 Diag(Loc, diag::note_condition_assign_to_comparison)
12527 << FixItHint::CreateReplacement(Loc, "==");
12530 /// \brief Redundant parentheses over an equality comparison can indicate
12531 /// that the user intended an assignment used as condition.
12532 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12533 // Don't warn if the parens came from a macro.
12534 SourceLocation parenLoc = ParenE->getLocStart();
12535 if (parenLoc.isInvalid() || parenLoc.isMacroID())
12537 // Don't warn for dependent expressions.
12538 if (ParenE->isTypeDependent())
12541 Expr *E = ParenE->IgnoreParens();
12543 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12544 if (opE->getOpcode() == BO_EQ &&
12545 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12546 == Expr::MLV_Valid) {
12547 SourceLocation Loc = opE->getOperatorLoc();
12549 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12550 SourceRange ParenERange = ParenE->getSourceRange();
12551 Diag(Loc, diag::note_equality_comparison_silence)
12552 << FixItHint::CreateRemoval(ParenERange.getBegin())
12553 << FixItHint::CreateRemoval(ParenERange.getEnd());
12554 Diag(Loc, diag::note_equality_comparison_to_assign)
12555 << FixItHint::CreateReplacement(Loc, "=");
12559 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12560 DiagnoseAssignmentAsCondition(E);
12561 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12562 DiagnoseEqualityWithExtraParens(parenE);
12564 ExprResult result = CheckPlaceholderExpr(E);
12565 if (result.isInvalid()) return ExprError();
12568 if (!E->isTypeDependent()) {
12569 if (getLangOpts().CPlusPlus)
12570 return CheckCXXBooleanCondition(E); // C++ 6.4p4
12572 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12573 if (ERes.isInvalid())
12574 return ExprError();
12577 QualType T = E->getType();
12578 if (!T->isScalarType()) { // C99 6.8.4.1p1
12579 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12580 << T << E->getSourceRange();
12581 return ExprError();
12588 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12591 return ExprError();
12593 return CheckBooleanCondition(SubExpr, Loc);
12597 /// A visitor for rebuilding a call to an __unknown_any expression
12598 /// to have an appropriate type.
12599 struct RebuildUnknownAnyFunction
12600 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12604 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12606 ExprResult VisitStmt(Stmt *S) {
12607 llvm_unreachable("unexpected statement!");
12610 ExprResult VisitExpr(Expr *E) {
12611 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12612 << E->getSourceRange();
12613 return ExprError();
12616 /// Rebuild an expression which simply semantically wraps another
12617 /// expression which it shares the type and value kind of.
12618 template <class T> ExprResult rebuildSugarExpr(T *E) {
12619 ExprResult SubResult = Visit(E->getSubExpr());
12620 if (SubResult.isInvalid()) return ExprError();
12622 Expr *SubExpr = SubResult.take();
12623 E->setSubExpr(SubExpr);
12624 E->setType(SubExpr->getType());
12625 E->setValueKind(SubExpr->getValueKind());
12626 assert(E->getObjectKind() == OK_Ordinary);
12630 ExprResult VisitParenExpr(ParenExpr *E) {
12631 return rebuildSugarExpr(E);
12634 ExprResult VisitUnaryExtension(UnaryOperator *E) {
12635 return rebuildSugarExpr(E);
12638 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12639 ExprResult SubResult = Visit(E->getSubExpr());
12640 if (SubResult.isInvalid()) return ExprError();
12642 Expr *SubExpr = SubResult.take();
12643 E->setSubExpr(SubExpr);
12644 E->setType(S.Context.getPointerType(SubExpr->getType()));
12645 assert(E->getValueKind() == VK_RValue);
12646 assert(E->getObjectKind() == OK_Ordinary);
12650 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12651 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12653 E->setType(VD->getType());
12655 assert(E->getValueKind() == VK_RValue);
12656 if (S.getLangOpts().CPlusPlus &&
12657 !(isa<CXXMethodDecl>(VD) &&
12658 cast<CXXMethodDecl>(VD)->isInstance()))
12659 E->setValueKind(VK_LValue);
12664 ExprResult VisitMemberExpr(MemberExpr *E) {
12665 return resolveDecl(E, E->getMemberDecl());
12668 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12669 return resolveDecl(E, E->getDecl());
12674 /// Given a function expression of unknown-any type, try to rebuild it
12675 /// to have a function type.
12676 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12677 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12678 if (Result.isInvalid()) return ExprError();
12679 return S.DefaultFunctionArrayConversion(Result.take());
12683 /// A visitor for rebuilding an expression of type __unknown_anytype
12684 /// into one which resolves the type directly on the referring
12685 /// expression. Strict preservation of the original source
12686 /// structure is not a goal.
12687 struct RebuildUnknownAnyExpr
12688 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12692 /// The current destination type.
12695 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12696 : S(S), DestType(CastType) {}
12698 ExprResult VisitStmt(Stmt *S) {
12699 llvm_unreachable("unexpected statement!");
12702 ExprResult VisitExpr(Expr *E) {
12703 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12704 << E->getSourceRange();
12705 return ExprError();
12708 ExprResult VisitCallExpr(CallExpr *E);
12709 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12711 /// Rebuild an expression which simply semantically wraps another
12712 /// expression which it shares the type and value kind of.
12713 template <class T> ExprResult rebuildSugarExpr(T *E) {
12714 ExprResult SubResult = Visit(E->getSubExpr());
12715 if (SubResult.isInvalid()) return ExprError();
12716 Expr *SubExpr = SubResult.take();
12717 E->setSubExpr(SubExpr);
12718 E->setType(SubExpr->getType());
12719 E->setValueKind(SubExpr->getValueKind());
12720 assert(E->getObjectKind() == OK_Ordinary);
12724 ExprResult VisitParenExpr(ParenExpr *E) {
12725 return rebuildSugarExpr(E);
12728 ExprResult VisitUnaryExtension(UnaryOperator *E) {
12729 return rebuildSugarExpr(E);
12732 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12733 const PointerType *Ptr = DestType->getAs<PointerType>();
12735 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12736 << E->getSourceRange();
12737 return ExprError();
12739 assert(E->getValueKind() == VK_RValue);
12740 assert(E->getObjectKind() == OK_Ordinary);
12741 E->setType(DestType);
12743 // Build the sub-expression as if it were an object of the pointee type.
12744 DestType = Ptr->getPointeeType();
12745 ExprResult SubResult = Visit(E->getSubExpr());
12746 if (SubResult.isInvalid()) return ExprError();
12747 E->setSubExpr(SubResult.take());
12751 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12753 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12755 ExprResult VisitMemberExpr(MemberExpr *E) {
12756 return resolveDecl(E, E->getMemberDecl());
12759 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12760 return resolveDecl(E, E->getDecl());
12765 /// Rebuilds a call expression which yielded __unknown_anytype.
12766 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12767 Expr *CalleeExpr = E->getCallee();
12771 FK_FunctionPointer,
12776 QualType CalleeType = CalleeExpr->getType();
12777 if (CalleeType == S.Context.BoundMemberTy) {
12778 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12779 Kind = FK_MemberFunction;
12780 CalleeType = Expr::findBoundMemberType(CalleeExpr);
12781 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12782 CalleeType = Ptr->getPointeeType();
12783 Kind = FK_FunctionPointer;
12785 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12786 Kind = FK_BlockPointer;
12788 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12790 // Verify that this is a legal result type of a function.
12791 if (DestType->isArrayType() || DestType->isFunctionType()) {
12792 unsigned diagID = diag::err_func_returning_array_function;
12793 if (Kind == FK_BlockPointer)
12794 diagID = diag::err_block_returning_array_function;
12796 S.Diag(E->getExprLoc(), diagID)
12797 << DestType->isFunctionType() << DestType;
12798 return ExprError();
12801 // Otherwise, go ahead and set DestType as the call's result.
12802 E->setType(DestType.getNonLValueExprType(S.Context));
12803 E->setValueKind(Expr::getValueKindForType(DestType));
12804 assert(E->getObjectKind() == OK_Ordinary);
12806 // Rebuild the function type, replacing the result type with DestType.
12807 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12809 // __unknown_anytype(...) is a special case used by the debugger when
12810 // it has no idea what a function's signature is.
12812 // We want to build this call essentially under the K&R
12813 // unprototyped rules, but making a FunctionNoProtoType in C++
12814 // would foul up all sorts of assumptions. However, we cannot
12815 // simply pass all arguments as variadic arguments, nor can we
12816 // portably just call the function under a non-variadic type; see
12817 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12818 // However, it turns out that in practice it is generally safe to
12819 // call a function declared as "A foo(B,C,D);" under the prototype
12820 // "A foo(B,C,D,...);". The only known exception is with the
12821 // Windows ABI, where any variadic function is implicitly cdecl
12822 // regardless of its normal CC. Therefore we change the parameter
12823 // types to match the types of the arguments.
12825 // This is a hack, but it is far superior to moving the
12826 // corresponding target-specific code from IR-gen to Sema/AST.
12828 ArrayRef<QualType> ParamTypes = Proto->getArgTypes();
12829 SmallVector<QualType, 8> ArgTypes;
12830 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12831 ArgTypes.reserve(E->getNumArgs());
12832 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12833 Expr *Arg = E->getArg(i);
12834 QualType ArgType = Arg->getType();
12835 if (E->isLValue()) {
12836 ArgType = S.Context.getLValueReferenceType(ArgType);
12837 } else if (E->isXValue()) {
12838 ArgType = S.Context.getRValueReferenceType(ArgType);
12840 ArgTypes.push_back(ArgType);
12842 ParamTypes = ArgTypes;
12844 DestType = S.Context.getFunctionType(DestType, ParamTypes,
12845 Proto->getExtProtoInfo());
12847 DestType = S.Context.getFunctionNoProtoType(DestType,
12848 FnType->getExtInfo());
12851 // Rebuild the appropriate pointer-to-function type.
12853 case FK_MemberFunction:
12857 case FK_FunctionPointer:
12858 DestType = S.Context.getPointerType(DestType);
12861 case FK_BlockPointer:
12862 DestType = S.Context.getBlockPointerType(DestType);
12866 // Finally, we can recurse.
12867 ExprResult CalleeResult = Visit(CalleeExpr);
12868 if (!CalleeResult.isUsable()) return ExprError();
12869 E->setCallee(CalleeResult.take());
12871 // Bind a temporary if necessary.
12872 return S.MaybeBindToTemporary(E);
12875 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12876 // Verify that this is a legal result type of a call.
12877 if (DestType->isArrayType() || DestType->isFunctionType()) {
12878 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12879 << DestType->isFunctionType() << DestType;
12880 return ExprError();
12883 // Rewrite the method result type if available.
12884 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12885 assert(Method->getResultType() == S.Context.UnknownAnyTy);
12886 Method->setResultType(DestType);
12889 // Change the type of the message.
12890 E->setType(DestType.getNonReferenceType());
12891 E->setValueKind(Expr::getValueKindForType(DestType));
12893 return S.MaybeBindToTemporary(E);
12896 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12897 // The only case we should ever see here is a function-to-pointer decay.
12898 if (E->getCastKind() == CK_FunctionToPointerDecay) {
12899 assert(E->getValueKind() == VK_RValue);
12900 assert(E->getObjectKind() == OK_Ordinary);
12902 E->setType(DestType);
12904 // Rebuild the sub-expression as the pointee (function) type.
12905 DestType = DestType->castAs<PointerType>()->getPointeeType();
12907 ExprResult Result = Visit(E->getSubExpr());
12908 if (!Result.isUsable()) return ExprError();
12910 E->setSubExpr(Result.take());
12912 } else if (E->getCastKind() == CK_LValueToRValue) {
12913 assert(E->getValueKind() == VK_RValue);
12914 assert(E->getObjectKind() == OK_Ordinary);
12916 assert(isa<BlockPointerType>(E->getType()));
12918 E->setType(DestType);
12920 // The sub-expression has to be a lvalue reference, so rebuild it as such.
12921 DestType = S.Context.getLValueReferenceType(DestType);
12923 ExprResult Result = Visit(E->getSubExpr());
12924 if (!Result.isUsable()) return ExprError();
12926 E->setSubExpr(Result.take());
12929 llvm_unreachable("Unhandled cast type!");
12933 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12934 ExprValueKind ValueKind = VK_LValue;
12935 QualType Type = DestType;
12937 // We know how to make this work for certain kinds of decls:
12940 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12941 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12942 DestType = Ptr->getPointeeType();
12943 ExprResult Result = resolveDecl(E, VD);
12944 if (Result.isInvalid()) return ExprError();
12945 return S.ImpCastExprToType(Result.take(), Type,
12946 CK_FunctionToPointerDecay, VK_RValue);
12949 if (!Type->isFunctionType()) {
12950 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12951 << VD << E->getSourceRange();
12952 return ExprError();
12955 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12956 if (MD->isInstance()) {
12957 ValueKind = VK_RValue;
12958 Type = S.Context.BoundMemberTy;
12961 // Function references aren't l-values in C.
12962 if (!S.getLangOpts().CPlusPlus)
12963 ValueKind = VK_RValue;
12966 } else if (isa<VarDecl>(VD)) {
12967 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12968 Type = RefTy->getPointeeType();
12969 } else if (Type->isFunctionType()) {
12970 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12971 << VD << E->getSourceRange();
12972 return ExprError();
12977 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12978 << VD << E->getSourceRange();
12979 return ExprError();
12982 // Modifying the declaration like this is friendly to IR-gen but
12983 // also really dangerous.
12984 VD->setType(DestType);
12986 E->setValueKind(ValueKind);
12990 /// Check a cast of an unknown-any type. We intentionally only
12991 /// trigger this for C-style casts.
12992 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12993 Expr *CastExpr, CastKind &CastKind,
12994 ExprValueKind &VK, CXXCastPath &Path) {
12995 // Rewrite the casted expression from scratch.
12996 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12997 if (!result.isUsable()) return ExprError();
12999 CastExpr = result.take();
13000 VK = CastExpr->getValueKind();
13001 CastKind = CK_NoOp;
13006 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13007 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13010 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13011 Expr *arg, QualType ¶mType) {
13012 // If the syntactic form of the argument is not an explicit cast of
13013 // any sort, just do default argument promotion.
13014 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13016 ExprResult result = DefaultArgumentPromotion(arg);
13017 if (result.isInvalid()) return ExprError();
13018 paramType = result.get()->getType();
13022 // Otherwise, use the type that was written in the explicit cast.
13023 assert(!arg->hasPlaceholderType());
13024 paramType = castArg->getTypeAsWritten();
13026 // Copy-initialize a parameter of that type.
13027 InitializedEntity entity =
13028 InitializedEntity::InitializeParameter(Context, paramType,
13029 /*consumed*/ false);
13030 return PerformCopyInitialization(entity, callLoc, Owned(arg));
13033 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13035 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13037 E = E->IgnoreParenImpCasts();
13038 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13039 E = call->getCallee();
13040 diagID = diag::err_uncasted_call_of_unknown_any;
13046 SourceLocation loc;
13048 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13049 loc = ref->getLocation();
13050 d = ref->getDecl();
13051 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13052 loc = mem->getMemberLoc();
13053 d = mem->getMemberDecl();
13054 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13055 diagID = diag::err_uncasted_call_of_unknown_any;
13056 loc = msg->getSelectorStartLoc();
13057 d = msg->getMethodDecl();
13059 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13060 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13061 << orig->getSourceRange();
13062 return ExprError();
13065 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13066 << E->getSourceRange();
13067 return ExprError();
13070 S.Diag(loc, diagID) << d << orig->getSourceRange();
13072 // Never recoverable.
13073 return ExprError();
13076 /// Check for operands with placeholder types and complain if found.
13077 /// Returns true if there was an error and no recovery was possible.
13078 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13079 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13080 if (!placeholderType) return Owned(E);
13082 switch (placeholderType->getKind()) {
13084 // Overloaded expressions.
13085 case BuiltinType::Overload: {
13086 // Try to resolve a single function template specialization.
13087 // This is obligatory.
13088 ExprResult result = Owned(E);
13089 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13092 // If that failed, try to recover with a call.
13094 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13095 /*complain*/ true);
13100 // Bound member functions.
13101 case BuiltinType::BoundMember: {
13102 ExprResult result = Owned(E);
13103 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13104 /*complain*/ true);
13108 // ARC unbridged casts.
13109 case BuiltinType::ARCUnbridgedCast: {
13110 Expr *realCast = stripARCUnbridgedCast(E);
13111 diagnoseARCUnbridgedCast(realCast);
13112 return Owned(realCast);
13115 // Expressions of unknown type.
13116 case BuiltinType::UnknownAny:
13117 return diagnoseUnknownAnyExpr(*this, E);
13120 case BuiltinType::PseudoObject:
13121 return checkPseudoObjectRValue(E);
13123 case BuiltinType::BuiltinFn:
13124 Diag(E->getLocStart(), diag::err_builtin_fn_use);
13125 return ExprError();
13127 // Everything else should be impossible.
13128 #define BUILTIN_TYPE(Id, SingletonId) \
13129 case BuiltinType::Id:
13130 #define PLACEHOLDER_TYPE(Id, SingletonId)
13131 #include "clang/AST/BuiltinTypes.def"
13135 llvm_unreachable("invalid placeholder type!");
13138 bool Sema::CheckCaseExpression(Expr *E) {
13139 if (E->isTypeDependent())
13141 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13142 return E->getType()->isIntegralOrEnumerationType();
13146 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13148 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13149 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13150 "Unknown Objective-C Boolean value!");
13151 QualType BoolT = Context.ObjCBuiltinBoolTy;
13152 if (!Context.getBOOLDecl()) {
13153 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13154 Sema::LookupOrdinaryName);
13155 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13156 NamedDecl *ND = Result.getFoundDecl();
13157 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13158 Context.setBOOLDecl(TD);
13161 if (Context.getBOOLDecl())
13162 BoolT = Context.getBOOLType();
13163 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,