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 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/Basic/PartialDiagnostic.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Lex/LiteralSupport.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Parse/DeclSpec.h"
26 #include "clang/Parse/Designator.h"
27 #include "clang/Parse/Scope.h"
28 using namespace clang;
31 /// \brief Determine whether the use of this declaration is valid, and
32 /// emit any corresponding diagnostics.
34 /// This routine diagnoses various problems with referencing
35 /// declarations that can occur when using a declaration. For example,
36 /// it might warn if a deprecated or unavailable declaration is being
37 /// used, or produce an error (and return true) if a C++0x deleted
38 /// function is being used.
40 /// If IgnoreDeprecated is set to true, this should not want about deprecated
43 /// \returns true if there was an error (this declaration cannot be
44 /// referenced), false otherwise.
46 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
47 // See if the decl is deprecated.
48 if (D->getAttr<DeprecatedAttr>()) {
49 EmitDeprecationWarning(D, Loc);
52 // See if the decl is unavailable
53 if (D->getAttr<UnavailableAttr>()) {
54 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
55 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
58 // See if this is a deleted function.
59 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60 if (FD->isDeleted()) {
61 Diag(Loc, diag::err_deleted_function_use);
62 Diag(D->getLocation(), diag::note_unavailable_here) << true;
70 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
71 /// (and other functions in future), which have been declared with sentinel
72 /// attribute. It warns if call does not have the sentinel argument.
74 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
75 Expr **Args, unsigned NumArgs) {
76 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
79 int sentinelPos = attr->getSentinel();
80 int nullPos = attr->getNullPos();
82 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
83 // base class. Then we won't be needing two versions of the same code.
85 bool warnNotEnoughArgs = false;
87 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
88 // skip over named parameters.
89 ObjCMethodDecl::param_iterator P, E = MD->param_end();
90 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
96 warnNotEnoughArgs = (P != E || i >= NumArgs);
98 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
99 // skip over named parameters.
100 ObjCMethodDecl::param_iterator P, E = FD->param_end();
101 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
107 warnNotEnoughArgs = (P != E || i >= NumArgs);
108 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
109 // block or function pointer call.
110 QualType Ty = V->getType();
111 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
112 const FunctionType *FT = Ty->isFunctionPointerType()
113 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
114 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
115 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
116 unsigned NumArgsInProto = Proto->getNumArgs();
118 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
124 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
126 if (Ty->isBlockPointerType())
133 if (warnNotEnoughArgs) {
134 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
135 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
139 while (sentinelPos > 0 && i < NumArgs-1) {
143 if (sentinelPos > 0) {
144 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
145 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
148 while (i < NumArgs-1) {
152 Expr *sentinelExpr = Args[sentinel];
153 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
154 !sentinelExpr->isNullPointerConstant(Context,
155 Expr::NPC_ValueDependentIsNull))) {
156 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
162 SourceRange Sema::getExprRange(ExprTy *E) const {
163 Expr *Ex = (Expr *)E;
164 return Ex? Ex->getSourceRange() : SourceRange();
167 //===----------------------------------------------------------------------===//
168 // Standard Promotions and Conversions
169 //===----------------------------------------------------------------------===//
171 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
172 void Sema::DefaultFunctionArrayConversion(Expr *&E) {
173 QualType Ty = E->getType();
174 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
176 if (Ty->isFunctionType())
177 ImpCastExprToType(E, Context.getPointerType(Ty),
178 CastExpr::CK_FunctionToPointerDecay);
179 else if (Ty->isArrayType()) {
180 // In C90 mode, arrays only promote to pointers if the array expression is
181 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
182 // type 'array of type' is converted to an expression that has type 'pointer
183 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
184 // that has type 'array of type' ...". The relevant change is "an lvalue"
185 // (C90) to "an expression" (C99).
188 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
189 // T" can be converted to an rvalue of type "pointer to T".
191 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
192 E->isLvalue(Context) == Expr::LV_Valid)
193 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
194 CastExpr::CK_ArrayToPointerDecay);
198 /// UsualUnaryConversions - Performs various conversions that are common to most
199 /// operators (C99 6.3). The conversions of array and function types are
200 /// sometimes surpressed. For example, the array->pointer conversion doesn't
201 /// apply if the array is an argument to the sizeof or address (&) operators.
202 /// In these instances, this routine should *not* be called.
203 Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
204 QualType Ty = Expr->getType();
205 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
209 // The following may be used in an expression wherever an int or
210 // unsigned int may be used:
211 // - an object or expression with an integer type whose integer
212 // conversion rank is less than or equal to the rank of int
214 // - A bit-field of type _Bool, int, signed int, or unsigned int.
216 // If an int can represent all values of the original type, the
217 // value is converted to an int; otherwise, it is converted to an
218 // unsigned int. These are called the integer promotions. All
219 // other types are unchanged by the integer promotions.
220 QualType PTy = Context.isPromotableBitField(Expr);
222 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
225 if (Ty->isPromotableIntegerType()) {
226 QualType PT = Context.getPromotedIntegerType(Ty);
227 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
231 DefaultFunctionArrayConversion(Expr);
235 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
236 /// do not have a prototype. Arguments that have type float are promoted to
237 /// double. All other argument types are converted by UsualUnaryConversions().
238 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
239 QualType Ty = Expr->getType();
240 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
242 // If this is a 'float' (CVR qualified or typedef) promote to double.
243 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
244 if (BT->getKind() == BuiltinType::Float)
245 return ImpCastExprToType(Expr, Context.DoubleTy,
246 CastExpr::CK_FloatingCast);
248 UsualUnaryConversions(Expr);
251 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
252 /// will warn if the resulting type is not a POD type, and rejects ObjC
253 /// interfaces passed by value. This returns true if the argument type is
254 /// completely illegal.
255 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
256 DefaultArgumentPromotion(Expr);
258 if (Expr->getType()->isObjCInterfaceType()) {
259 Diag(Expr->getLocStart(),
260 diag::err_cannot_pass_objc_interface_to_vararg)
261 << Expr->getType() << CT;
265 if (!Expr->getType()->isPODType())
266 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
267 << Expr->getType() << CT;
273 /// UsualArithmeticConversions - Performs various conversions that are common to
274 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
275 /// routine returns the first non-arithmetic type found. The client is
276 /// responsible for emitting appropriate error diagnostics.
277 /// FIXME: verify the conversion rules for "complex int" are consistent with
279 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
282 UsualUnaryConversions(lhsExpr);
284 UsualUnaryConversions(rhsExpr);
286 // For conversion purposes, we ignore any qualifiers.
287 // For example, "const float" and "float" are equivalent.
289 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
291 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
293 // If both types are identical, no conversion is needed.
297 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
298 // The caller can deal with this (e.g. pointer + int).
299 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
302 // Perform bitfield promotions.
303 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
304 if (!LHSBitfieldPromoteTy.isNull())
305 lhs = LHSBitfieldPromoteTy;
306 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
307 if (!RHSBitfieldPromoteTy.isNull())
308 rhs = RHSBitfieldPromoteTy;
310 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
312 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
313 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
317 //===----------------------------------------------------------------------===//
318 // Semantic Analysis for various Expression Types
319 //===----------------------------------------------------------------------===//
322 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
323 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
324 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
325 /// multiple tokens. However, the common case is that StringToks points to one
328 Action::OwningExprResult
329 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
330 assert(NumStringToks && "Must have at least one string!");
332 StringLiteralParser Literal(StringToks, NumStringToks, PP);
333 if (Literal.hadError)
336 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
337 for (unsigned i = 0; i != NumStringToks; ++i)
338 StringTokLocs.push_back(StringToks[i].getLocation());
340 QualType StrTy = Context.CharTy;
341 if (Literal.AnyWide) StrTy = Context.getWCharType();
342 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
344 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
345 if (getLangOptions().CPlusPlus)
348 // Get an array type for the string, according to C99 6.4.5. This includes
349 // the nul terminator character as well as the string length for pascal
351 StrTy = Context.getConstantArrayType(StrTy,
352 llvm::APInt(32, Literal.GetNumStringChars()+1),
353 ArrayType::Normal, 0);
355 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
356 return Owned(StringLiteral::Create(Context, Literal.GetString(),
357 Literal.GetStringLength(),
358 Literal.AnyWide, StrTy,
360 StringTokLocs.size()));
363 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of
364 /// CurBlock to VD should cause it to be snapshotted (as we do for auto
365 /// variables defined outside the block) or false if this is not needed (e.g.
366 /// for values inside the block or for globals).
368 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
371 static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
373 // If the value is defined inside the block, we couldn't snapshot it even if
375 if (CurBlock->TheDecl == VD->getDeclContext())
378 // If this is an enum constant or function, it is constant, don't snapshot.
379 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
382 // If this is a reference to an extern, static, or global variable, no need to
384 // FIXME: What about 'const' variables in C++?
385 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
386 if (!Var->hasLocalStorage())
389 // Blocks that have these can't be constant.
390 CurBlock->hasBlockDeclRefExprs = true;
392 // If we have nested blocks, the decl may be declared in an outer block (in
393 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
394 // be defined outside all of the current blocks (in which case the blocks do
395 // all get the bit). Walk the nesting chain.
396 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
397 NextBlock = NextBlock->PrevBlockInfo) {
398 // If we found the defining block for the variable, don't mark the block as
399 // having a reference outside it.
400 if (NextBlock->TheDecl == VD->getDeclContext())
403 // Otherwise, the DeclRef from the inner block causes the outer one to need
404 // a snapshot as well.
405 NextBlock->hasBlockDeclRefExprs = true;
413 /// BuildDeclRefExpr - Build a DeclRefExpr.
414 Sema::OwningExprResult
415 Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
416 bool TypeDependent, bool ValueDependent,
417 const CXXScopeSpec *SS) {
418 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
420 diag::err_auto_variable_cannot_appear_in_own_initializer)
425 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
426 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
427 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
428 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
429 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
430 << D->getIdentifier() << FD->getDeclName();
431 Diag(D->getLocation(), diag::note_local_variable_declared_here)
432 << D->getIdentifier();
439 MarkDeclarationReferenced(Loc, D);
441 return Owned(DeclRefExpr::Create(Context,
442 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
443 SS? SS->getRange() : SourceRange(),
445 Ty, TypeDependent, ValueDependent));
448 /// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
449 /// variable corresponding to the anonymous union or struct whose type
451 static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
452 RecordDecl *Record) {
453 assert(Record->isAnonymousStructOrUnion() &&
454 "Record must be an anonymous struct or union!");
456 // FIXME: Once Decls are directly linked together, this will be an O(1)
457 // operation rather than a slow walk through DeclContext's vector (which
458 // itself will be eliminated). DeclGroups might make this even better.
459 DeclContext *Ctx = Record->getDeclContext();
460 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
461 DEnd = Ctx->decls_end();
464 // The object for the anonymous struct/union directly
465 // follows its type in the list of declarations.
467 assert(D != DEnd && "Missing object for anonymous record");
468 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
473 assert(false && "Missing object for anonymous record");
477 /// \brief Given a field that represents a member of an anonymous
478 /// struct/union, build the path from that field's context to the
481 /// Construct the sequence of field member references we'll have to
482 /// perform to get to the field in the anonymous union/struct. The
483 /// list of members is built from the field outward, so traverse it
484 /// backwards to go from an object in the current context to the field
487 /// \returns The variable from which the field access should begin,
488 /// for an anonymous struct/union that is not a member of another
489 /// class. Otherwise, returns NULL.
490 VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
491 llvm::SmallVectorImpl<FieldDecl *> &Path) {
492 assert(Field->getDeclContext()->isRecord() &&
493 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
494 && "Field must be stored inside an anonymous struct or union");
496 Path.push_back(Field);
497 VarDecl *BaseObject = 0;
498 DeclContext *Ctx = Field->getDeclContext();
500 RecordDecl *Record = cast<RecordDecl>(Ctx);
501 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
502 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
503 Path.push_back(AnonField);
505 BaseObject = cast<VarDecl>(AnonObject);
508 Ctx = Ctx->getParent();
509 } while (Ctx->isRecord() &&
510 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
515 Sema::OwningExprResult
516 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
518 Expr *BaseObjectExpr,
519 SourceLocation OpLoc) {
520 llvm::SmallVector<FieldDecl *, 4> AnonFields;
521 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
524 // Build the expression that refers to the base object, from
525 // which we will build a sequence of member references to each
526 // of the anonymous union objects and, eventually, the field we
527 // found via name lookup.
528 bool BaseObjectIsPointer = false;
529 Qualifiers BaseQuals;
531 // BaseObject is an anonymous struct/union variable (and is,
532 // therefore, not part of another non-anonymous record).
533 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
534 MarkDeclarationReferenced(Loc, BaseObject);
535 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
538 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
539 } else if (BaseObjectExpr) {
540 // The caller provided the base object expression. Determine
541 // whether its a pointer and whether it adds any qualifiers to the
542 // anonymous struct/union fields we're looking into.
543 QualType ObjectType = BaseObjectExpr->getType();
544 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
545 BaseObjectIsPointer = true;
546 ObjectType = ObjectPtr->getPointeeType();
549 = Context.getCanonicalType(ObjectType).getQualifiers();
551 // We've found a member of an anonymous struct/union that is
552 // inside a non-anonymous struct/union, so in a well-formed
553 // program our base object expression is "this".
554 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
555 if (!MD->isStatic()) {
556 QualType AnonFieldType
557 = Context.getTagDeclType(
558 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
559 QualType ThisType = Context.getTagDeclType(MD->getParent());
560 if ((Context.getCanonicalType(AnonFieldType)
561 == Context.getCanonicalType(ThisType)) ||
562 IsDerivedFrom(ThisType, AnonFieldType)) {
563 // Our base object expression is "this".
564 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
565 MD->getThisType(Context));
566 BaseObjectIsPointer = true;
569 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
570 << Field->getDeclName());
572 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
576 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
577 << Field->getDeclName());
580 // Build the implicit member references to the field of the
581 // anonymous struct/union.
582 Expr *Result = BaseObjectExpr;
583 Qualifiers ResultQuals = BaseQuals;
584 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
585 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
587 QualType MemberType = (*FI)->getType();
588 Qualifiers MemberTypeQuals =
589 Context.getCanonicalType(MemberType).getQualifiers();
591 // CVR attributes from the base are picked up by members,
592 // except that 'mutable' members don't pick up 'const'.
593 if ((*FI)->isMutable())
594 ResultQuals.removeConst();
596 // GC attributes are never picked up by members.
597 ResultQuals.removeObjCGCAttr();
599 // TR 18037 does not allow fields to be declared with address spaces.
600 assert(!MemberTypeQuals.hasAddressSpace());
602 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
603 if (NewQuals != MemberTypeQuals)
604 MemberType = Context.getQualifiedType(MemberType, NewQuals);
606 MarkDeclarationReferenced(Loc, *FI);
607 // FIXME: Might this end up being a qualified name?
608 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
610 BaseObjectIsPointer = false;
611 ResultQuals = NewQuals;
614 return Owned(Result);
617 Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
618 const CXXScopeSpec &SS,
620 bool HasTrailingLParen,
621 bool IsAddressOfOperand) {
622 if (Name.getKind() == UnqualifiedId::IK_TemplateId) {
623 ASTTemplateArgsPtr TemplateArgsPtr(*this,
624 Name.TemplateId->getTemplateArgs(),
625 Name.TemplateId->getTemplateArgIsType(),
626 Name.TemplateId->NumArgs);
627 return ActOnTemplateIdExpr(SS,
628 TemplateTy::make(Name.TemplateId->Template),
629 Name.TemplateId->TemplateNameLoc,
630 Name.TemplateId->LAngleLoc,
632 Name.TemplateId->getTemplateArgLocations(),
633 Name.TemplateId->RAngleLoc);
636 // FIXME: We lose a bunch of source information by doing this. Later,
637 // we'll want to merge ActOnDeclarationNameExpr's logic into
638 // ActOnIdExpression.
639 return ActOnDeclarationNameExpr(S,
641 GetNameFromUnqualifiedId(Name),
647 /// ActOnDeclarationNameExpr - The parser has read some kind of name
648 /// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
649 /// performs lookup on that name and returns an expression that refers
650 /// to that name. This routine isn't directly called from the parser,
651 /// because the parser doesn't know about DeclarationName. Rather,
652 /// this routine is called by ActOnIdExpression, which contains a
653 /// parsed UnqualifiedId.
655 /// HasTrailingLParen indicates whether this identifier is used in a
656 /// function call context. LookupCtx is only used for a C++
657 /// qualified-id (foo::bar) to indicate the class or namespace that
658 /// the identifier must be a member of.
660 /// isAddressOfOperand means that this expression is the direct operand
661 /// of an address-of operator. This matters because this is the only
662 /// situation where a qualified name referencing a non-static member may
663 /// appear outside a member function of this class.
664 Sema::OwningExprResult
665 Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
666 DeclarationName Name, bool HasTrailingLParen,
667 const CXXScopeSpec *SS,
668 bool isAddressOfOperand) {
669 // Could be enum-constant, value decl, instance variable, etc.
670 if (SS && SS->isInvalid())
673 // C++ [temp.dep.expr]p3:
674 // An id-expression is type-dependent if it contains:
675 // -- a nested-name-specifier that contains a class-name that
676 // names a dependent type.
677 // FIXME: Member of the current instantiation.
678 if (SS && isDependentScopeSpecifier(*SS)) {
679 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
681 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
682 isAddressOfOperand));
686 LookupParsedName(Lookup, S, SS, Name, LookupOrdinaryName, false, true, Loc);
688 if (Lookup.isAmbiguous()) {
689 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
690 SS && SS->isSet() ? SS->getRange()
695 NamedDecl *D = Lookup.getAsSingleDecl(Context);
697 // If this reference is in an Objective-C method, then ivar lookup happens as
699 IdentifierInfo *II = Name.getAsIdentifierInfo();
700 if (II && getCurMethodDecl()) {
701 // There are two cases to handle here. 1) scoped lookup could have failed,
702 // in which case we should look for an ivar. 2) scoped lookup could have
703 // found a decl, but that decl is outside the current instance method (i.e.
704 // a global variable). In these two cases, we do a lookup for an ivar with
705 // this name, if the lookup sucedes, we replace it our current decl.
706 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
707 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
708 ObjCInterfaceDecl *ClassDeclared;
709 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
710 // Check if referencing a field with __attribute__((deprecated)).
711 if (DiagnoseUseOfDecl(IV, Loc))
714 // If we're referencing an invalid decl, just return this as a silent
715 // error node. The error diagnostic was already emitted on the decl.
716 if (IV->isInvalidDecl())
719 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
720 // If a class method attemps to use a free standing ivar, this is
722 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
723 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
724 << IV->getDeclName());
725 // If a class method uses a global variable, even if an ivar with
726 // same name exists, use the global.
728 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
729 ClassDeclared != IFace)
730 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
731 // FIXME: This should use a new expr for a direct reference, don't
732 // turn this into Self->ivar, just return a BareIVarExpr or something.
733 IdentifierInfo &II = Context.Idents.get("self");
734 UnqualifiedId SelfName;
735 SelfName.setIdentifier(&II, SourceLocation());
736 CXXScopeSpec SelfScopeSpec;
737 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
738 SelfName, false, false);
739 MarkDeclarationReferenced(Loc, IV);
740 return Owned(new (Context)
741 ObjCIvarRefExpr(IV, IV->getType(), Loc,
742 SelfExpr.takeAs<Expr>(), true, true));
745 } else if (getCurMethodDecl()->isInstanceMethod()) {
746 // We should warn if a local variable hides an ivar.
747 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
748 ObjCInterfaceDecl *ClassDeclared;
749 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
750 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
751 IFace == ClassDeclared)
752 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
755 // Needed to implement property "super.method" notation.
756 if (D == 0 && II->isStr("super")) {
759 if (getCurMethodDecl()->isInstanceMethod())
760 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
761 getCurMethodDecl()->getClassInterface()));
763 T = Context.getObjCClassType();
764 return Owned(new (Context) ObjCSuperExpr(Loc, T));
768 // Determine whether this name might be a candidate for
769 // argument-dependent lookup.
770 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
774 // We've seen something of the form
778 // and we did not find any entity by the name
779 // "identifier". However, this identifier is still subject to
780 // argument-dependent lookup, so keep track of the name.
781 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
787 // Otherwise, this could be an implicitly declared function reference (legal
788 // in C90, extension in C99).
789 if (HasTrailingLParen && II &&
790 !getLangOptions().CPlusPlus) // Not in C++.
791 D = ImplicitlyDefineFunction(Loc, *II, S);
793 // If this name wasn't predeclared and if this is not a function call,
794 // diagnose the problem.
795 if (SS && !SS->isEmpty())
796 return ExprError(Diag(Loc, diag::err_no_member)
797 << Name << computeDeclContext(*SS, false)
799 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
800 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
801 return ExprError(Diag(Loc, diag::err_undeclared_use)
802 << Name.getAsString());
804 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
808 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
809 // Warn about constructs like:
810 // if (void *X = foo()) { ... } else { X }.
811 // In the else block, the pointer is always false.
813 // FIXME: In a template instantiation, we don't have scope
814 // information to check this property.
815 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
818 if (CheckS->isWithinElse() &&
819 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
820 if (Var->getType()->isBooleanType())
821 ExprError(Diag(Loc, diag::warn_value_always_false)
822 << Var->getDeclName());
824 ExprError(Diag(Loc, diag::warn_value_always_zero)
825 << Var->getDeclName());
829 // Move up one more control parent to check again.
830 CheckS = CheckS->getControlParent();
832 CheckS = CheckS->getParent();
835 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
836 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
837 // C99 DR 316 says that, if a function type comes from a
838 // function definition (without a prototype), that type is only
839 // used for checking compatibility. Therefore, when referencing
840 // the function, we pretend that we don't have the full function
842 if (DiagnoseUseOfDecl(Func, Loc))
845 QualType T = Func->getType();
846 QualType NoProtoType = T;
847 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
848 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
849 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
853 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
855 /// \brief Cast member's object to its own class if necessary.
857 Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
858 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
859 if (CXXRecordDecl *RD =
860 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
862 Context.getCanonicalType(Context.getTypeDeclType(RD));
863 if (DestType->isDependentType() || From->getType()->isDependentType())
865 QualType FromRecordType = From->getType();
866 QualType DestRecordType = DestType;
867 if (FromRecordType->getAs<PointerType>()) {
868 DestType = Context.getPointerType(DestType);
869 FromRecordType = FromRecordType->getPointeeType();
871 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
872 CheckDerivedToBaseConversion(FromRecordType,
874 From->getSourceRange().getBegin(),
875 From->getSourceRange()))
877 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
883 /// \brief Build a MemberExpr AST node.
884 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
885 const CXXScopeSpec *SS, NamedDecl *Member,
886 SourceLocation Loc, QualType Ty) {
887 if (SS && SS->isSet())
888 return MemberExpr::Create(C, Base, isArrow,
889 (NestedNameSpecifier *)SS->getScopeRep(),
890 SS->getRange(), Member, Loc,
891 // FIXME: Explicit template argument lists
892 false, SourceLocation(), 0, 0, SourceLocation(),
895 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
898 /// \brief Complete semantic analysis for a reference to the given declaration.
899 Sema::OwningExprResult
900 Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
901 bool HasTrailingLParen,
902 const CXXScopeSpec *SS,
903 bool isAddressOfOperand) {
904 assert(D && "Cannot refer to a NULL declaration");
905 DeclarationName Name = D->getDeclName();
907 // If this is an expression of the form &Class::member, don't build an
908 // implicit member ref, because we want a pointer to the member in general,
909 // not any specific instance's member.
910 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
911 DeclContext *DC = computeDeclContext(*SS);
912 if (D && isa<CXXRecordDecl>(DC)) {
914 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
915 DType = FD->getType().getNonReferenceType();
916 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
917 DType = Method->getType();
918 } else if (isa<OverloadedFunctionDecl>(D)) {
919 DType = Context.OverloadTy;
921 // Could be an inner type. That's diagnosed below, so ignore it here.
922 if (!DType.isNull()) {
923 // The pointer is type- and value-dependent if it points into something
925 bool Dependent = DC->isDependentContext();
926 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
931 // We may have found a field within an anonymous union or struct
932 // (C++ [class.union]).
933 // FIXME: This needs to happen post-isImplicitMemberReference?
934 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
935 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
936 return BuildAnonymousStructUnionMemberReference(Loc, FD);
938 // Cope with an implicit member access in a C++ non-static member function.
939 QualType ThisType, MemberType;
940 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
941 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
942 MarkDeclarationReferenced(Loc, D);
943 if (PerformObjectMemberConversion(This, D))
946 bool ShouldCheckUse = true;
947 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
948 // Don't diagnose the use of a virtual member function unless it's
949 // explicitly qualified.
950 if (MD->isVirtual() && (!SS || !SS->isSet()))
951 ShouldCheckUse = false;
954 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
956 return Owned(BuildMemberExpr(Context, This, true, SS, D,
960 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
961 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
963 // "invalid use of member 'x' in static member function"
964 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
965 << FD->getDeclName());
968 // Any other ways we could have found the field in a well-formed
969 // program would have been turned into implicit member expressions
971 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
972 << FD->getDeclName());
975 if (isa<TypedefDecl>(D))
976 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
977 if (isa<ObjCInterfaceDecl>(D))
978 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
979 if (isa<NamespaceDecl>(D))
980 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
982 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
983 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
984 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
986 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
987 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
989 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
990 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
991 /*TypeDependent=*/true,
992 /*ValueDependent=*/true, SS);
994 ValueDecl *VD = cast<ValueDecl>(D);
996 // Check whether this declaration can be used. Note that we suppress
997 // this check when we're going to perform argument-dependent lookup
998 // on this function name, because this might not be the function
999 // that overload resolution actually selects.
1000 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1002 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1005 // Only create DeclRefExpr's for valid Decl's.
1006 if (VD->isInvalidDecl())
1009 // If the identifier reference is inside a block, and it refers to a value
1010 // that is outside the block, create a BlockDeclRefExpr instead of a
1011 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1012 // the block is formed.
1014 // We do not do this for things like enum constants, global variables, etc,
1015 // as they do not get snapshotted.
1017 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
1018 MarkDeclarationReferenced(Loc, VD);
1019 QualType ExprTy = VD->getType().getNonReferenceType();
1020 // The BlocksAttr indicates the variable is bound by-reference.
1021 if (VD->getAttr<BlocksAttr>())
1022 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
1023 // This is to record that a 'const' was actually synthesize and added.
1024 bool constAdded = !ExprTy.isConstQualified();
1025 // Variable will be bound by-copy, make it const within the closure.
1028 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1031 // If this reference is not in a block or if the referenced variable is
1032 // within the block, create a normal DeclRefExpr.
1034 bool TypeDependent = false;
1035 bool ValueDependent = false;
1036 if (getLangOptions().CPlusPlus) {
1037 // C++ [temp.dep.expr]p3:
1038 // An id-expression is type-dependent if it contains:
1039 // - an identifier that was declared with a dependent type,
1040 if (VD->getType()->isDependentType())
1041 TypeDependent = true;
1042 // - FIXME: a template-id that is dependent,
1043 // - a conversion-function-id that specifies a dependent type,
1044 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1045 Name.getCXXNameType()->isDependentType())
1046 TypeDependent = true;
1047 // - a nested-name-specifier that contains a class-name that
1048 // names a dependent type.
1049 else if (SS && !SS->isEmpty()) {
1050 for (DeclContext *DC = computeDeclContext(*SS);
1051 DC; DC = DC->getParent()) {
1052 // FIXME: could stop early at namespace scope.
1053 if (DC->isRecord()) {
1054 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1055 if (Context.getTypeDeclType(Record)->isDependentType()) {
1056 TypeDependent = true;
1063 // C++ [temp.dep.constexpr]p2:
1065 // An identifier is value-dependent if it is:
1066 // - a name declared with a dependent type,
1068 ValueDependent = true;
1069 // - the name of a non-type template parameter,
1070 else if (isa<NonTypeTemplateParmDecl>(VD))
1071 ValueDependent = true;
1072 // - a constant with integral or enumeration type and is
1073 // initialized with an expression that is value-dependent
1074 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1075 if (Context.getCanonicalType(Dcl->getType()).getCVRQualifiers()
1076 == Qualifiers::Const &&
1078 ValueDependent = Dcl->getInit()->isValueDependent();
1083 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1084 TypeDependent, ValueDependent, SS);
1087 Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1088 tok::TokenKind Kind) {
1089 PredefinedExpr::IdentType IT;
1092 default: assert(0 && "Unknown simple primary expr!");
1093 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1094 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1095 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1098 // Pre-defined identifiers are of type char[x], where x is the length of the
1101 Decl *currentDecl = getCurFunctionOrMethodDecl();
1103 Diag(Loc, diag::ext_predef_outside_function);
1104 currentDecl = Context.getTranslationUnitDecl();
1108 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1109 ResTy = Context.DependentTy;
1112 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
1114 llvm::APInt LengthI(32, Length + 1);
1115 ResTy = Context.CharTy.withConst();
1116 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1118 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1121 Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1122 llvm::SmallString<16> CharBuffer;
1123 CharBuffer.resize(Tok.getLength());
1124 const char *ThisTokBegin = &CharBuffer[0];
1125 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1127 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1128 Tok.getLocation(), PP);
1129 if (Literal.hadError())
1132 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1134 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1136 type, Tok.getLocation()));
1139 Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1140 // Fast path for a single digit (which is quite common). A single digit
1141 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1142 if (Tok.getLength() == 1) {
1143 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1144 unsigned IntSize = Context.Target.getIntWidth();
1145 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1146 Context.IntTy, Tok.getLocation()));
1149 llvm::SmallString<512> IntegerBuffer;
1150 // Add padding so that NumericLiteralParser can overread by one character.
1151 IntegerBuffer.resize(Tok.getLength()+1);
1152 const char *ThisTokBegin = &IntegerBuffer[0];
1154 // Get the spelling of the token, which eliminates trigraphs, etc.
1155 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1157 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1158 Tok.getLocation(), PP);
1159 if (Literal.hadError)
1164 if (Literal.isFloatingLiteral()) {
1166 if (Literal.isFloat)
1167 Ty = Context.FloatTy;
1168 else if (!Literal.isLong)
1169 Ty = Context.DoubleTy;
1171 Ty = Context.LongDoubleTy;
1173 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1175 // isExact will be set by GetFloatValue().
1176 bool isExact = false;
1177 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1178 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
1180 } else if (!Literal.isIntegerLiteral()) {
1185 // long long is a C99 feature.
1186 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1188 Diag(Tok.getLocation(), diag::ext_longlong);
1190 // Get the value in the widest-possible width.
1191 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1193 if (Literal.GetIntegerValue(ResultVal)) {
1194 // If this value didn't fit into uintmax_t, warn and force to ull.
1195 Diag(Tok.getLocation(), diag::warn_integer_too_large);
1196 Ty = Context.UnsignedLongLongTy;
1197 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1198 "long long is not intmax_t?");
1200 // If this value fits into a ULL, try to figure out what else it fits into
1201 // according to the rules of C99 6.4.4.1p5.
1203 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1204 // be an unsigned int.
1205 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1207 // Check from smallest to largest, picking the smallest type we can.
1209 if (!Literal.isLong && !Literal.isLongLong) {
1210 // Are int/unsigned possibilities?
1211 unsigned IntSize = Context.Target.getIntWidth();
1213 // Does it fit in a unsigned int?
1214 if (ResultVal.isIntN(IntSize)) {
1215 // Does it fit in a signed int?
1216 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1218 else if (AllowUnsigned)
1219 Ty = Context.UnsignedIntTy;
1224 // Are long/unsigned long possibilities?
1225 if (Ty.isNull() && !Literal.isLongLong) {
1226 unsigned LongSize = Context.Target.getLongWidth();
1228 // Does it fit in a unsigned long?
1229 if (ResultVal.isIntN(LongSize)) {
1230 // Does it fit in a signed long?
1231 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1232 Ty = Context.LongTy;
1233 else if (AllowUnsigned)
1234 Ty = Context.UnsignedLongTy;
1239 // Finally, check long long if needed.
1241 unsigned LongLongSize = Context.Target.getLongLongWidth();
1243 // Does it fit in a unsigned long long?
1244 if (ResultVal.isIntN(LongLongSize)) {
1245 // Does it fit in a signed long long?
1246 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1247 Ty = Context.LongLongTy;
1248 else if (AllowUnsigned)
1249 Ty = Context.UnsignedLongLongTy;
1250 Width = LongLongSize;
1254 // If we still couldn't decide a type, we probably have something that
1255 // does not fit in a signed long long, but has no U suffix.
1257 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1258 Ty = Context.UnsignedLongLongTy;
1259 Width = Context.Target.getLongLongWidth();
1262 if (ResultVal.getBitWidth() != Width)
1263 ResultVal.trunc(Width);
1265 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1268 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1269 if (Literal.isImaginary)
1270 Res = new (Context) ImaginaryLiteral(Res,
1271 Context.getComplexType(Res->getType()));
1276 Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1277 SourceLocation R, ExprArg Val) {
1278 Expr *E = Val.takeAs<Expr>();
1279 assert((E != 0) && "ActOnParenExpr() missing expr");
1280 return Owned(new (Context) ParenExpr(L, R, E));
1283 /// The UsualUnaryConversions() function is *not* called by this routine.
1284 /// See C99 6.3.2.1p[2-4] for more details.
1285 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1286 SourceLocation OpLoc,
1287 const SourceRange &ExprRange,
1289 if (exprType->isDependentType())
1293 if (exprType->isFunctionType()) {
1294 // alignof(function) is allowed as an extension.
1296 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1300 // Allow sizeof(void)/alignof(void) as an extension.
1301 if (exprType->isVoidType()) {
1302 Diag(OpLoc, diag::ext_sizeof_void_type)
1303 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1307 if (RequireCompleteType(OpLoc, exprType,
1308 isSizeof ? diag::err_sizeof_incomplete_type :
1309 PDiag(diag::err_alignof_incomplete_type)
1313 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
1314 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
1315 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
1316 << exprType << isSizeof << ExprRange;
1323 bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1324 const SourceRange &ExprRange) {
1325 E = E->IgnoreParens();
1327 // alignof decl is always ok.
1328 if (isa<DeclRefExpr>(E))
1331 // Cannot know anything else if the expression is dependent.
1332 if (E->isTypeDependent())
1335 if (E->getBitField()) {
1336 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1340 // Alignment of a field access is always okay, so long as it isn't a
1342 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1343 if (isa<FieldDecl>(ME->getMemberDecl()))
1346 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1349 /// \brief Build a sizeof or alignof expression given a type operand.
1350 Action::OwningExprResult
1351 Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1352 SourceLocation OpLoc,
1353 bool isSizeOf, SourceRange R) {
1357 QualType T = DInfo->getType();
1359 if (!T->isDependentType() &&
1360 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1363 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1364 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
1365 Context.getSizeType(), OpLoc,
1369 /// \brief Build a sizeof or alignof expression given an expression
1371 Action::OwningExprResult
1372 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1373 bool isSizeOf, SourceRange R) {
1374 // Verify that the operand is valid.
1375 bool isInvalid = false;
1376 if (E->isTypeDependent()) {
1377 // Delay type-checking for type-dependent expressions.
1378 } else if (!isSizeOf) {
1379 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1380 } else if (E->getBitField()) { // C99 6.5.3.4p1.
1381 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1384 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1390 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1391 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1392 Context.getSizeType(), OpLoc,
1396 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1397 /// the same for @c alignof and @c __alignof
1398 /// Note that the ArgRange is invalid if isType is false.
1399 Action::OwningExprResult
1400 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1401 void *TyOrEx, const SourceRange &ArgRange) {
1402 // If error parsing type, ignore.
1403 if (TyOrEx == 0) return ExprError();
1406 DeclaratorInfo *DInfo;
1407 (void) GetTypeFromParser(TyOrEx, &DInfo);
1408 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
1411 Expr *ArgEx = (Expr *)TyOrEx;
1412 Action::OwningExprResult Result
1413 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1415 if (Result.isInvalid())
1418 return move(Result);
1421 QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
1422 if (V->isTypeDependent())
1423 return Context.DependentTy;
1425 // These operators return the element type of a complex type.
1426 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
1427 return CT->getElementType();
1429 // Otherwise they pass through real integer and floating point types here.
1430 if (V->getType()->isArithmeticType())
1431 return V->getType();
1433 // Reject anything else.
1434 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1435 << (isReal ? "__real" : "__imag");
1441 Action::OwningExprResult
1442 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1443 tok::TokenKind Kind, ExprArg Input) {
1444 // Since this might be a postfix expression, get rid of ParenListExprs.
1445 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
1446 Expr *Arg = (Expr *)Input.get();
1448 UnaryOperator::Opcode Opc;
1450 default: assert(0 && "Unknown unary op!");
1451 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1452 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1455 if (getLangOptions().CPlusPlus &&
1456 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1457 // Which overloaded operator?
1458 OverloadedOperatorKind OverOp =
1459 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1461 // C++ [over.inc]p1:
1463 // [...] If the function is a member function with one
1464 // parameter (which shall be of type int) or a non-member
1465 // function with two parameters (the second of which shall be
1466 // of type int), it defines the postfix increment operator ++
1467 // for objects of that type. When the postfix increment is
1468 // called as a result of using the ++ operator, the int
1469 // argument will have value zero.
1472 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1473 /*isSigned=*/true), Context.IntTy, SourceLocation())
1476 // Build the candidate set for overloading
1477 OverloadCandidateSet CandidateSet;
1478 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
1480 // Perform overload resolution.
1481 OverloadCandidateSet::iterator Best;
1482 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
1484 // We found a built-in operator or an overloaded operator.
1485 FunctionDecl *FnDecl = Best->Function;
1488 // We matched an overloaded operator. Build a call to that
1491 // Convert the arguments.
1492 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1493 if (PerformObjectArgumentInitialization(Arg, Method))
1496 // Convert the arguments.
1497 if (PerformCopyInitialization(Arg,
1498 FnDecl->getParamDecl(0)->getType(),
1503 // Determine the result type
1504 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
1506 // Build the actual expression node.
1507 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1509 UsualUnaryConversions(FnExpr);
1514 ExprOwningPtr<CXXOperatorCallExpr>
1515 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OverOp,
1519 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
1522 return Owned(TheCall.release());
1525 // We matched a built-in operator. Convert the arguments, then
1526 // break out so that we will build the appropriate built-in
1528 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1536 case OR_No_Viable_Function: {
1537 // No viable function; try checking this as a built-in operator, which
1538 // will fail and provide a diagnostic. Then, print the overload
1540 OwningExprResult Result = CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1541 assert(Result.isInvalid() &&
1542 "C++ postfix-unary operator overloading is missing candidates!");
1543 if (Result.isInvalid())
1544 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1546 return move(Result);
1550 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1551 << UnaryOperator::getOpcodeStr(Opc)
1552 << Arg->getSourceRange();
1553 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1557 Diag(OpLoc, diag::err_ovl_deleted_oper)
1558 << Best->Function->isDeleted()
1559 << UnaryOperator::getOpcodeStr(Opc)
1560 << Arg->getSourceRange();
1561 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1565 // Either we found no viable overloaded operator or we matched a
1566 // built-in operator. In either case, fall through to trying to
1567 // build a built-in operation.
1572 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1575 Action::OwningExprResult
1576 Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1577 ExprArg Idx, SourceLocation RLoc) {
1578 // Since this might be a postfix expression, get rid of ParenListExprs.
1579 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1581 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1582 *RHSExp = static_cast<Expr*>(Idx.get());
1584 if (getLangOptions().CPlusPlus &&
1585 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1588 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1589 Context.DependentTy, RLoc));
1592 if (getLangOptions().CPlusPlus &&
1593 (LHSExp->getType()->isRecordType() ||
1594 LHSExp->getType()->isEnumeralType() ||
1595 RHSExp->getType()->isRecordType() ||
1596 RHSExp->getType()->isEnumeralType())) {
1597 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
1600 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1604 Action::OwningExprResult
1605 Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1606 ExprArg Idx, SourceLocation RLoc) {
1607 Expr *LHSExp = static_cast<Expr*>(Base.get());
1608 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1610 // Perform default conversions.
1611 DefaultFunctionArrayConversion(LHSExp);
1612 DefaultFunctionArrayConversion(RHSExp);
1614 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1616 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1617 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1618 // in the subscript position. As a result, we need to derive the array base
1619 // and index from the expression types.
1620 Expr *BaseExpr, *IndexExpr;
1621 QualType ResultType;
1622 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1625 ResultType = Context.DependentTy;
1626 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
1629 ResultType = PTy->getPointeeType();
1630 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
1631 // Handle the uncommon case of "123[Ptr]".
1634 ResultType = PTy->getPointeeType();
1635 } else if (const ObjCObjectPointerType *PTy =
1636 LHSTy->getAs<ObjCObjectPointerType>()) {
1639 ResultType = PTy->getPointeeType();
1640 } else if (const ObjCObjectPointerType *PTy =
1641 RHSTy->getAs<ObjCObjectPointerType>()) {
1642 // Handle the uncommon case of "123[Ptr]".
1645 ResultType = PTy->getPointeeType();
1646 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
1647 BaseExpr = LHSExp; // vectors: V[123]
1650 // FIXME: need to deal with const...
1651 ResultType = VTy->getElementType();
1652 } else if (LHSTy->isArrayType()) {
1653 // If we see an array that wasn't promoted by
1654 // DefaultFunctionArrayConversion, it must be an array that
1655 // wasn't promoted because of the C90 rule that doesn't
1656 // allow promoting non-lvalue arrays. Warn, then
1657 // force the promotion here.
1658 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1659 LHSExp->getSourceRange();
1660 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1661 CastExpr::CK_ArrayToPointerDecay);
1662 LHSTy = LHSExp->getType();
1666 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
1667 } else if (RHSTy->isArrayType()) {
1668 // Same as previous, except for 123[f().a] case
1669 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1670 RHSExp->getSourceRange();
1671 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1672 CastExpr::CK_ArrayToPointerDecay);
1673 RHSTy = RHSExp->getType();
1677 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
1679 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1680 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
1683 if (!(IndexExpr->getType()->isIntegerType() &&
1684 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
1685 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1686 << IndexExpr->getSourceRange());
1688 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
1689 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1690 && !IndexExpr->isTypeDependent())
1691 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1693 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1694 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1695 // type. Note that Functions are not objects, and that (in C99 parlance)
1696 // incomplete types are not object types.
1697 if (ResultType->isFunctionType()) {
1698 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1699 << ResultType << BaseExpr->getSourceRange();
1703 if (!ResultType->isDependentType() &&
1704 RequireCompleteType(LLoc, ResultType,
1705 PDiag(diag::err_subscript_incomplete_type)
1706 << BaseExpr->getSourceRange()))
1709 // Diagnose bad cases where we step over interface counts.
1710 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1711 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1712 << ResultType << BaseExpr->getSourceRange();
1718 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1723 CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1724 const IdentifierInfo *CompName,
1725 SourceLocation CompLoc) {
1726 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1729 // FIXME: This logic can be greatly simplified by splitting it along
1730 // halving/not halving and reworking the component checking.
1731 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
1733 // The vector accessor can't exceed the number of elements.
1734 const char *compStr = CompName->getNameStart();
1736 // This flag determines whether or not the component is one of the four
1737 // special names that indicate a subset of exactly half the elements are
1739 bool HalvingSwizzle = false;
1741 // This flag determines whether or not CompName has an 's' char prefix,
1742 // indicating that it is a string of hex values to be used as vector indices.
1743 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
1745 // Check that we've found one of the special components, or that the component
1746 // names must come from the same set.
1747 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1748 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1749 HalvingSwizzle = true;
1750 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1753 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1754 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1757 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1760 if (!HalvingSwizzle && *compStr) {
1761 // We didn't get to the end of the string. This means the component names
1762 // didn't come from the same set *or* we encountered an illegal name.
1763 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1764 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1768 // Ensure no component accessor exceeds the width of the vector type it
1770 if (!HalvingSwizzle) {
1771 compStr = CompName->getNameStart();
1777 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1778 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1779 << baseType << SourceRange(CompLoc);
1785 // If this is a halving swizzle, verify that the base type has an even
1786 // number of elements.
1787 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1788 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1789 << baseType << SourceRange(CompLoc);
1793 // The component accessor looks fine - now we need to compute the actual type.
1794 // The vector type is implied by the component accessor. For example,
1795 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1796 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1797 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1798 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1799 : CompName->getLength();
1804 return vecType->getElementType();
1806 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1807 // Now look up the TypeDefDecl from the vector type. Without this,
1808 // diagostics look bad. We want extended vector types to appear built-in.
1809 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1810 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1811 return Context.getTypedefType(ExtVectorDecls[i]);
1813 return VT; // should never get here (a typedef type should always be found).
1816 static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1817 IdentifierInfo *Member,
1818 const Selector &Sel,
1819 ASTContext &Context) {
1821 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
1823 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1826 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1827 E = PDecl->protocol_end(); I != E; ++I) {
1828 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1835 static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
1836 IdentifierInfo *Member,
1837 const Selector &Sel,
1838 ASTContext &Context) {
1839 // Check protocols on qualified interfaces.
1841 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1842 E = QIdTy->qual_end(); I != E; ++I) {
1843 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1847 // Also must look for a getter name which uses property syntax.
1848 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1854 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1855 E = QIdTy->qual_end(); I != E; ++I) {
1856 // Search in the protocol-qualifier list of current protocol.
1857 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
1865 Action::OwningExprResult
1866 Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1867 tok::TokenKind OpKind, SourceLocation MemberLoc,
1868 DeclarationName MemberName,
1869 bool HasExplicitTemplateArgs,
1870 SourceLocation LAngleLoc,
1871 const TemplateArgumentLoc *ExplicitTemplateArgs,
1872 unsigned NumExplicitTemplateArgs,
1873 SourceLocation RAngleLoc,
1874 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1875 NamedDecl *FirstQualifierInScope) {
1876 if (SS && SS->isInvalid())
1879 // Since this might be a postfix expression, get rid of ParenListExprs.
1880 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1882 Expr *BaseExpr = Base.takeAs<Expr>();
1883 assert(BaseExpr && "no base expression");
1885 // Perform default conversions.
1886 DefaultFunctionArrayConversion(BaseExpr);
1888 QualType BaseType = BaseExpr->getType();
1889 // If this is an Objective-C pseudo-builtin and a definition is provided then
1891 if (BaseType->isObjCIdType()) {
1892 // We have an 'id' type. Rather than fall through, we check if this
1893 // is a reference to 'isa'.
1894 if (BaseType != Context.ObjCIdRedefinitionType) {
1895 BaseType = Context.ObjCIdRedefinitionType;
1896 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
1899 assert(!BaseType.isNull() && "no type for member expression");
1901 // Handle properties on ObjC 'Class' types.
1902 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1903 // Also must look for a getter name which uses property syntax.
1904 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1905 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1906 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1907 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1908 ObjCMethodDecl *Getter;
1909 // FIXME: need to also look locally in the implementation.
1910 if ((Getter = IFace->lookupClassMethod(Sel))) {
1911 // Check the use of this method.
1912 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1915 // If we found a getter then this may be a valid dot-reference, we
1916 // will look for the matching setter, in case it is needed.
1917 Selector SetterSel =
1918 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1919 PP.getSelectorTable(), Member);
1920 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1922 // If this reference is in an @implementation, also check for 'private'
1924 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
1926 // Look through local category implementations associated with the class.
1928 Setter = IFace->getCategoryClassMethod(SetterSel);
1930 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1933 if (Getter || Setter) {
1937 PType = Getter->getResultType();
1939 // Get the expression type from Setter's incoming parameter.
1940 PType = (*(Setter->param_end() -1))->getType();
1941 // FIXME: we must check that the setter has property type.
1942 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
1944 Setter, MemberLoc, BaseExpr));
1946 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1947 << MemberName << BaseType);
1951 if (BaseType->isObjCClassType() &&
1952 BaseType != Context.ObjCClassRedefinitionType) {
1953 BaseType = Context.ObjCClassRedefinitionType;
1954 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
1957 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1958 // must have pointer type, and the accessed type is the pointee.
1959 if (OpKind == tok::arrow) {
1960 if (BaseType->isDependentType()) {
1961 NestedNameSpecifier *Qualifier = 0;
1963 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1964 if (!FirstQualifierInScope)
1965 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
1968 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
1970 SS? SS->getRange() : SourceRange(),
1971 FirstQualifierInScope,
1974 HasExplicitTemplateArgs,
1976 ExplicitTemplateArgs,
1977 NumExplicitTemplateArgs,
1980 else if (const PointerType *PT = BaseType->getAs<PointerType>())
1981 BaseType = PT->getPointeeType();
1982 else if (BaseType->isObjCObjectPointerType())
1985 return ExprError(Diag(MemberLoc,
1986 diag::err_typecheck_member_reference_arrow)
1987 << BaseType << BaseExpr->getSourceRange());
1988 } else if (BaseType->isDependentType()) {
1989 // Require that the base type isn't a pointer type
1990 // (so we'll report an error for)
1994 // In Obj-C++, however, the above expression is valid, since it could be
1995 // accessing the 'f' property if T is an Obj-C interface. The extra check
1996 // allows this, while still reporting an error if T is a struct pointer.
1997 const PointerType *PT = BaseType->getAs<PointerType>();
1999 if (!PT || (getLangOptions().ObjC1 &&
2000 !PT->getPointeeType()->isRecordType())) {
2001 NestedNameSpecifier *Qualifier = 0;
2003 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2004 if (!FirstQualifierInScope)
2005 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2008 return Owned(CXXUnresolvedMemberExpr::Create(Context,
2012 SS? SS->getRange() : SourceRange(),
2013 FirstQualifierInScope,
2016 HasExplicitTemplateArgs,
2018 ExplicitTemplateArgs,
2019 NumExplicitTemplateArgs,
2024 // Handle field access to simple records. This also handles access to fields
2025 // of the ObjC 'id' struct.
2026 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
2027 RecordDecl *RDecl = RTy->getDecl();
2028 if (RequireCompleteType(OpLoc, BaseType,
2029 PDiag(diag::err_typecheck_incomplete_tag)
2030 << BaseExpr->getSourceRange()))
2033 DeclContext *DC = RDecl;
2034 if (SS && SS->isSet()) {
2035 // If the member name was a qualified-id, look into the
2036 // nested-name-specifier.
2037 DC = computeDeclContext(*SS, false);
2039 if (!isa<TypeDecl>(DC)) {
2040 Diag(MemberLoc, diag::err_qualified_member_nonclass)
2041 << DC << SS->getRange();
2045 // FIXME: If DC is not computable, we should build a
2046 // CXXUnresolvedMemberExpr.
2047 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2050 // The record definition is complete, now make sure the member is valid.
2051 LookupResult Result;
2052 LookupQualifiedName(Result, DC, MemberName, LookupMemberName, false);
2055 return ExprError(Diag(MemberLoc, diag::err_no_member)
2056 << MemberName << DC << BaseExpr->getSourceRange());
2057 if (Result.isAmbiguous()) {
2058 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2059 BaseExpr->getSourceRange());
2063 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2065 if (SS && SS->isSet()) {
2066 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
2067 QualType BaseTypeCanon
2068 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2069 QualType MemberTypeCanon
2070 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
2072 if (BaseTypeCanon != MemberTypeCanon &&
2073 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2074 return ExprError(Diag(SS->getBeginLoc(),
2075 diag::err_not_direct_base_or_virtual)
2076 << MemberTypeCanon << BaseTypeCanon);
2079 // If the decl being referenced had an error, return an error for this
2080 // sub-expr without emitting another error, in order to avoid cascading
2082 if (MemberDecl->isInvalidDecl())
2085 bool ShouldCheckUse = true;
2086 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2087 // Don't diagnose the use of a virtual member function unless it's
2088 // explicitly qualified.
2089 if (MD->isVirtual() && (!SS || !SS->isSet()))
2090 ShouldCheckUse = false;
2093 // Check the use of this field
2094 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2097 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2098 // We may have found a field within an anonymous union or struct
2099 // (C++ [class.union]).
2100 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
2101 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2104 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2105 QualType MemberType = FD->getType();
2106 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2107 MemberType = Ref->getPointeeType();
2109 Qualifiers BaseQuals = BaseType.getQualifiers();
2110 BaseQuals.removeObjCGCAttr();
2111 if (FD->isMutable()) BaseQuals.removeConst();
2113 Qualifiers MemberQuals
2114 = Context.getCanonicalType(MemberType).getQualifiers();
2116 Qualifiers Combined = BaseQuals + MemberQuals;
2117 if (Combined != MemberQuals)
2118 MemberType = Context.getQualifiedType(MemberType, Combined);
2121 MarkDeclarationReferenced(MemberLoc, FD);
2122 if (PerformObjectMemberConversion(BaseExpr, FD))
2124 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2125 FD, MemberLoc, MemberType));
2128 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2129 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2130 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2132 Var->getType().getNonReferenceType()));
2134 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2135 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2136 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2137 MemberFn, MemberLoc,
2138 MemberFn->getType()));
2140 if (FunctionTemplateDecl *FunTmpl
2141 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2142 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2144 if (HasExplicitTemplateArgs)
2145 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2146 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2147 SS? SS->getRange() : SourceRange(),
2148 FunTmpl, MemberLoc, true,
2149 LAngleLoc, ExplicitTemplateArgs,
2150 NumExplicitTemplateArgs, RAngleLoc,
2151 Context.OverloadTy));
2153 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2155 Context.OverloadTy));
2157 if (OverloadedFunctionDecl *Ovl
2158 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2159 if (HasExplicitTemplateArgs)
2160 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2161 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2162 SS? SS->getRange() : SourceRange(),
2163 Ovl, MemberLoc, true,
2164 LAngleLoc, ExplicitTemplateArgs,
2165 NumExplicitTemplateArgs, RAngleLoc,
2166 Context.OverloadTy));
2168 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2169 Ovl, MemberLoc, Context.OverloadTy));
2171 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2172 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2173 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2174 Enum, MemberLoc, Enum->getType()));
2176 if (isa<TypeDecl>(MemberDecl))
2177 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2178 << MemberName << int(OpKind == tok::arrow));
2180 // We found a declaration kind that we didn't expect. This is a
2181 // generic error message that tells the user that she can't refer
2182 // to this member with '.' or '->'.
2183 return ExprError(Diag(MemberLoc,
2184 diag::err_typecheck_member_reference_unknown)
2185 << MemberName << int(OpKind == tok::arrow));
2188 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2189 // into a record type was handled above, any destructor we see here is a
2190 // pseudo-destructor.
2191 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2192 // C++ [expr.pseudo]p2:
2193 // The left hand side of the dot operator shall be of scalar type. The
2194 // left hand side of the arrow operator shall be of pointer to scalar
2196 if (!BaseType->isScalarType())
2197 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2198 << BaseType << BaseExpr->getSourceRange());
2200 // [...] The type designated by the pseudo-destructor-name shall be the
2201 // same as the object type.
2202 if (!MemberName.getCXXNameType()->isDependentType() &&
2203 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2204 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2205 << BaseType << MemberName.getCXXNameType()
2206 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
2208 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
2211 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2213 // shall designate the same scalar type.
2215 // FIXME: DPG can't see any way to trigger this particular clause, so it
2216 // isn't checked here.
2218 // FIXME: We've lost the precise spelling of the type by going through
2219 // DeclarationName. Can we do better?
2220 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
2221 OpKind == tok::arrow,
2223 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2224 SS? SS->getRange() : SourceRange(),
2225 MemberName.getCXXNameType(),
2229 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2231 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2232 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2233 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
2234 const ObjCInterfaceType *IFaceT =
2235 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
2237 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2239 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2240 ObjCInterfaceDecl *ClassDeclared;
2241 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
2244 // If the decl being referenced had an error, return an error for this
2245 // sub-expr without emitting another error, in order to avoid cascading
2247 if (IV->isInvalidDecl())
2250 // Check whether we can reference this field.
2251 if (DiagnoseUseOfDecl(IV, MemberLoc))
2253 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2254 IV->getAccessControl() != ObjCIvarDecl::Package) {
2255 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2256 if (ObjCMethodDecl *MD = getCurMethodDecl())
2257 ClassOfMethodDecl = MD->getClassInterface();
2258 else if (ObjCImpDecl && getCurFunctionDecl()) {
2259 // Case of a c-function declared inside an objc implementation.
2260 // FIXME: For a c-style function nested inside an objc implementation
2261 // class, there is no implementation context available, so we pass
2262 // down the context as argument to this routine. Ideally, this context
2263 // need be passed down in the AST node and somehow calculated from the
2264 // AST for a function decl.
2265 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2266 if (ObjCImplementationDecl *IMPD =
2267 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2268 ClassOfMethodDecl = IMPD->getClassInterface();
2269 else if (ObjCCategoryImplDecl* CatImplClass =
2270 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2271 ClassOfMethodDecl = CatImplClass->getClassInterface();
2274 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2275 if (ClassDeclared != IDecl ||
2276 ClassOfMethodDecl != ClassDeclared)
2277 Diag(MemberLoc, diag::error_private_ivar_access)
2278 << IV->getDeclName();
2279 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2281 Diag(MemberLoc, diag::error_protected_ivar_access)
2282 << IV->getDeclName();
2285 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2286 MemberLoc, BaseExpr,
2287 OpKind == tok::arrow));
2289 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2290 << IDecl->getDeclName() << MemberName
2291 << BaseExpr->getSourceRange());
2294 // Handle properties on 'id' and qualified "id".
2295 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2296 BaseType->isObjCQualifiedIdType())) {
2297 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
2298 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2300 // Check protocols on qualified interfaces.
2301 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2302 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2303 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2304 // Check the use of this declaration
2305 if (DiagnoseUseOfDecl(PD, MemberLoc))
2308 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2309 MemberLoc, BaseExpr));
2311 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2312 // Check the use of this method.
2313 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2316 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2317 OMD->getResultType(),
2318 OMD, OpLoc, MemberLoc,
2323 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2324 << MemberName << BaseType);
2326 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2327 // pointer to a (potentially qualified) interface type.
2328 const ObjCObjectPointerType *OPT;
2329 if (OpKind == tok::period &&
2330 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2331 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2332 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2333 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2335 // Search for a declared property first.
2336 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
2337 // Check whether we can reference this property.
2338 if (DiagnoseUseOfDecl(PD, MemberLoc))
2340 QualType ResTy = PD->getType();
2341 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2342 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2343 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2344 ResTy = Getter->getResultType();
2345 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
2346 MemberLoc, BaseExpr));
2348 // Check protocols on qualified interfaces.
2349 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2350 E = OPT->qual_end(); I != E; ++I)
2351 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2352 // Check whether we can reference this property.
2353 if (DiagnoseUseOfDecl(PD, MemberLoc))
2356 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2357 MemberLoc, BaseExpr));
2359 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2360 E = OPT->qual_end(); I != E; ++I)
2361 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2362 // Check whether we can reference this property.
2363 if (DiagnoseUseOfDecl(PD, MemberLoc))
2366 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2367 MemberLoc, BaseExpr));
2369 // If that failed, look for an "implicit" property by seeing if the nullary
2370 // selector is implemented.
2372 // FIXME: The logic for looking up nullary and unary selectors should be
2373 // shared with the code in ActOnInstanceMessage.
2375 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2376 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2378 // If this reference is in an @implementation, check for 'private' methods.
2380 Getter = IFace->lookupPrivateInstanceMethod(Sel);
2382 // Look through local category implementations associated with the class.
2384 Getter = IFace->getCategoryInstanceMethod(Sel);
2386 // Check if we can reference this property.
2387 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2390 // If we found a getter then this may be a valid dot-reference, we
2391 // will look for the matching setter, in case it is needed.
2392 Selector SetterSel =
2393 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2394 PP.getSelectorTable(), Member);
2395 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2397 // If this reference is in an @implementation, also check for 'private'
2399 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
2401 // Look through local category implementations associated with the class.
2403 Setter = IFace->getCategoryInstanceMethod(SetterSel);
2405 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2408 if (Getter || Setter) {
2412 PType = Getter->getResultType();
2414 // Get the expression type from Setter's incoming parameter.
2415 PType = (*(Setter->param_end() -1))->getType();
2416 // FIXME: we must check that the setter has property type.
2417 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
2418 Setter, MemberLoc, BaseExpr));
2420 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2421 << MemberName << BaseType);
2424 // Handle the following exceptional case (*Obj).isa.
2425 if (OpKind == tok::period &&
2426 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2427 MemberName.getAsIdentifierInfo()->isStr("isa"))
2428 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2429 Context.getObjCIdType()));
2431 // Handle 'field access' to vectors, such as 'V.xx'.
2432 if (BaseType->isExtVectorType()) {
2433 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2434 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2437 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
2441 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2442 << BaseType << BaseExpr->getSourceRange();
2444 // If the user is trying to apply -> or . to a function or function
2445 // pointer, it's probably because they forgot parentheses to call
2446 // the function. Suggest the addition of those parentheses.
2447 if (BaseType == Context.OverloadTy ||
2448 BaseType->isFunctionType() ||
2449 (BaseType->isPointerType() &&
2450 BaseType->getAs<PointerType>()->isFunctionType())) {
2451 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2452 Diag(Loc, diag::note_member_reference_needs_call)
2453 << CodeModificationHint::CreateInsertion(Loc, "()");
2459 Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2460 SourceLocation OpLoc,
2461 tok::TokenKind OpKind,
2462 const CXXScopeSpec &SS,
2463 UnqualifiedId &Member,
2464 DeclPtrTy ObjCImpDecl,
2465 bool HasTrailingLParen) {
2466 if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2467 TemplateName Template
2468 = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2470 // FIXME: We're going to end up looking up the template based on its name,
2472 DeclarationName Name;
2473 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2474 Name = ActualTemplate->getDeclName();
2475 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2476 Name = Ovl->getDeclName();
2478 DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2479 if (DTN->isIdentifier())
2480 Name = DTN->getIdentifier();
2482 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2485 // Translate the parser's template argument list in our AST format.
2486 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2487 Member.TemplateId->getTemplateArgs(),
2488 Member.TemplateId->getTemplateArgIsType(),
2489 Member.TemplateId->NumArgs);
2491 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
2492 translateTemplateArguments(TemplateArgsPtr,
2493 Member.TemplateId->getTemplateArgLocations(),
2495 TemplateArgsPtr.release();
2497 // Do we have the save the actual template name? We might need it...
2498 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2499 Member.TemplateId->TemplateNameLoc,
2500 Name, true, Member.TemplateId->LAngleLoc,
2501 TemplateArgs.data(), TemplateArgs.size(),
2502 Member.TemplateId->RAngleLoc, DeclPtrTy(),
2506 // FIXME: We lose a lot of source information by mapping directly to the
2508 OwningExprResult Result
2509 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2510 Member.getSourceRange().getBegin(),
2511 GetNameFromUnqualifiedId(Member),
2514 if (Result.isInvalid() || HasTrailingLParen ||
2515 Member.getKind() != UnqualifiedId::IK_DestructorName)
2516 return move(Result);
2518 // The only way a reference to a destructor can be used is to
2519 // immediately call them. Since the next token is not a '(', produce a
2520 // diagnostic and build the call now.
2521 Expr *E = (Expr *)Result.get();
2522 SourceLocation ExpectedLParenLoc
2523 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2524 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2525 << isa<CXXPseudoDestructorExpr>(E)
2526 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2528 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2529 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
2532 Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2534 ParmVarDecl *Param) {
2535 if (Param->hasUnparsedDefaultArg()) {
2537 diag::err_use_of_default_argument_to_function_declared_later) <<
2538 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2539 Diag(UnparsedDefaultArgLocs[Param],
2540 diag::note_default_argument_declared_here);
2542 if (Param->hasUninstantiatedDefaultArg()) {
2543 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2545 // Instantiate the expression.
2546 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
2548 InstantiatingTemplate Inst(*this, CallLoc, Param,
2549 ArgList.getInnermost().getFlatArgumentList(),
2550 ArgList.getInnermost().flat_size());
2552 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
2553 if (Result.isInvalid())
2556 if (SetParamDefaultArgument(Param, move(Result),
2558 UninstExpr->getSourceRange().getBegin()))
2562 Expr *DefaultExpr = Param->getDefaultArg();
2564 // If the default expression creates temporaries, we need to
2565 // push them to the current stack of expression temporaries so they'll
2566 // be properly destroyed.
2567 if (CXXExprWithTemporaries *E
2568 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2569 assert(!E->shouldDestroyTemporaries() &&
2570 "Can't destroy temporaries in a default argument expr!");
2571 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2572 ExprTemporaries.push_back(E->getTemporary(I));
2576 // We already type-checked the argument, so we know it works.
2577 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2580 /// ConvertArgumentsForCall - Converts the arguments specified in
2581 /// Args/NumArgs to the parameter types of the function FDecl with
2582 /// function prototype Proto. Call is the call expression itself, and
2583 /// Fn is the function expression. For a C++ member function, this
2584 /// routine does not attempt to convert the object argument. Returns
2585 /// true if the call is ill-formed.
2587 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2588 FunctionDecl *FDecl,
2589 const FunctionProtoType *Proto,
2590 Expr **Args, unsigned NumArgs,
2591 SourceLocation RParenLoc) {
2592 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
2593 // assignment, to the types of the corresponding parameter, ...
2594 unsigned NumArgsInProto = Proto->getNumArgs();
2595 unsigned NumArgsToCheck = NumArgs;
2596 bool Invalid = false;
2598 // If too few arguments are available (and we don't have default
2599 // arguments for the remaining parameters), don't make the call.
2600 if (NumArgs < NumArgsInProto) {
2601 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2602 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2603 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2604 // Use default arguments for missing arguments
2605 NumArgsToCheck = NumArgsInProto;
2606 Call->setNumArgs(Context, NumArgsInProto);
2609 // If too many are passed and not variadic, error on the extras and drop
2611 if (NumArgs > NumArgsInProto) {
2612 if (!Proto->isVariadic()) {
2613 Diag(Args[NumArgsInProto]->getLocStart(),
2614 diag::err_typecheck_call_too_many_args)
2615 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2616 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2617 Args[NumArgs-1]->getLocEnd());
2618 // This deletes the extra arguments.
2619 Call->setNumArgs(Context, NumArgsInProto);
2622 NumArgsToCheck = NumArgsInProto;
2625 // Continue to check argument types (even if we have too few/many args).
2626 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2627 QualType ProtoArgType = Proto->getArgType(i);
2633 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2635 PDiag(diag::err_call_incomplete_argument)
2636 << Arg->getSourceRange()))
2639 // Pass the argument.
2640 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2643 ParmVarDecl *Param = FDecl->getParamDecl(i);
2645 OwningExprResult ArgExpr =
2646 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2648 if (ArgExpr.isInvalid())
2651 Arg = ArgExpr.takeAs<Expr>();
2654 Call->setArg(i, Arg);
2657 // If this is a variadic call, handle args passed through "...".
2658 if (Proto->isVariadic()) {
2659 VariadicCallType CallType = VariadicFunction;
2660 if (Fn->getType()->isBlockPointerType())
2661 CallType = VariadicBlock; // Block
2662 else if (isa<MemberExpr>(Fn))
2663 CallType = VariadicMethod;
2665 // Promote the arguments (C99 6.5.2.2p7).
2666 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2667 Expr *Arg = Args[i];
2668 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
2669 Call->setArg(i, Arg);
2676 /// \brief "Deconstruct" the function argument of a call expression to find
2677 /// the underlying declaration (if any), the name of the called function,
2678 /// whether argument-dependent lookup is available, whether it has explicit
2679 /// template arguments, etc.
2680 void Sema::DeconstructCallFunction(Expr *FnExpr,
2681 NamedDecl *&Function,
2682 DeclarationName &Name,
2683 NestedNameSpecifier *&Qualifier,
2684 SourceRange &QualifierRange,
2685 bool &ArgumentDependentLookup,
2686 bool &HasExplicitTemplateArguments,
2687 const TemplateArgumentLoc *&ExplicitTemplateArgs,
2688 unsigned &NumExplicitTemplateArgs) {
2689 // Set defaults for all of the output parameters.
2691 Name = DeclarationName();
2693 QualifierRange = SourceRange();
2694 ArgumentDependentLookup = getLangOptions().CPlusPlus;
2695 HasExplicitTemplateArguments = false;
2697 // If we're directly calling a function, get the appropriate declaration.
2698 // Also, in C++, keep track of whether we should perform argument-dependent
2699 // lookup and whether there were any explicitly-specified template arguments.
2701 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2702 FnExpr = IcExpr->getSubExpr();
2703 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2704 // Parentheses around a function disable ADL
2705 // (C++0x [basic.lookup.argdep]p1).
2706 ArgumentDependentLookup = false;
2707 FnExpr = PExpr->getSubExpr();
2708 } else if (isa<UnaryOperator>(FnExpr) &&
2709 cast<UnaryOperator>(FnExpr)->getOpcode()
2710 == UnaryOperator::AddrOf) {
2711 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2712 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2713 Function = dyn_cast<NamedDecl>(DRExpr->getDecl());
2714 if ((Qualifier = DRExpr->getQualifier())) {
2715 ArgumentDependentLookup = false;
2716 QualifierRange = DRExpr->getQualifierRange();
2719 } else if (UnresolvedFunctionNameExpr *DepName
2720 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2721 Name = DepName->getName();
2723 } else if (TemplateIdRefExpr *TemplateIdRef
2724 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2725 Function = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2727 Function = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2728 HasExplicitTemplateArguments = true;
2729 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2730 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2732 // C++ [temp.arg.explicit]p6:
2733 // [Note: For simple function names, argument dependent lookup (3.4.2)
2734 // applies even when the function name is not visible within the
2735 // scope of the call. This is because the call still has the syntactic
2736 // form of a function call (3.4.1). But when a function template with
2737 // explicit template arguments is used, the call does not have the
2738 // correct syntactic form unless there is a function template with
2739 // that name visible at the point of the call. If no such name is
2740 // visible, the call is not syntactically well-formed and
2741 // argument-dependent lookup does not apply. If some such name is
2742 // visible, argument dependent lookup applies and additional function
2743 // templates may be found in other namespaces.
2745 // The summary of this paragraph is that, if we get to this point and the
2746 // template-id was not a qualified name, then argument-dependent lookup
2747 // is still possible.
2748 if ((Qualifier = TemplateIdRef->getQualifier())) {
2749 ArgumentDependentLookup = false;
2750 QualifierRange = TemplateIdRef->getQualifierRange();
2754 // Any kind of name that does not refer to a declaration (or
2755 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2756 ArgumentDependentLookup = false;
2762 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2763 /// This provides the location of the left/right parens and a list of comma
2765 Action::OwningExprResult
2766 Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2768 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2769 unsigned NumArgs = args.size();
2771 // Since this might be a postfix expression, get rid of ParenListExprs.
2772 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2774 Expr *Fn = fn.takeAs<Expr>();
2775 Expr **Args = reinterpret_cast<Expr**>(args.release());
2776 assert(Fn && "no function call expression");
2777 FunctionDecl *FDecl = NULL;
2778 NamedDecl *NDecl = NULL;
2779 DeclarationName UnqualifiedName;
2781 if (getLangOptions().CPlusPlus) {
2782 // If this is a pseudo-destructor expression, build the call immediately.
2783 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2785 // Pseudo-destructor calls should not have any arguments.
2786 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2787 << CodeModificationHint::CreateRemoval(
2788 SourceRange(Args[0]->getLocStart(),
2789 Args[NumArgs-1]->getLocEnd()));
2791 for (unsigned I = 0; I != NumArgs; ++I)
2792 Args[I]->Destroy(Context);
2797 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2801 // Determine whether this is a dependent call inside a C++ template,
2802 // in which case we won't do any semantic analysis now.
2803 // FIXME: Will need to cache the results of name lookup (including ADL) in
2805 bool Dependent = false;
2806 if (Fn->isTypeDependent())
2808 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2812 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2813 Context.DependentTy, RParenLoc));
2815 // Determine whether this is a call to an object (C++ [over.call.object]).
2816 if (Fn->getType()->isRecordType())
2817 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2818 CommaLocs, RParenLoc));
2820 // Determine whether this is a call to a member function.
2821 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2822 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2823 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2824 isa<CXXMethodDecl>(MemDecl) ||
2825 (isa<FunctionTemplateDecl>(MemDecl) &&
2827 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
2828 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2829 CommaLocs, RParenLoc));
2832 // Determine whether this is a call to a pointer-to-member function.
2833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2834 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2835 BO->getOpcode() == BinaryOperator::PtrMemI) {
2836 if (const FunctionProtoType *FPT =
2837 dyn_cast<FunctionProtoType>(BO->getType())) {
2838 QualType ResultTy = FPT->getResultType().getNonReferenceType();
2840 ExprOwningPtr<CXXMemberCallExpr>
2841 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2845 if (CheckCallReturnType(FPT->getResultType(),
2846 BO->getRHS()->getSourceRange().getBegin(),
2850 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2854 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2856 return ExprError(Diag(Fn->getLocStart(),
2857 diag::err_typecheck_call_not_function)
2858 << Fn->getType() << Fn->getSourceRange());
2863 // If we're directly calling a function, get the appropriate declaration.
2864 // Also, in C++, keep track of whether we should perform argument-dependent
2865 // lookup and whether there were any explicitly-specified template arguments.
2867 bool HasExplicitTemplateArgs = 0;
2868 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
2869 unsigned NumExplicitTemplateArgs = 0;
2870 NestedNameSpecifier *Qualifier = 0;
2871 SourceRange QualifierRange;
2872 DeconstructCallFunction(Fn, NDecl, UnqualifiedName, Qualifier, QualifierRange,
2873 ADL,HasExplicitTemplateArgs, ExplicitTemplateArgs,
2874 NumExplicitTemplateArgs);
2876 OverloadedFunctionDecl *Ovl = 0;
2877 FunctionTemplateDecl *FunctionTemplate = 0;
2879 FDecl = dyn_cast<FunctionDecl>(NDecl);
2880 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
2881 FDecl = FunctionTemplate->getTemplatedDecl();
2883 FDecl = dyn_cast<FunctionDecl>(NDecl);
2884 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
2887 if (Ovl || FunctionTemplate ||
2888 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2889 // We don't perform ADL for implicit declarations of builtins.
2890 if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
2893 // We don't perform ADL in C.
2894 if (!getLangOptions().CPlusPlus)
2897 if (Ovl || FunctionTemplate || ADL) {
2898 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2899 HasExplicitTemplateArgs,
2900 ExplicitTemplateArgs,
2901 NumExplicitTemplateArgs,
2902 LParenLoc, Args, NumArgs, CommaLocs,
2907 Fn = FixOverloadedFunctionReference(Fn, FDecl);
2911 // Promote the function operand.
2912 UsualUnaryConversions(Fn);
2914 // Make the call expr early, before semantic checks. This guarantees cleanup
2915 // of arguments and function on error.
2916 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2921 const FunctionType *FuncT;
2922 if (!Fn->getType()->isBlockPointerType()) {
2923 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2924 // have type pointer to function".
2925 const PointerType *PT = Fn->getType()->getAs<PointerType>();
2927 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2928 << Fn->getType() << Fn->getSourceRange());
2929 FuncT = PT->getPointeeType()->getAs<FunctionType>();
2930 } else { // This is a block call.
2931 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
2932 getAs<FunctionType>();
2935 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2936 << Fn->getType() << Fn->getSourceRange());
2938 // Check for a valid return type
2939 if (CheckCallReturnType(FuncT->getResultType(),
2940 Fn->getSourceRange().getBegin(), TheCall.get(),
2944 // We know the result type of the call, set it.
2945 TheCall->setType(FuncT->getResultType().getNonReferenceType());
2947 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2948 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2952 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
2955 // Check if we have too few/too many template arguments, based
2956 // on our knowledge of the function definition.
2957 const FunctionDecl *Def = 0;
2958 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
2959 const FunctionProtoType *Proto =
2960 Def->getType()->getAs<FunctionProtoType>();
2961 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2962 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2963 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2968 // Promote the arguments (C99 6.5.2.2p6).
2969 for (unsigned i = 0; i != NumArgs; i++) {
2970 Expr *Arg = Args[i];
2971 DefaultArgumentPromotion(Arg);
2972 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2974 PDiag(diag::err_call_incomplete_argument)
2975 << Arg->getSourceRange()))
2977 TheCall->setArg(i, Arg);
2981 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2982 if (!Method->isStatic())
2983 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2984 << Fn->getSourceRange());
2986 // Check for sentinels
2988 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
2990 // Do special checking on direct calls to functions.
2992 if (CheckFunctionCall(FDecl, TheCall.get()))
2995 if (unsigned BuiltinID = FDecl->getBuiltinID())
2996 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2998 if (CheckBlockCall(NDecl, TheCall.get()))
3002 return MaybeBindToTemporary(TheCall.take());
3005 Action::OwningExprResult
3006 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3007 SourceLocation RParenLoc, ExprArg InitExpr) {
3008 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3009 //FIXME: Preserve type source info.
3010 QualType literalType = GetTypeFromParser(Ty);
3011 // FIXME: put back this assert when initializers are worked out.
3012 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3013 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
3015 if (literalType->isArrayType()) {
3016 if (literalType->isVariableArrayType())
3017 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3018 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
3019 } else if (!literalType->isDependentType() &&
3020 RequireCompleteType(LParenLoc, literalType,
3021 PDiag(diag::err_typecheck_decl_incomplete_type)
3022 << SourceRange(LParenLoc,
3023 literalExpr->getSourceRange().getEnd())))
3026 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
3027 DeclarationName(), /*FIXME:DirectInit=*/false))
3030 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3031 if (isFileScope) { // 6.5.2.5p3
3032 if (CheckForConstantInitializer(literalExpr, literalType))
3036 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
3037 literalExpr, isFileScope));
3040 Action::OwningExprResult
3041 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
3042 SourceLocation RBraceLoc) {
3043 unsigned NumInit = initlist.size();
3044 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
3046 // Semantic analysis for initializers is done by ActOnDeclarator() and
3047 // CheckInitializer() - it requires knowledge of the object being intialized.
3049 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
3051 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3055 static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3056 QualType SrcTy, QualType DestTy) {
3057 if (Context.getCanonicalType(SrcTy).getUnqualifiedType() ==
3058 Context.getCanonicalType(DestTy).getUnqualifiedType())
3059 return CastExpr::CK_NoOp;
3061 if (SrcTy->hasPointerRepresentation()) {
3062 if (DestTy->hasPointerRepresentation())
3063 return CastExpr::CK_BitCast;
3064 if (DestTy->isIntegerType())
3065 return CastExpr::CK_PointerToIntegral;
3068 if (SrcTy->isIntegerType()) {
3069 if (DestTy->isIntegerType())
3070 return CastExpr::CK_IntegralCast;
3071 if (DestTy->hasPointerRepresentation())
3072 return CastExpr::CK_IntegralToPointer;
3073 if (DestTy->isRealFloatingType())
3074 return CastExpr::CK_IntegralToFloating;
3077 if (SrcTy->isRealFloatingType()) {
3078 if (DestTy->isRealFloatingType())
3079 return CastExpr::CK_FloatingCast;
3080 if (DestTy->isIntegerType())
3081 return CastExpr::CK_FloatingToIntegral;
3084 // FIXME: Assert here.
3085 // assert(false && "Unhandled cast combination!");
3086 return CastExpr::CK_Unknown;
3089 /// CheckCastTypes - Check type constraints for casting between types.
3090 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
3091 CastExpr::CastKind& Kind,
3092 CXXMethodDecl *& ConversionDecl,
3093 bool FunctionalStyle) {
3094 if (getLangOptions().CPlusPlus)
3095 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3098 DefaultFunctionArrayConversion(castExpr);
3100 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3101 // type needs to be scalar.
3102 if (castType->isVoidType()) {
3103 // Cast to void allows any expr type.
3104 Kind = CastExpr::CK_ToVoid;
3108 if (!castType->isScalarType() && !castType->isVectorType()) {
3109 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3110 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3111 (castType->isStructureType() || castType->isUnionType())) {
3112 // GCC struct/union extension: allow cast to self.
3113 // FIXME: Check that the cast destination type is complete.
3114 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3115 << castType << castExpr->getSourceRange();
3116 Kind = CastExpr::CK_NoOp;
3120 if (castType->isUnionType()) {
3121 // GCC cast to union extension
3122 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
3123 RecordDecl::field_iterator Field, FieldEnd;
3124 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
3125 Field != FieldEnd; ++Field) {
3126 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3127 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3128 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3129 << castExpr->getSourceRange();
3133 if (Field == FieldEnd)
3134 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3135 << castExpr->getType() << castExpr->getSourceRange();
3136 Kind = CastExpr::CK_ToUnion;
3140 // Reject any other conversions to non-scalar types.
3141 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3142 << castType << castExpr->getSourceRange();
3145 if (!castExpr->getType()->isScalarType() &&
3146 !castExpr->getType()->isVectorType()) {
3147 return Diag(castExpr->getLocStart(),
3148 diag::err_typecheck_expect_scalar_operand)
3149 << castExpr->getType() << castExpr->getSourceRange();
3152 if (castType->isExtVectorType())
3153 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3155 if (castType->isVectorType())
3156 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3157 if (castExpr->getType()->isVectorType())
3158 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3160 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
3161 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
3163 if (isa<ObjCSelectorExpr>(castExpr))
3164 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3166 if (!castType->isArithmeticType()) {
3167 QualType castExprType = castExpr->getType();
3168 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3169 return Diag(castExpr->getLocStart(),
3170 diag::err_cast_pointer_from_non_pointer_int)
3171 << castExprType << castExpr->getSourceRange();
3172 } else if (!castExpr->getType()->isArithmeticType()) {
3173 if (!castType->isIntegralType() && castType->isArithmeticType())
3174 return Diag(castExpr->getLocStart(),
3175 diag::err_cast_pointer_to_non_pointer_int)
3176 << castType << castExpr->getSourceRange();
3179 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
3183 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3184 CastExpr::CastKind &Kind) {
3185 assert(VectorTy->isVectorType() && "Not a vector type!");
3187 if (Ty->isVectorType() || Ty->isIntegerType()) {
3188 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
3189 return Diag(R.getBegin(),
3190 Ty->isVectorType() ?
3191 diag::err_invalid_conversion_between_vectors :
3192 diag::err_invalid_conversion_between_vector_and_integer)
3193 << VectorTy << Ty << R;
3195 return Diag(R.getBegin(),
3196 diag::err_invalid_conversion_between_vector_and_scalar)
3197 << VectorTy << Ty << R;
3199 Kind = CastExpr::CK_BitCast;
3203 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3204 CastExpr::CastKind &Kind) {
3205 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3207 QualType SrcTy = CastExpr->getType();
3209 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3210 // an ExtVectorType.
3211 if (SrcTy->isVectorType()) {
3212 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3213 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3214 << DestTy << SrcTy << R;
3215 Kind = CastExpr::CK_BitCast;
3219 // All non-pointer scalars can be cast to ExtVector type. The appropriate
3220 // conversion will take place first from scalar to elt type, and then
3221 // splat from elt type to vector.
3222 if (SrcTy->isPointerType())
3223 return Diag(R.getBegin(),
3224 diag::err_invalid_conversion_between_vector_and_scalar)
3225 << DestTy << SrcTy << R;
3227 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3228 ImpCastExprToType(CastExpr, DestElemTy,
3229 getScalarCastKind(Context, SrcTy, DestElemTy));
3231 Kind = CastExpr::CK_VectorSplat;
3235 Action::OwningExprResult
3236 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
3237 SourceLocation RParenLoc, ExprArg Op) {
3238 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3240 assert((Ty != 0) && (Op.get() != 0) &&
3241 "ActOnCastExpr(): missing type or expr");
3243 Expr *castExpr = (Expr *)Op.get();
3244 //FIXME: Preserve type source info.
3245 QualType castType = GetTypeFromParser(Ty);
3247 // If the Expr being casted is a ParenListExpr, handle it specially.
3248 if (isa<ParenListExpr>(castExpr))
3249 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
3250 CXXMethodDecl *Method = 0;
3251 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3256 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
3259 if (CastArg.isInvalid())
3262 castExpr = CastArg.takeAs<Expr>();
3267 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
3268 Kind, castExpr, castType,
3269 LParenLoc, RParenLoc));
3272 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3273 /// of comma binary operators.
3274 Action::OwningExprResult
3275 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3276 Expr *expr = EA.takeAs<Expr>();
3277 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3281 OwningExprResult Result(*this, E->getExpr(0));
3283 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3284 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3285 Owned(E->getExpr(i)));
3287 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3290 Action::OwningExprResult
3291 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3292 SourceLocation RParenLoc, ExprArg Op,
3294 ParenListExpr *PE = (ParenListExpr *)Op.get();
3296 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3297 // then handle it as such.
3298 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3299 if (PE->getNumExprs() == 0) {
3300 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3304 llvm::SmallVector<Expr *, 8> initExprs;
3305 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3306 initExprs.push_back(PE->getExpr(i));
3308 // FIXME: This means that pretty-printing the final AST will produce curly
3309 // braces instead of the original commas.
3311 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3312 initExprs.size(), RParenLoc);
3314 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3317 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3318 // sequence of BinOp comma operators.
3319 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3320 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3324 Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3327 unsigned nexprs = Val.size();
3328 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3329 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3330 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3334 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3335 /// In that case, lhs = cond.
3337 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3338 SourceLocation QuestionLoc) {
3339 // C++ is sufficiently different to merit its own checker.
3340 if (getLangOptions().CPlusPlus)
3341 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3343 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3345 UsualUnaryConversions(Cond);
3346 UsualUnaryConversions(LHS);
3347 UsualUnaryConversions(RHS);
3348 QualType CondTy = Cond->getType();
3349 QualType LHSTy = LHS->getType();
3350 QualType RHSTy = RHS->getType();
3352 // first, check the condition.
3353 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3354 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3359 // Now check the two expressions.
3360 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3361 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3363 // If both operands have arithmetic type, do the usual arithmetic conversions
3364 // to find a common type: C99 6.5.15p3,5.
3365 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3366 UsualArithmeticConversions(LHS, RHS);
3367 return LHS->getType();
3370 // If both operands are the same structure or union type, the result is that
3372 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3373 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
3374 if (LHSRT->getDecl() == RHSRT->getDecl())
3375 // "If both the operands have structure or union type, the result has
3376 // that type." This implies that CV qualifiers are dropped.
3377 return LHSTy.getUnqualifiedType();
3378 // FIXME: Type of conditional expression must be complete in C mode.
3381 // C99 6.5.15p5: "If both operands have void type, the result has void type."
3382 // The following || allows only one side to be void (a GCC-ism).
3383 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3384 if (!LHSTy->isVoidType())
3385 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3386 << RHS->getSourceRange();
3387 if (!RHSTy->isVoidType())
3388 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3389 << LHS->getSourceRange();
3390 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3391 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
3392 return Context.VoidTy;
3394 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3395 // the type of the other operand."
3396 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
3397 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3398 // promote the null to a pointer.
3399 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
3402 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
3403 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3404 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
3407 // Handle things like Class and struct objc_class*. Here we case the result
3408 // to the pseudo-builtin, because that will be implicitly cast back to the
3409 // redefinition type if an attempt is made to access its fields.
3410 if (LHSTy->isObjCClassType() &&
3411 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3412 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3415 if (RHSTy->isObjCClassType() &&
3416 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3417 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3420 // And the same for struct objc_object* / id
3421 if (LHSTy->isObjCIdType() &&
3422 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3423 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3426 if (RHSTy->isObjCIdType() &&
3427 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3428 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3431 // Handle block pointer types.
3432 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3433 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3434 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3435 QualType destType = Context.getPointerType(Context.VoidTy);
3436 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3437 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
3440 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3441 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3444 // We have 2 block pointer types.
3445 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3446 // Two identical block pointer types are always compatible.
3449 // The block pointer types aren't identical, continue checking.
3450 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3451 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
3453 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3454 rhptee.getUnqualifiedType())) {
3455 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3456 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3457 // In this situation, we assume void* type. No especially good
3458 // reason, but this is what gcc does, and we do have to pick
3459 // to get a consistent AST.
3460 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3461 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3462 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
3465 // The block pointer types are compatible.
3466 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3467 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3470 // Check constraints for Objective-C object pointers types.
3471 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
3473 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3474 // Two identical object pointer types are always compatible.
3477 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3478 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
3479 QualType compositeType = LHSTy;
3481 // If both operands are interfaces and either operand can be
3482 // assigned to the other, use that type as the composite
3483 // type. This allows
3484 // xxx ? (A*) a : (B*) b
3485 // where B is a subclass of A.
3487 // Additionally, as for assignment, if either type is 'id'
3488 // allow silent coercion. Finally, if the types are
3489 // incompatible then make sure to use 'id' as the composite
3490 // type so the result is acceptable for sending messages to.
3492 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3493 // It could return the composite type.
3494 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
3495 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
3496 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
3497 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
3498 } else if ((LHSTy->isObjCQualifiedIdType() ||
3499 RHSTy->isObjCQualifiedIdType()) &&
3500 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
3501 // Need to handle "id<xx>" explicitly.
3502 // GCC allows qualified id and any Objective-C type to devolve to
3503 // id. Currently localizing to here until clear this should be
3504 // part of ObjCQualifiedIdTypesAreCompatible.
3505 compositeType = Context.getObjCIdType();
3506 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
3507 compositeType = Context.getObjCIdType();
3508 } else if (!(compositeType =
3509 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3512 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3514 << LHS->getSourceRange() << RHS->getSourceRange();
3515 QualType incompatTy = Context.getObjCIdType();
3516 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3517 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
3520 // The object pointer types are compatible.
3521 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3522 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
3523 return compositeType;
3525 // Check Objective-C object pointer types and 'void *'
3526 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
3527 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3528 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
3529 QualType destPointee
3530 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
3531 QualType destType = Context.getPointerType(destPointee);
3532 // Add qualifiers if necessary.
3533 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3534 // Promote to void*.
3535 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
3538 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3539 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
3540 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3541 QualType destPointee
3542 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
3543 QualType destType = Context.getPointerType(destPointee);
3544 // Add qualifiers if necessary.
3545 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3546 // Promote to void*.
3547 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3550 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3551 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3552 // get the "pointed to" types
3553 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3554 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3556 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3557 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3558 // Figure out necessary qualifiers (C99 6.5.15p6)
3559 QualType destPointee
3560 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
3561 QualType destType = Context.getPointerType(destPointee);
3562 // Add qualifiers if necessary.
3563 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3564 // Promote to void*.
3565 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
3568 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3569 QualType destPointee
3570 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
3571 QualType destType = Context.getPointerType(destPointee);
3572 // Add qualifiers if necessary.
3573 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3574 // Promote to void*.
3575 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
3579 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3580 // Two identical pointer types are always compatible.
3583 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3584 rhptee.getUnqualifiedType())) {
3585 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3586 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3587 // In this situation, we assume void* type. No especially good
3588 // reason, but this is what gcc does, and we do have to pick
3589 // to get a consistent AST.
3590 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3591 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3592 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
3595 // The pointer types are compatible.
3596 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3597 // differently qualified versions of compatible types, the result type is
3598 // a pointer to an appropriately qualified version of the *composite*
3600 // FIXME: Need to calculate the composite type.
3601 // FIXME: Need to add qualifiers
3602 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3603 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3607 // GCC compatibility: soften pointer/integer mismatch.
3608 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3609 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3610 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3611 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
3614 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3615 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3616 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3617 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
3621 // Otherwise, the operands are not compatible.
3622 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3623 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3627 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
3628 /// in the case of a the GNU conditional expr extension.
3629 Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3630 SourceLocation ColonLoc,
3631 ExprArg Cond, ExprArg LHS,
3633 Expr *CondExpr = (Expr *) Cond.get();
3634 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
3636 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3637 // was the condition.
3638 bool isLHSNull = LHSExpr == 0;
3642 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
3643 RHSExpr, QuestionLoc);
3644 if (result.isNull())
3650 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
3651 isLHSNull ? 0 : LHSExpr,
3652 ColonLoc, RHSExpr, result));
3655 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
3656 // being closely modeled after the C99 spec:-). The odd characteristic of this
3657 // routine is it effectively iqnores the qualifiers on the top level pointee.
3658 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3659 // FIXME: add a couple examples in this comment.
3660 Sema::AssignConvertType
3661 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3662 QualType lhptee, rhptee;
3664 if ((lhsType->isObjCClassType() &&
3665 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3666 (rhsType->isObjCClassType() &&
3667 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3671 // get the "pointed to" type (ignoring qualifiers at the top level)
3672 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3673 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
3675 // make sure we operate on the canonical type
3676 lhptee = Context.getCanonicalType(lhptee);
3677 rhptee = Context.getCanonicalType(rhptee);
3679 AssignConvertType ConvTy = Compatible;
3681 // C99 6.5.16.1p1: This following citation is common to constraints
3682 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3683 // qualifiers of the type *pointed to* by the right;
3684 // FIXME: Handle ExtQualType
3685 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
3686 ConvTy = CompatiblePointerDiscardsQualifiers;
3688 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3689 // incomplete type and the other is a pointer to a qualified or unqualified
3690 // version of void...
3691 if (lhptee->isVoidType()) {
3692 if (rhptee->isIncompleteOrObjectType())
3695 // As an extension, we allow cast to/from void* to function pointer.
3696 assert(rhptee->isFunctionType());
3697 return FunctionVoidPointer;
3700 if (rhptee->isVoidType()) {
3701 if (lhptee->isIncompleteOrObjectType())
3704 // As an extension, we allow cast to/from void* to function pointer.
3705 assert(lhptee->isFunctionType());
3706 return FunctionVoidPointer;
3708 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
3709 // unqualified versions of compatible types, ...
3710 lhptee = lhptee.getUnqualifiedType();
3711 rhptee = rhptee.getUnqualifiedType();
3712 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3713 // Check if the pointee types are compatible ignoring the sign.
3714 // We explicitly check for char so that we catch "char" vs
3715 // "unsigned char" on systems where "char" is unsigned.
3716 if (lhptee->isCharType())
3717 lhptee = Context.UnsignedCharTy;
3718 else if (lhptee->isSignedIntegerType())
3719 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3721 if (rhptee->isCharType())
3722 rhptee = Context.UnsignedCharTy;
3723 else if (rhptee->isSignedIntegerType())
3724 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3726 if (lhptee == rhptee) {
3727 // Types are compatible ignoring the sign. Qualifier incompatibility
3728 // takes priority over sign incompatibility because the sign
3729 // warning can be disabled.
3730 if (ConvTy != Compatible)
3732 return IncompatiblePointerSign;
3734 // General pointer incompatibility takes priority over qualifiers.
3735 return IncompatiblePointer;
3740 /// CheckBlockPointerTypesForAssignment - This routine determines whether two
3741 /// block pointer types are compatible or whether a block and normal pointer
3742 /// are compatible. It is more restrict than comparing two function pointer
3744 Sema::AssignConvertType
3745 Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
3747 QualType lhptee, rhptee;
3749 // get the "pointed to" type (ignoring qualifiers at the top level)
3750 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3751 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
3753 // make sure we operate on the canonical type
3754 lhptee = Context.getCanonicalType(lhptee);
3755 rhptee = Context.getCanonicalType(rhptee);
3757 AssignConvertType ConvTy = Compatible;
3759 // For blocks we enforce that qualifiers are identical.
3760 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3761 ConvTy = CompatiblePointerDiscardsQualifiers;
3763 if (!Context.typesAreCompatible(lhptee, rhptee))
3764 return IncompatibleBlockPointer;
3768 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3769 /// has code to accommodate several GCC extensions when type checking
3770 /// pointers. Here are some objectionable examples that GCC considers warnings:
3774 /// struct foo *pfoo;
3776 /// pint = pshort; // warning: assignment from incompatible pointer type
3777 /// a = pint; // warning: assignment makes integer from pointer without a cast
3778 /// pint = a; // warning: assignment makes pointer from integer without a cast
3779 /// pint = pfoo; // warning: assignment from incompatible pointer type
3781 /// As a result, the code for dealing with pointers is more complex than the
3782 /// C99 spec dictates.
3784 Sema::AssignConvertType
3785 Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
3786 // Get canonical types. We're not formatting these types, just comparing
3788 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3789 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
3791 if (lhsType == rhsType)
3792 return Compatible; // Common case: fast path an exact match.
3794 if ((lhsType->isObjCClassType() &&
3795 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3796 (rhsType->isObjCClassType() &&
3797 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3801 // If the left-hand side is a reference type, then we are in a
3802 // (rare!) case where we've allowed the use of references in C,
3803 // e.g., as a parameter type in a built-in function. In this case,
3804 // just make sure that the type referenced is compatible with the
3805 // right-hand side type. The caller is responsible for adjusting
3806 // lhsType so that the resulting expression does not have reference
3808 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
3809 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
3811 return Incompatible;
3813 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3814 // to the same ExtVector type.
3815 if (lhsType->isExtVectorType()) {
3816 if (rhsType->isExtVectorType())
3817 return lhsType == rhsType ? Compatible : Incompatible;
3818 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3822 if (lhsType->isVectorType() || rhsType->isVectorType()) {
3823 // If we are allowing lax vector conversions, and LHS and RHS are both
3824 // vectors, the total size only needs to be the same. This is a bitcast;
3825 // no bits are changed but the result type is different.
3826 if (getLangOptions().LaxVectorConversions &&
3827 lhsType->isVectorType() && rhsType->isVectorType()) {
3828 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
3829 return IncompatibleVectors;
3831 return Incompatible;
3834 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
3837 if (isa<PointerType>(lhsType)) {
3838 if (rhsType->isIntegerType())
3839 return IntToPointer;
3841 if (isa<PointerType>(rhsType))
3842 return CheckPointerTypesForAssignment(lhsType, rhsType);
3844 // In general, C pointers are not compatible with ObjC object pointers.
3845 if (isa<ObjCObjectPointerType>(rhsType)) {
3846 if (lhsType->isVoidPointerType()) // an exception to the rule.
3848 return IncompatiblePointer;
3850 if (rhsType->getAs<BlockPointerType>()) {
3851 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3854 // Treat block pointers as objects.
3855 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
3858 return Incompatible;
3861 if (isa<BlockPointerType>(lhsType)) {
3862 if (rhsType->isIntegerType())
3863 return IntToBlockPointer;
3865 // Treat block pointers as objects.
3866 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
3869 if (rhsType->isBlockPointerType())
3870 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
3872 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3873 if (RHSPT->getPointeeType()->isVoidType())
3876 return Incompatible;
3879 if (isa<ObjCObjectPointerType>(lhsType)) {
3880 if (rhsType->isIntegerType())
3881 return IntToPointer;
3883 // In general, C pointers are not compatible with ObjC object pointers.
3884 if (isa<PointerType>(rhsType)) {
3885 if (rhsType->isVoidPointerType()) // an exception to the rule.
3887 return IncompatiblePointer;
3889 if (rhsType->isObjCObjectPointerType()) {
3890 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3892 if (Context.typesAreCompatible(lhsType, rhsType))
3894 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3895 return IncompatibleObjCQualifiedId;
3896 return IncompatiblePointer;
3898 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3899 if (RHSPT->getPointeeType()->isVoidType())
3902 // Treat block pointers as objects.
3903 if (rhsType->isBlockPointerType())
3905 return Incompatible;
3907 if (isa<PointerType>(rhsType)) {
3908 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3909 if (lhsType == Context.BoolTy)
3912 if (lhsType->isIntegerType())
3913 return PointerToInt;
3915 if (isa<PointerType>(lhsType))
3916 return CheckPointerTypesForAssignment(lhsType, rhsType);
3918 if (isa<BlockPointerType>(lhsType) &&
3919 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3921 return Incompatible;
3923 if (isa<ObjCObjectPointerType>(rhsType)) {
3924 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3925 if (lhsType == Context.BoolTy)
3928 if (lhsType->isIntegerType())
3929 return PointerToInt;
3931 // In general, C pointers are not compatible with ObjC object pointers.
3932 if (isa<PointerType>(lhsType)) {
3933 if (lhsType->isVoidPointerType()) // an exception to the rule.
3935 return IncompatiblePointer;
3937 if (isa<BlockPointerType>(lhsType) &&
3938 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3940 return Incompatible;
3943 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
3944 if (Context.typesAreCompatible(lhsType, rhsType))
3947 return Incompatible;
3950 /// \brief Constructs a transparent union from an expression that is
3951 /// used to initialize the transparent union.
3952 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3953 QualType UnionType, FieldDecl *Field) {
3954 // Build an initializer list that designates the appropriate member
3955 // of the transparent union.
3956 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3959 Initializer->setType(UnionType);
3960 Initializer->setInitializedFieldInUnion(Field);
3962 // Build a compound literal constructing a value of the transparent
3963 // union type from this initializer list.
3964 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3968 Sema::AssignConvertType
3969 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3970 QualType FromType = rExpr->getType();
3972 // If the ArgType is a Union type, we want to handle a potential
3973 // transparent_union GCC extension.
3974 const RecordType *UT = ArgType->getAsUnionType();
3975 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3976 return Incompatible;
3978 // The field to initialize within the transparent union.
3979 RecordDecl *UD = UT->getDecl();
3980 FieldDecl *InitField = 0;
3981 // It's compatible if the expression matches any of the fields.
3982 for (RecordDecl::field_iterator it = UD->field_begin(),
3983 itend = UD->field_end();
3984 it != itend; ++it) {
3985 if (it->getType()->isPointerType()) {
3986 // If the transparent union contains a pointer type, we allow:
3988 // 2) null pointer constant
3989 if (FromType->isPointerType())
3990 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
3991 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
3996 if (rExpr->isNullPointerConstant(Context,
3997 Expr::NPC_ValueDependentIsNull)) {
3998 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
4004 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4012 return Incompatible;
4014 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4018 Sema::AssignConvertType
4019 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
4020 if (getLangOptions().CPlusPlus) {
4021 if (!lhsType->isRecordType()) {
4022 // C++ 5.17p3: If the left operand is not of class type, the
4023 // expression is implicitly converted (C++ 4) to the
4024 // cv-unqualified type of the left operand.
4025 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4027 return Incompatible;
4031 // FIXME: Currently, we fall through and treat C++ classes like C
4035 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4036 // a null pointer constant.
4037 if ((lhsType->isPointerType() ||
4038 lhsType->isObjCObjectPointerType() ||
4039 lhsType->isBlockPointerType())
4040 && rExpr->isNullPointerConstant(Context,
4041 Expr::NPC_ValueDependentIsNull)) {
4042 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
4046 // This check seems unnatural, however it is necessary to ensure the proper
4047 // conversion of functions/arrays. If the conversion were done for all
4048 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
4049 // expressions that surpress this implicit conversion (&, sizeof).
4051 // Suppress this for references: C++ 8.5.3p5.
4052 if (!lhsType->isReferenceType())
4053 DefaultFunctionArrayConversion(rExpr);
4055 Sema::AssignConvertType result =
4056 CheckAssignmentConstraints(lhsType, rExpr->getType());
4058 // C99 6.5.16.1p2: The value of the right operand is converted to the
4059 // type of the assignment expression.
4060 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4061 // so that we can use references in built-in functions even in C.
4062 // The getNonReferenceType() call makes sure that the resulting expression
4063 // does not have reference type.
4064 if (result != Incompatible && rExpr->getType() != lhsType)
4065 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4066 CastExpr::CK_Unknown);
4070 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4071 Diag(Loc, diag::err_typecheck_invalid_operands)
4072 << lex->getType() << rex->getType()
4073 << lex->getSourceRange() << rex->getSourceRange();
4077 inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
4079 // For conversion purposes, we ignore any qualifiers.
4080 // For example, "const float" and "float" are equivalent.
4082 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4084 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
4086 // If the vector types are identical, return.
4087 if (lhsType == rhsType)
4090 // Handle the case of a vector & extvector type of the same size and element
4091 // type. It would be nice if we only had one vector type someday.
4092 if (getLangOptions().LaxVectorConversions) {
4093 // FIXME: Should we warn here?
4094 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4095 if (const VectorType *RV = rhsType->getAs<VectorType>())
4096 if (LV->getElementType() == RV->getElementType() &&
4097 LV->getNumElements() == RV->getNumElements()) {
4098 return lhsType->isExtVectorType() ? lhsType : rhsType;
4103 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4104 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4105 bool swapped = false;
4106 if (rhsType->isExtVectorType()) {
4108 std::swap(rex, lex);
4109 std::swap(rhsType, lhsType);
4112 // Handle the case of an ext vector and scalar.
4113 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
4114 QualType EltTy = LV->getElementType();
4115 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4116 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
4117 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
4118 if (swapped) std::swap(rex, lex);
4122 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4123 rhsType->isRealFloatingType()) {
4124 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
4125 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
4126 if (swapped) std::swap(rex, lex);
4132 // Vectors of different size or scalar and non-ext-vector are errors.
4133 Diag(Loc, diag::err_typecheck_vector_not_convertable)
4134 << lex->getType() << rex->getType()
4135 << lex->getSourceRange() << rex->getSourceRange();
4139 inline QualType Sema::CheckMultiplyDivideOperands(
4140 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4141 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4142 return CheckVectorOperands(Loc, lex, rex);
4144 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4146 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4148 return InvalidOperands(Loc, lex, rex);
4151 inline QualType Sema::CheckRemainderOperands(
4152 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4153 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4154 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4155 return CheckVectorOperands(Loc, lex, rex);
4156 return InvalidOperands(Loc, lex, rex);
4159 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4161 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4163 return InvalidOperands(Loc, lex, rex);
4166 inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
4167 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
4168 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4169 QualType compType = CheckVectorOperands(Loc, lex, rex);
4170 if (CompLHSTy) *CompLHSTy = compType;
4174 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4176 // handle the common case first (both operands are arithmetic).
4177 if (lex->getType()->isArithmeticType() &&
4178 rex->getType()->isArithmeticType()) {
4179 if (CompLHSTy) *CompLHSTy = compType;
4183 // Put any potential pointer into PExp
4184 Expr* PExp = lex, *IExp = rex;
4185 if (IExp->getType()->isAnyPointerType())
4186 std::swap(PExp, IExp);
4188 if (PExp->getType()->isAnyPointerType()) {
4190 if (IExp->getType()->isIntegerType()) {
4191 QualType PointeeTy = PExp->getType()->getPointeeType();
4193 // Check for arithmetic on pointers to incomplete types.
4194 if (PointeeTy->isVoidType()) {
4195 if (getLangOptions().CPlusPlus) {
4196 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4197 << lex->getSourceRange() << rex->getSourceRange();
4201 // GNU extension: arithmetic on pointer to void
4202 Diag(Loc, diag::ext_gnu_void_ptr)
4203 << lex->getSourceRange() << rex->getSourceRange();
4204 } else if (PointeeTy->isFunctionType()) {
4205 if (getLangOptions().CPlusPlus) {
4206 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4207 << lex->getType() << lex->getSourceRange();
4211 // GNU extension: arithmetic on pointer to function
4212 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4213 << lex->getType() << lex->getSourceRange();
4215 // Check if we require a complete type.
4216 if (((PExp->getType()->isPointerType() &&
4217 !PExp->getType()->isDependentType()) ||
4218 PExp->getType()->isObjCObjectPointerType()) &&
4219 RequireCompleteType(Loc, PointeeTy,
4220 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4221 << PExp->getSourceRange()
4222 << PExp->getType()))
4225 // Diagnose bad cases where we step over interface counts.
4226 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4227 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4228 << PointeeTy << PExp->getSourceRange();
4233 QualType LHSTy = Context.isPromotableBitField(lex);
4234 if (LHSTy.isNull()) {
4235 LHSTy = lex->getType();
4236 if (LHSTy->isPromotableIntegerType())
4237 LHSTy = Context.getPromotedIntegerType(LHSTy);
4241 return PExp->getType();
4245 return InvalidOperands(Loc, lex, rex);
4249 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
4250 SourceLocation Loc, QualType* CompLHSTy) {
4251 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4252 QualType compType = CheckVectorOperands(Loc, lex, rex);
4253 if (CompLHSTy) *CompLHSTy = compType;
4257 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4259 // Enforce type constraints: C99 6.5.6p3.
4261 // Handle the common case first (both operands are arithmetic).
4262 if (lex->getType()->isArithmeticType()
4263 && rex->getType()->isArithmeticType()) {
4264 if (CompLHSTy) *CompLHSTy = compType;
4268 // Either ptr - int or ptr - ptr.
4269 if (lex->getType()->isAnyPointerType()) {
4270 QualType lpointee = lex->getType()->getPointeeType();
4272 // The LHS must be an completely-defined object type.
4274 bool ComplainAboutVoid = false;
4275 Expr *ComplainAboutFunc = 0;
4276 if (lpointee->isVoidType()) {
4277 if (getLangOptions().CPlusPlus) {
4278 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4279 << lex->getSourceRange() << rex->getSourceRange();
4283 // GNU C extension: arithmetic on pointer to void
4284 ComplainAboutVoid = true;
4285 } else if (lpointee->isFunctionType()) {
4286 if (getLangOptions().CPlusPlus) {
4287 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4288 << lex->getType() << lex->getSourceRange();
4292 // GNU C extension: arithmetic on pointer to function
4293 ComplainAboutFunc = lex;
4294 } else if (!lpointee->isDependentType() &&
4295 RequireCompleteType(Loc, lpointee,
4296 PDiag(diag::err_typecheck_sub_ptr_object)
4297 << lex->getSourceRange()
4301 // Diagnose bad cases where we step over interface counts.
4302 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4303 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4304 << lpointee << lex->getSourceRange();
4308 // The result type of a pointer-int computation is the pointer type.
4309 if (rex->getType()->isIntegerType()) {
4310 if (ComplainAboutVoid)
4311 Diag(Loc, diag::ext_gnu_void_ptr)
4312 << lex->getSourceRange() << rex->getSourceRange();
4313 if (ComplainAboutFunc)
4314 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4315 << ComplainAboutFunc->getType()
4316 << ComplainAboutFunc->getSourceRange();
4318 if (CompLHSTy) *CompLHSTy = lex->getType();
4319 return lex->getType();
4322 // Handle pointer-pointer subtractions.
4323 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
4324 QualType rpointee = RHSPTy->getPointeeType();
4326 // RHS must be a completely-type object type.
4327 // Handle the GNU void* extension.
4328 if (rpointee->isVoidType()) {
4329 if (getLangOptions().CPlusPlus) {
4330 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4331 << lex->getSourceRange() << rex->getSourceRange();
4335 ComplainAboutVoid = true;
4336 } else if (rpointee->isFunctionType()) {
4337 if (getLangOptions().CPlusPlus) {
4338 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4339 << rex->getType() << rex->getSourceRange();
4343 // GNU extension: arithmetic on pointer to function
4344 if (!ComplainAboutFunc)
4345 ComplainAboutFunc = rex;
4346 } else if (!rpointee->isDependentType() &&
4347 RequireCompleteType(Loc, rpointee,
4348 PDiag(diag::err_typecheck_sub_ptr_object)
4349 << rex->getSourceRange()
4353 if (getLangOptions().CPlusPlus) {
4354 // Pointee types must be the same: C++ [expr.add]
4355 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4356 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4357 << lex->getType() << rex->getType()
4358 << lex->getSourceRange() << rex->getSourceRange();
4362 // Pointee types must be compatible C99 6.5.6p3
4363 if (!Context.typesAreCompatible(
4364 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4365 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4366 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4367 << lex->getType() << rex->getType()
4368 << lex->getSourceRange() << rex->getSourceRange();
4373 if (ComplainAboutVoid)
4374 Diag(Loc, diag::ext_gnu_void_ptr)
4375 << lex->getSourceRange() << rex->getSourceRange();
4376 if (ComplainAboutFunc)
4377 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4378 << ComplainAboutFunc->getType()
4379 << ComplainAboutFunc->getSourceRange();
4381 if (CompLHSTy) *CompLHSTy = lex->getType();
4382 return Context.getPointerDiffType();
4386 return InvalidOperands(Loc, lex, rex);
4390 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4391 bool isCompAssign) {
4392 // C99 6.5.7p2: Each of the operands shall have integer type.
4393 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4394 return InvalidOperands(Loc, lex, rex);
4396 // Vector shifts promote their scalar inputs to vector type.
4397 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4398 return CheckVectorOperands(Loc, lex, rex);
4400 // Shifts don't perform usual arithmetic conversions, they just do integer
4401 // promotions on each operand. C99 6.5.7p3
4402 QualType LHSTy = Context.isPromotableBitField(lex);
4403 if (LHSTy.isNull()) {
4404 LHSTy = lex->getType();
4405 if (LHSTy->isPromotableIntegerType())
4406 LHSTy = Context.getPromotedIntegerType(LHSTy);
4409 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
4411 UsualUnaryConversions(rex);
4413 // Sanity-check shift operands
4415 // Check right/shifter operand
4416 if (!rex->isValueDependent() &&
4417 rex->isIntegerConstantExpr(Right, Context)) {
4418 if (Right.isNegative())
4419 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4421 llvm::APInt LeftBits(Right.getBitWidth(),
4422 Context.getTypeSize(lex->getType()));
4423 if (Right.uge(LeftBits))
4424 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4428 // "The type of the result is that of the promoted left operand."
4432 /// Implements -Wsign-compare.
4433 void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
4434 const PartialDiagnostic &PD) {
4435 QualType lt = lex->getType(), rt = rex->getType();
4437 // Only warn if both operands are integral.
4438 if (!lt->isIntegerType() || !rt->isIntegerType())
4441 // The rule is that the signed operand becomes unsigned, so isolate the
4443 Expr *signedOperand;
4444 if (lt->isSignedIntegerType()) {
4445 if (rt->isSignedIntegerType()) return;
4446 signedOperand = lex;
4448 if (!rt->isSignedIntegerType()) return;
4449 signedOperand = rex;
4452 // If the value is a non-negative integer constant, then the
4453 // signed->unsigned conversion won't change it.
4455 if (signedOperand->isIntegerConstantExpr(value, Context)) {
4456 assert(value.isSigned() && "result of signed expression not signed");
4458 if (value.isNonNegative())
4463 << lex->getType() << rex->getType()
4464 << lex->getSourceRange() << rex->getSourceRange();
4467 // C99 6.5.8, C++ [expr.rel]
4468 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4469 unsigned OpaqueOpc, bool isRelational) {
4470 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4472 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4473 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
4475 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison);
4477 // C99 6.5.8p3 / C99 6.5.9p4
4478 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4479 UsualArithmeticConversions(lex, rex);
4481 UsualUnaryConversions(lex);
4482 UsualUnaryConversions(rex);
4484 QualType lType = lex->getType();
4485 QualType rType = rex->getType();
4487 if (!lType->isFloatingType()
4488 && !(lType->isBlockPointerType() && isRelational)) {
4489 // For non-floating point types, check for self-comparisons of the form
4490 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4491 // often indicate logic errors in the program.
4492 // NOTE: Don't warn about comparisons of enum constants. These can arise
4493 // from macro expansions, and are usually quite deliberate.
4494 Expr *LHSStripped = lex->IgnoreParens();
4495 Expr *RHSStripped = rex->IgnoreParens();
4496 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4497 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
4498 if (DRL->getDecl() == DRR->getDecl() &&
4499 !isa<EnumConstantDecl>(DRL->getDecl()))
4500 Diag(Loc, diag::warn_selfcomparison);
4502 if (isa<CastExpr>(LHSStripped))
4503 LHSStripped = LHSStripped->IgnoreParenCasts();
4504 if (isa<CastExpr>(RHSStripped))
4505 RHSStripped = RHSStripped->IgnoreParenCasts();
4507 // Warn about comparisons against a string constant (unless the other
4508 // operand is null), the user probably wants strcmp.
4509 Expr *literalString = 0;
4510 Expr *literalStringStripped = 0;
4511 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
4512 !RHSStripped->isNullPointerConstant(Context,
4513 Expr::NPC_ValueDependentIsNull)) {
4514 literalString = lex;
4515 literalStringStripped = LHSStripped;
4516 } else if ((isa<StringLiteral>(RHSStripped) ||
4517 isa<ObjCEncodeExpr>(RHSStripped)) &&
4518 !LHSStripped->isNullPointerConstant(Context,
4519 Expr::NPC_ValueDependentIsNull)) {
4520 literalString = rex;
4521 literalStringStripped = RHSStripped;
4524 if (literalString) {
4525 std::string resultComparison;
4527 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4528 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4529 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4530 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4531 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4532 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4533 default: assert(false && "Invalid comparison operator");
4535 Diag(Loc, diag::warn_stringcompare)
4536 << isa<ObjCEncodeExpr>(literalStringStripped)
4537 << literalString->getSourceRange()
4538 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4539 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4541 << CodeModificationHint::CreateInsertion(
4542 PP.getLocForEndOfToken(rex->getLocEnd()),
4547 // The result of comparisons is 'bool' in C++, 'int' in C.
4548 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
4551 if (lType->isRealType() && rType->isRealType())
4554 // Check for comparisons of floating point operands using != and ==.
4555 if (lType->isFloatingType()) {
4556 assert(rType->isFloatingType());
4557 CheckFloatComparison(Loc,lex,rex);
4560 if (lType->isArithmeticType() && rType->isArithmeticType())
4564 bool LHSIsNull = lex->isNullPointerConstant(Context,
4565 Expr::NPC_ValueDependentIsNull);
4566 bool RHSIsNull = rex->isNullPointerConstant(Context,
4567 Expr::NPC_ValueDependentIsNull);
4569 // All of the following pointer related warnings are GCC extensions, except
4570 // when handling null pointer constants. One day, we can consider making them
4571 // errors (when -pedantic-errors is enabled).
4572 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
4573 QualType LCanPointeeTy =
4574 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
4575 QualType RCanPointeeTy =
4576 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
4578 if (getLangOptions().CPlusPlus) {
4579 if (LCanPointeeTy == RCanPointeeTy)
4582 // C++ [expr.rel]p2:
4583 // [...] Pointer conversions (4.10) and qualification
4584 // conversions (4.4) are performed on pointer operands (or on
4585 // a pointer operand and a null pointer constant) to bring
4586 // them to their composite pointer type. [...]
4588 // C++ [expr.eq]p1 uses the same notion for (in)equality
4589 // comparisons of pointers.
4590 QualType T = FindCompositePointerType(lex, rex);
4592 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4593 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4597 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4598 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
4601 // C99 6.5.9p2 and C99 6.5.8p2
4602 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4603 RCanPointeeTy.getUnqualifiedType())) {
4604 // Valid unless a relational comparison of function pointers
4605 if (isRelational && LCanPointeeTy->isFunctionType()) {
4606 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4607 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4609 } else if (!isRelational &&
4610 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4611 // Valid unless comparison between non-null pointer and function pointer
4612 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4613 && !LHSIsNull && !RHSIsNull) {
4614 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4615 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4619 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4620 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4622 if (LCanPointeeTy != RCanPointeeTy)
4623 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4627 if (getLangOptions().CPlusPlus) {
4628 // Comparison of pointers with null pointer constants and equality
4629 // comparisons of member pointers to null pointer constants.
4631 (lType->isPointerType() ||
4632 (!isRelational && lType->isMemberPointerType()))) {
4633 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
4637 (rType->isPointerType() ||
4638 (!isRelational && rType->isMemberPointerType()))) {
4639 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
4643 // Comparison of member pointers.
4644 if (!isRelational &&
4645 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4647 // In addition, pointers to members can be compared, or a pointer to
4648 // member and a null pointer constant. Pointer to member conversions
4649 // (4.11) and qualification conversions (4.4) are performed to bring
4650 // them to a common type. If one operand is a null pointer constant,
4651 // the common type is the type of the other operand. Otherwise, the
4652 // common type is a pointer to member type similar (4.4) to the type
4653 // of one of the operands, with a cv-qualification signature (4.4)
4654 // that is the union of the cv-qualification signatures of the operand
4656 QualType T = FindCompositePointerType(lex, rex);
4658 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4659 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4663 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4664 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
4668 // Comparison of nullptr_t with itself.
4669 if (lType->isNullPtrType() && rType->isNullPtrType())
4673 // Handle block pointer types.
4674 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
4675 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4676 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
4678 if (!LHSIsNull && !RHSIsNull &&
4679 !Context.typesAreCompatible(lpointee, rpointee)) {
4680 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4681 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4683 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4686 // Allow block pointers to be compared with null pointer constants.
4688 && ((lType->isBlockPointerType() && rType->isPointerType())
4689 || (lType->isPointerType() && rType->isBlockPointerType()))) {
4690 if (!LHSIsNull && !RHSIsNull) {
4691 if (!((rType->isPointerType() && rType->getAs<PointerType>()
4692 ->getPointeeType()->isVoidType())
4693 || (lType->isPointerType() && lType->getAs<PointerType>()
4694 ->getPointeeType()->isVoidType())))
4695 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4696 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4698 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4702 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
4703 if (lType->isPointerType() || rType->isPointerType()) {
4704 const PointerType *LPT = lType->getAs<PointerType>();
4705 const PointerType *RPT = rType->getAs<PointerType>();
4706 bool LPtrToVoid = LPT ?
4707 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
4708 bool RPtrToVoid = RPT ?
4709 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
4711 if (!LPtrToVoid && !RPtrToVoid &&
4712 !Context.typesAreCompatible(lType, rType)) {
4713 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4714 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4716 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4719 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4720 if (!Context.areComparableObjCPointerTypes(lType, rType))
4721 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4722 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4723 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4727 if (lType->isAnyPointerType() && rType->isIntegerType()) {
4728 unsigned DiagID = 0;
4731 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4732 } else if (isRelational)
4733 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4735 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4739 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4741 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
4744 if (lType->isIntegerType() && rType->isAnyPointerType()) {
4745 unsigned DiagID = 0;
4748 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4749 } else if (isRelational)
4750 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4752 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4756 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4758 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
4761 // Handle block pointers.
4762 if (!isRelational && RHSIsNull
4763 && lType->isBlockPointerType() && rType->isIntegerType()) {
4764 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
4767 if (!isRelational && LHSIsNull
4768 && lType->isIntegerType() && rType->isBlockPointerType()) {
4769 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
4772 return InvalidOperands(Loc, lex, rex);
4775 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
4776 /// operates on extended vector types. Instead of producing an IntTy result,
4777 /// like a scalar comparison, a vector comparison produces a vector of integer
4779 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
4781 bool isRelational) {
4782 // Check to make sure we're operating on vectors of the same type and width,
4783 // Allowing one side to be a scalar of element type.
4784 QualType vType = CheckVectorOperands(Loc, lex, rex);
4788 QualType lType = lex->getType();
4789 QualType rType = rex->getType();
4791 // For non-floating point types, check for self-comparisons of the form
4792 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4793 // often indicate logic errors in the program.
4794 if (!lType->isFloatingType()) {
4795 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4796 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4797 if (DRL->getDecl() == DRR->getDecl())
4798 Diag(Loc, diag::warn_selfcomparison);
4801 // Check for comparisons of floating point operands using != and ==.
4802 if (!isRelational && lType->isFloatingType()) {
4803 assert (rType->isFloatingType());
4804 CheckFloatComparison(Loc,lex,rex);
4807 // Return the type for the comparison, which is the same as vector type for
4808 // integer vectors, or an integer type of identical size and number of
4809 // elements for floating point vectors.
4810 if (lType->isIntegerType())
4813 const VectorType *VTy = lType->getAs<VectorType>();
4814 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
4815 if (TypeSize == Context.getTypeSize(Context.IntTy))
4816 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
4817 if (TypeSize == Context.getTypeSize(Context.LongTy))
4818 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4820 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
4821 "Unhandled vector element size in vector compare");
4822 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4825 inline QualType Sema::CheckBitwiseOperands(
4826 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4827 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4828 return CheckVectorOperands(Loc, lex, rex);
4830 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4832 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4834 return InvalidOperands(Loc, lex, rex);
4837 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
4838 Expr *&lex, Expr *&rex, SourceLocation Loc) {
4839 UsualUnaryConversions(lex);
4840 UsualUnaryConversions(rex);
4842 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4843 return InvalidOperands(Loc, lex, rex);
4845 if (Context.getLangOptions().CPlusPlus) {
4846 // C++ [expr.log.and]p2
4847 // C++ [expr.log.or]p2
4848 return Context.BoolTy;
4851 return Context.IntTy;
4854 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4855 /// is a read-only property; return true if so. A readonly property expression
4856 /// depends on various declarations and thus must be treated specially.
4858 static bool IsReadonlyProperty(Expr *E, Sema &S) {
4859 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4860 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4861 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4862 QualType BaseType = PropExpr->getBase()->getType();
4863 if (const ObjCObjectPointerType *OPT =
4864 BaseType->getAsObjCInterfacePointerType())
4865 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4866 if (S.isPropertyReadonly(PDecl, IFace))
4873 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4874 /// emit an error and return true. If so, return false.
4875 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
4876 SourceLocation OrigLoc = Loc;
4877 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4879 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4880 IsLV = Expr::MLV_ReadonlyProperty;
4881 if (IsLV == Expr::MLV_Valid)
4885 bool NeedType = false;
4886 switch (IsLV) { // C99 6.5.16p2
4887 default: assert(0 && "Unknown result from isModifiableLvalue!");
4888 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
4889 case Expr::MLV_ArrayType:
4890 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4893 case Expr::MLV_NotObjectType:
4894 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4897 case Expr::MLV_LValueCast:
4898 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4900 case Expr::MLV_InvalidExpression:
4901 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4903 case Expr::MLV_IncompleteType:
4904 case Expr::MLV_IncompleteVoidType:
4905 return S.RequireCompleteType(Loc, E->getType(),
4906 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4907 << E->getSourceRange());
4908 case Expr::MLV_DuplicateVectorComponents:
4909 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4911 case Expr::MLV_NotBlockQualified:
4912 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4914 case Expr::MLV_ReadonlyProperty:
4915 Diag = diag::error_readonly_property_assignment;
4917 case Expr::MLV_NoSetterProperty:
4918 Diag = diag::error_nosetter_property_assignment;
4924 Assign = SourceRange(OrigLoc, OrigLoc);
4926 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
4928 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
4935 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4937 QualType CompoundType) {
4938 // Verify that LHS is a modifiable lvalue, and emit error if not.
4939 if (CheckForModifiableLvalue(LHS, Loc, *this))
4942 QualType LHSType = LHS->getType();
4943 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
4945 AssignConvertType ConvTy;
4946 if (CompoundType.isNull()) {
4947 // Simple assignment "x = y".
4948 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
4949 // Special case of NSObject attributes on c-style pointer types.
4950 if (ConvTy == IncompatiblePointer &&
4951 ((Context.isObjCNSObjectType(LHSType) &&
4952 RHSType->isObjCObjectPointerType()) ||
4953 (Context.isObjCNSObjectType(RHSType) &&
4954 LHSType->isObjCObjectPointerType())))
4955 ConvTy = Compatible;
4957 // If the RHS is a unary plus or minus, check to see if they = and + are
4958 // right next to each other. If so, the user may have typo'd "x =+ 4"
4959 // instead of "x += 4".
4960 Expr *RHSCheck = RHS;
4961 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4962 RHSCheck = ICE->getSubExpr();
4963 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4964 if ((UO->getOpcode() == UnaryOperator::Plus ||
4965 UO->getOpcode() == UnaryOperator::Minus) &&
4966 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
4967 // Only if the two operators are exactly adjacent.
4968 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4969 // And there is a space or other character before the subexpr of the
4970 // unary +/-. We don't want to warn on "x=-1".
4971 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4972 UO->getSubExpr()->getLocStart().isFileID()) {
4973 Diag(Loc, diag::warn_not_compound_assign)
4974 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4975 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
4979 // Compound assignment "x += y"
4980 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
4983 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4987 // C99 6.5.16p3: The type of an assignment expression is the type of the
4988 // left operand unless the left operand has qualified type, in which case
4989 // it is the unqualified version of the type of the left operand.
4990 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4991 // is converted to the type of the assignment expression (above).
4992 // C++ 5.17p1: the type of the assignment expression is that of its left
4994 return LHSType.getUnqualifiedType();
4998 QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
4999 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
5000 DefaultFunctionArrayConversion(RHS);
5002 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5003 // incomplete in C++).
5005 return RHS->getType();
5008 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5009 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
5010 QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5012 if (Op->isTypeDependent())
5013 return Context.DependentTy;
5015 QualType ResType = Op->getType();
5016 assert(!ResType.isNull() && "no type for increment/decrement expression");
5018 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5019 // Decrement of bool is not allowed.
5021 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5024 // Increment of bool sets it to true, but is deprecated.
5025 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5026 } else if (ResType->isRealType()) {
5028 } else if (ResType->isAnyPointerType()) {
5029 QualType PointeeTy = ResType->getPointeeType();
5031 // C99 6.5.2.4p2, 6.5.6p2
5032 if (PointeeTy->isVoidType()) {
5033 if (getLangOptions().CPlusPlus) {
5034 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5035 << Op->getSourceRange();
5039 // Pointer to void is a GNU extension in C.
5040 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
5041 } else if (PointeeTy->isFunctionType()) {
5042 if (getLangOptions().CPlusPlus) {
5043 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5044 << Op->getType() << Op->getSourceRange();
5048 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
5049 << ResType << Op->getSourceRange();
5050 } else if (RequireCompleteType(OpLoc, PointeeTy,
5051 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5052 << Op->getSourceRange()
5055 // Diagnose bad cases where we step over interface counts.
5056 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5057 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5058 << PointeeTy << Op->getSourceRange();
5061 } else if (ResType->isComplexType()) {
5062 // C99 does not support ++/-- on complex types, we allow as an extension.
5063 Diag(OpLoc, diag::ext_integer_increment_complex)
5064 << ResType << Op->getSourceRange();
5066 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
5067 << ResType << Op->getSourceRange();
5070 // At this point, we know we have a real, complex or pointer type.
5071 // Now make sure the operand is a modifiable lvalue.
5072 if (CheckForModifiableLvalue(Op, OpLoc, *this))
5077 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
5078 /// This routine allows us to typecheck complex/recursive expressions
5079 /// where the declaration is needed for type checking. We only need to
5080 /// handle cases when the expression references a function designator
5081 /// or is an lvalue. Here are some examples:
5083 /// - &*****f => f for f a function designator.
5085 /// - &s.zz[1].yy -> s, if zz is an array
5086 /// - *(x + 1) -> x, if x is an array
5087 /// - &"123"[2] -> 0
5088 /// - & __real__ x -> x
5089 static NamedDecl *getPrimaryDecl(Expr *E) {
5090 switch (E->getStmtClass()) {
5091 case Stmt::DeclRefExprClass:
5092 return cast<DeclRefExpr>(E)->getDecl();
5093 case Stmt::MemberExprClass:
5094 // If this is an arrow operator, the address is an offset from
5095 // the base's value, so the object the base refers to is
5097 if (cast<MemberExpr>(E)->isArrow())
5099 // Otherwise, the expression refers to a part of the base
5100 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
5101 case Stmt::ArraySubscriptExprClass: {
5102 // FIXME: This code shouldn't be necessary! We should catch the implicit
5103 // promotion of register arrays earlier.
5104 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5105 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5106 if (ICE->getSubExpr()->getType()->isArrayType())
5107 return getPrimaryDecl(ICE->getSubExpr());
5111 case Stmt::UnaryOperatorClass: {
5112 UnaryOperator *UO = cast<UnaryOperator>(E);
5114 switch(UO->getOpcode()) {
5115 case UnaryOperator::Real:
5116 case UnaryOperator::Imag:
5117 case UnaryOperator::Extension:
5118 return getPrimaryDecl(UO->getSubExpr());
5123 case Stmt::ParenExprClass:
5124 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
5125 case Stmt::ImplicitCastExprClass:
5126 // If the result of an implicit cast is an l-value, we care about
5127 // the sub-expression; otherwise, the result here doesn't matter.
5128 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
5134 /// CheckAddressOfOperand - The operand of & must be either a function
5135 /// designator or an lvalue designating an object. If it is an lvalue, the
5136 /// object cannot be declared with storage class register or be a bit field.
5137 /// Note: The usual conversions are *not* applied to the operand of the &
5138 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
5139 /// In C++, the operand might be an overloaded function name, in which case
5140 /// we allow the '&' but retain the overloaded-function type.
5141 QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
5142 // Make sure to ignore parentheses in subsequent checks
5143 op = op->IgnoreParens();
5145 if (op->isTypeDependent())
5146 return Context.DependentTy;
5148 if (getLangOptions().C99) {
5149 // Implement C99-only parts of addressof rules.
5150 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5151 if (uOp->getOpcode() == UnaryOperator::Deref)
5152 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5153 // (assuming the deref expression is valid).
5154 return uOp->getSubExpr()->getType();
5156 // Technically, there should be a check for array subscript
5157 // expressions here, but the result of one is always an lvalue anyway.
5159 NamedDecl *dcl = getPrimaryDecl(op);
5160 Expr::isLvalueResult lval = op->isLvalue(Context);
5162 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5164 // The operand must be either an l-value or a function designator
5165 if (!op->getType()->isFunctionType()) {
5166 // FIXME: emit more specific diag...
5167 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5168 << op->getSourceRange();
5171 } else if (op->getBitField()) { // C99 6.5.3.2p1
5172 // The operand cannot be a bit-field
5173 Diag(OpLoc, diag::err_typecheck_address_of)
5174 << "bit-field" << op->getSourceRange();
5176 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5177 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
5178 // The operand cannot be an element of a vector
5179 Diag(OpLoc, diag::err_typecheck_address_of)
5180 << "vector element" << op->getSourceRange();
5182 } else if (isa<ObjCPropertyRefExpr>(op)) {
5183 // cannot take address of a property expression.
5184 Diag(OpLoc, diag::err_typecheck_address_of)
5185 << "property expression" << op->getSourceRange();
5187 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5188 // FIXME: Can LHS ever be null here?
5189 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5190 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
5191 } else if (dcl) { // C99 6.5.3.2p1
5192 // We have an lvalue with a decl. Make sure the decl is not declared
5193 // with the register storage-class specifier.
5194 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5195 if (vd->getStorageClass() == VarDecl::Register) {
5196 Diag(OpLoc, diag::err_typecheck_address_of)
5197 << "register variable" << op->getSourceRange();
5200 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5201 isa<FunctionTemplateDecl>(dcl)) {
5202 return Context.OverloadTy;
5203 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
5204 // Okay: we can take the address of a field.
5205 // Could be a pointer to member, though, if there is an explicit
5206 // scope qualifier for the class.
5207 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
5208 DeclContext *Ctx = dcl->getDeclContext();
5209 if (Ctx && Ctx->isRecord()) {
5210 if (FD->getType()->isReferenceType()) {
5212 diag::err_cannot_form_pointer_to_member_of_reference_type)
5213 << FD->getDeclName() << FD->getType();
5217 return Context.getMemberPointerType(op->getType(),
5218 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
5221 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
5222 // Okay: we can take the address of a function.
5224 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5226 return Context.getMemberPointerType(op->getType(),
5227 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5228 } else if (!isa<FunctionDecl>(dcl))
5229 assert(0 && "Unknown/unexpected decl type");
5232 if (lval == Expr::LV_IncompleteVoidType) {
5233 // Taking the address of a void variable is technically illegal, but we
5234 // allow it in cases which are otherwise valid.
5235 // Example: "extern void x; void* y = &x;".
5236 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5239 // If the operand has type "type", the result has type "pointer to type".
5240 return Context.getPointerType(op->getType());
5243 QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
5244 if (Op->isTypeDependent())
5245 return Context.DependentTy;
5247 UsualUnaryConversions(Op);
5248 QualType Ty = Op->getType();
5250 // Note that per both C89 and C99, this is always legal, even if ptype is an
5251 // incomplete type or void. It would be possible to warn about dereferencing
5252 // a void pointer, but it's completely well-defined, and such a warning is
5253 // unlikely to catch any mistakes.
5254 if (const PointerType *PT = Ty->getAs<PointerType>())
5255 return PT->getPointeeType();
5257 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
5258 return OPT->getPointeeType();
5260 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
5261 << Ty << Op->getSourceRange();
5265 static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5266 tok::TokenKind Kind) {
5267 BinaryOperator::Opcode Opc;
5269 default: assert(0 && "Unknown binop!");
5270 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5271 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
5272 case tok::star: Opc = BinaryOperator::Mul; break;
5273 case tok::slash: Opc = BinaryOperator::Div; break;
5274 case tok::percent: Opc = BinaryOperator::Rem; break;
5275 case tok::plus: Opc = BinaryOperator::Add; break;
5276 case tok::minus: Opc = BinaryOperator::Sub; break;
5277 case tok::lessless: Opc = BinaryOperator::Shl; break;
5278 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5279 case tok::lessequal: Opc = BinaryOperator::LE; break;
5280 case tok::less: Opc = BinaryOperator::LT; break;
5281 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5282 case tok::greater: Opc = BinaryOperator::GT; break;
5283 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5284 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5285 case tok::amp: Opc = BinaryOperator::And; break;
5286 case tok::caret: Opc = BinaryOperator::Xor; break;
5287 case tok::pipe: Opc = BinaryOperator::Or; break;
5288 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5289 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5290 case tok::equal: Opc = BinaryOperator::Assign; break;
5291 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5292 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5293 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5294 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5295 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5296 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5297 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5298 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5299 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5300 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5301 case tok::comma: Opc = BinaryOperator::Comma; break;
5306 static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5307 tok::TokenKind Kind) {
5308 UnaryOperator::Opcode Opc;
5310 default: assert(0 && "Unknown unary op!");
5311 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5312 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5313 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5314 case tok::star: Opc = UnaryOperator::Deref; break;
5315 case tok::plus: Opc = UnaryOperator::Plus; break;
5316 case tok::minus: Opc = UnaryOperator::Minus; break;
5317 case tok::tilde: Opc = UnaryOperator::Not; break;
5318 case tok::exclaim: Opc = UnaryOperator::LNot; break;
5319 case tok::kw___real: Opc = UnaryOperator::Real; break;
5320 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5321 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5326 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
5327 /// operator @p Opc at location @c TokLoc. This routine only supports
5328 /// built-in operations; ActOnBinOp handles overloaded operators.
5329 Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5331 Expr *lhs, Expr *rhs) {
5332 QualType ResultTy; // Result type of the binary operator.
5333 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
5334 // The following two variables are used for compound assignment operators
5335 QualType CompLHSTy; // Type of LHS after promotions for computation
5336 QualType CompResultTy; // Type of computation result
5339 case BinaryOperator::Assign:
5340 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5342 case BinaryOperator::PtrMemD:
5343 case BinaryOperator::PtrMemI:
5344 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5345 Opc == BinaryOperator::PtrMemI);
5347 case BinaryOperator::Mul:
5348 case BinaryOperator::Div:
5349 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5351 case BinaryOperator::Rem:
5352 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5354 case BinaryOperator::Add:
5355 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5357 case BinaryOperator::Sub:
5358 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5360 case BinaryOperator::Shl:
5361 case BinaryOperator::Shr:
5362 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5364 case BinaryOperator::LE:
5365 case BinaryOperator::LT:
5366 case BinaryOperator::GE:
5367 case BinaryOperator::GT:
5368 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
5370 case BinaryOperator::EQ:
5371 case BinaryOperator::NE:
5372 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
5374 case BinaryOperator::And:
5375 case BinaryOperator::Xor:
5376 case BinaryOperator::Or:
5377 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5379 case BinaryOperator::LAnd:
5380 case BinaryOperator::LOr:
5381 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5383 case BinaryOperator::MulAssign:
5384 case BinaryOperator::DivAssign:
5385 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5386 CompLHSTy = CompResultTy;
5387 if (!CompResultTy.isNull())
5388 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5390 case BinaryOperator::RemAssign:
5391 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5392 CompLHSTy = CompResultTy;
5393 if (!CompResultTy.isNull())
5394 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5396 case BinaryOperator::AddAssign:
5397 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5398 if (!CompResultTy.isNull())
5399 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5401 case BinaryOperator::SubAssign:
5402 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5403 if (!CompResultTy.isNull())
5404 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5406 case BinaryOperator::ShlAssign:
5407 case BinaryOperator::ShrAssign:
5408 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5409 CompLHSTy = CompResultTy;
5410 if (!CompResultTy.isNull())
5411 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5413 case BinaryOperator::AndAssign:
5414 case BinaryOperator::XorAssign:
5415 case BinaryOperator::OrAssign:
5416 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5417 CompLHSTy = CompResultTy;
5418 if (!CompResultTy.isNull())
5419 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5421 case BinaryOperator::Comma:
5422 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5425 if (ResultTy.isNull())
5427 if (CompResultTy.isNull())
5428 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5430 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
5431 CompLHSTy, CompResultTy,
5435 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5436 /// ParenRange in parentheses.
5437 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5438 const PartialDiagnostic &PD,
5439 SourceRange ParenRange)
5441 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5442 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5443 // We can't display the parentheses, so just dig the
5444 // warning/error and return.
5450 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5451 << CodeModificationHint::CreateInsertion(EndLoc, ")");
5454 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5455 /// operators are mixed in a way that suggests that the programmer forgot that
5456 /// comparison operators have higher precedence. The most typical example of
5457 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
5458 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5459 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
5460 typedef BinaryOperator BinOp;
5461 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5462 rhsopc = static_cast<BinOp::Opcode>(-1);
5463 if (BinOp *BO = dyn_cast<BinOp>(lhs))
5464 lhsopc = BO->getOpcode();
5465 if (BinOp *BO = dyn_cast<BinOp>(rhs))
5466 rhsopc = BO->getOpcode();
5468 // Subs are not binary operators.
5469 if (lhsopc == -1 && rhsopc == -1)
5472 // Bitwise operations are sometimes used as eager logical ops.
5473 // Don't diagnose this.
5474 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5475 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
5478 if (BinOp::isComparisonOp(lhsopc))
5479 SuggestParentheses(Self, OpLoc,
5480 PDiag(diag::warn_precedence_bitwise_rel)
5481 << SourceRange(lhs->getLocStart(), OpLoc)
5482 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5483 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5484 else if (BinOp::isComparisonOp(rhsopc))
5485 SuggestParentheses(Self, OpLoc,
5486 PDiag(diag::warn_precedence_bitwise_rel)
5487 << SourceRange(OpLoc, rhs->getLocEnd())
5488 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5489 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
5492 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5493 /// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5494 /// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5495 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5496 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
5497 if (BinaryOperator::isBitwiseOp(Opc))
5498 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5501 // Binary Operators. 'Tok' is the token for the operator.
5502 Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5503 tok::TokenKind Kind,
5504 ExprArg LHS, ExprArg RHS) {
5505 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
5506 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
5508 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5509 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
5511 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5512 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5514 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
5517 Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
5518 BinaryOperator::Opcode Opc,
5519 Expr *lhs, Expr *rhs) {
5520 if (getLangOptions().CPlusPlus &&
5521 (lhs->getType()->isOverloadableType() ||
5522 rhs->getType()->isOverloadableType())) {
5523 // Find all of the overloaded operators visible from this
5524 // point. We perform both an operator-name lookup from the local
5525 // scope and an argument-dependent lookup based on the types of
5527 FunctionSet Functions;
5528 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5529 if (OverOp != OO_None) {
5531 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5533 Expr *Args[2] = { lhs, rhs };
5534 DeclarationName OpName
5535 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5536 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
5539 // Build the (potentially-overloaded, potentially-dependent)
5540 // binary operation.
5541 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
5544 // Build a built-in binary operation.
5545 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
5548 Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5551 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5553 // FIXME: Input is modified below, but InputArg is not updated appropriately.
5554 Expr *Input = (Expr *)InputArg.get();
5555 QualType resultType;
5557 case UnaryOperator::OffsetOf:
5558 assert(false && "Invalid unary operator");
5561 case UnaryOperator::PreInc:
5562 case UnaryOperator::PreDec:
5563 case UnaryOperator::PostInc:
5564 case UnaryOperator::PostDec:
5565 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
5566 Opc == UnaryOperator::PreInc ||
5567 Opc == UnaryOperator::PostInc);
5569 case UnaryOperator::AddrOf:
5570 resultType = CheckAddressOfOperand(Input, OpLoc);
5572 case UnaryOperator::Deref:
5573 DefaultFunctionArrayConversion(Input);
5574 resultType = CheckIndirectionOperand(Input, OpLoc);
5576 case UnaryOperator::Plus:
5577 case UnaryOperator::Minus:
5578 UsualUnaryConversions(Input);
5579 resultType = Input->getType();
5580 if (resultType->isDependentType())
5582 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5584 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5585 resultType->isEnumeralType())
5587 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5588 Opc == UnaryOperator::Plus &&
5589 resultType->isPointerType())
5592 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5593 << resultType << Input->getSourceRange());
5594 case UnaryOperator::Not: // bitwise complement
5595 UsualUnaryConversions(Input);
5596 resultType = Input->getType();
5597 if (resultType->isDependentType())
5599 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5600 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5601 // C99 does not support '~' for complex conjugation.
5602 Diag(OpLoc, diag::ext_integer_complement_complex)
5603 << resultType << Input->getSourceRange();
5604 else if (!resultType->isIntegerType())
5605 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5606 << resultType << Input->getSourceRange());
5608 case UnaryOperator::LNot: // logical negation
5609 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5610 DefaultFunctionArrayConversion(Input);
5611 resultType = Input->getType();
5612 if (resultType->isDependentType())
5614 if (!resultType->isScalarType()) // C99 6.5.3.3p1
5615 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5616 << resultType << Input->getSourceRange());
5617 // LNot always has type int. C99 6.5.3.3p5.
5618 // In C++, it's bool. C++ 5.3.1p8
5619 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
5621 case UnaryOperator::Real:
5622 case UnaryOperator::Imag:
5623 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
5625 case UnaryOperator::Extension:
5626 resultType = Input->getType();
5629 if (resultType.isNull())
5633 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
5636 Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5637 UnaryOperator::Opcode Opc,
5639 Expr *Input = (Expr*)input.get();
5640 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5641 // Find all of the overloaded operators visible from this
5642 // point. We perform both an operator-name lookup from the local
5643 // scope and an argument-dependent lookup based on the types of
5645 FunctionSet Functions;
5646 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5647 if (OverOp != OO_None) {
5649 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5651 DeclarationName OpName
5652 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5653 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
5656 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5659 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5662 // Unary Operators. 'Tok' is the token for the operator.
5663 Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5664 tok::TokenKind Op, ExprArg input) {
5665 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
5668 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5669 Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5670 SourceLocation LabLoc,
5671 IdentifierInfo *LabelII) {
5672 // Look up the record for this label identifier.
5673 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
5675 // If we haven't seen this label yet, create a forward reference. It
5676 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
5678 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
5680 // Create the AST node. The address of a label always has type 'void*'.
5681 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5682 Context.getPointerType(Context.VoidTy)));
5685 Sema::OwningExprResult
5686 Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5687 SourceLocation RPLoc) { // "({..})"
5688 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
5689 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5690 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5692 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5694 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
5696 // FIXME: there are a variety of strange constraints to enforce here, for
5697 // example, it is not possible to goto into a stmt expression apparently.
5698 // More semantic analysis is needed.
5700 // If there are sub stmts in the compound stmt, take the type of the last one
5701 // as the type of the stmtexpr.
5702 QualType Ty = Context.VoidTy;
5704 if (!Compound->body_empty()) {
5705 Stmt *LastStmt = Compound->body_back();
5706 // If LastStmt is a label, skip down through into the body.
5707 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5708 LastStmt = Label->getSubStmt();
5710 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
5711 Ty = LastExpr->getType();
5714 // FIXME: Check that expression type is complete/non-abstract; statement
5715 // expressions are not lvalues.
5718 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
5721 Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5722 SourceLocation BuiltinLoc,
5723 SourceLocation TypeLoc,
5725 OffsetOfComponent *CompPtr,
5726 unsigned NumComponents,
5727 SourceLocation RPLoc) {
5728 // FIXME: This function leaks all expressions in the offset components on
5730 // FIXME: Preserve type source info.
5731 QualType ArgTy = GetTypeFromParser(argty);
5732 assert(!ArgTy.isNull() && "Missing type argument!");
5734 bool Dependent = ArgTy->isDependentType();
5736 // We must have at least one component that refers to the type, and the first
5737 // one is known to be a field designator. Verify that the ArgTy represents
5738 // a struct/union/class.
5739 if (!Dependent && !ArgTy->isRecordType())
5740 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
5742 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5743 // with an incomplete type would be illegal.
5745 // Otherwise, create a null pointer as the base, and iteratively process
5746 // the offsetof designators.
5747 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5748 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
5749 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
5750 ArgTy, SourceLocation());
5752 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5753 // GCC extension, diagnose them.
5754 // FIXME: This diagnostic isn't actually visible because the location is in
5756 if (NumComponents != 1)
5757 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5758 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
5761 bool DidWarnAboutNonPOD = false;
5763 if (RequireCompleteType(TypeLoc, Res->getType(),
5764 diag::err_offsetof_incomplete_type))
5767 // FIXME: Dependent case loses a lot of information here. And probably
5768 // leaks like a sieve.
5769 for (unsigned i = 0; i != NumComponents; ++i) {
5770 const OffsetOfComponent &OC = CompPtr[i];
5771 if (OC.isBrackets) {
5772 // Offset of an array sub-field. TODO: Should we allow vector elements?
5773 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5775 Res->Destroy(Context);
5776 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5780 // FIXME: C++: Verify that operator[] isn't overloaded.
5782 // Promote the array so it looks more like a normal array subscript
5784 DefaultFunctionArrayConversion(Res);
5787 Expr *Idx = static_cast<Expr*>(OC.U.E);
5789 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
5790 return ExprError(Diag(Idx->getLocStart(),
5791 diag::err_typecheck_subscript_not_integer)
5792 << Idx->getSourceRange());
5794 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5799 const RecordType *RC = Res->getType()->getAs<RecordType>();
5801 Res->Destroy(Context);
5802 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5806 // Get the decl corresponding to this.
5807 RecordDecl *RD = RC->getDecl();
5808 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5809 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
5810 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5811 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5813 DidWarnAboutNonPOD = true;
5818 LookupQualifiedName(R, RD, OC.U.IdentInfo, LookupMemberName);
5820 FieldDecl *MemberDecl
5821 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
5824 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5825 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
5827 // FIXME: C++: Verify that MemberDecl isn't a static field.
5828 // FIXME: Verify that MemberDecl isn't a bitfield.
5829 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
5830 Res = BuildAnonymousStructUnionMemberReference(
5831 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
5833 // MemberDecl->getType() doesn't get the right qualifiers, but it
5834 // doesn't matter here.
5835 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5836 MemberDecl->getType().getNonReferenceType());
5841 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5842 Context.getSizeType(), BuiltinLoc));
5846 Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5847 TypeTy *arg1,TypeTy *arg2,
5848 SourceLocation RPLoc) {
5849 // FIXME: Preserve type source info.
5850 QualType argT1 = GetTypeFromParser(arg1);
5851 QualType argT2 = GetTypeFromParser(arg2);
5853 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
5855 if (getLangOptions().CPlusPlus) {
5856 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5857 << SourceRange(BuiltinLoc, RPLoc);
5861 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5862 argT1, argT2, RPLoc));
5865 Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5867 ExprArg expr1, ExprArg expr2,
5868 SourceLocation RPLoc) {
5869 Expr *CondExpr = static_cast<Expr*>(cond.get());
5870 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5871 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
5873 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5876 bool ValueDependent = false;
5877 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
5878 resType = Context.DependentTy;
5879 ValueDependent = true;
5881 // The conditional expression is required to be a constant expression.
5882 llvm::APSInt condEval(32);
5883 SourceLocation ExpLoc;
5884 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
5885 return ExprError(Diag(ExpLoc,
5886 diag::err_typecheck_choose_expr_requires_constant)
5887 << CondExpr->getSourceRange());
5889 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5890 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5891 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5892 : RHSExpr->isValueDependent();
5895 cond.release(); expr1.release(); expr2.release();
5896 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5898 resType->isDependentType(),
5902 //===----------------------------------------------------------------------===//
5903 // Clang Extensions.
5904 //===----------------------------------------------------------------------===//
5906 /// ActOnBlockStart - This callback is invoked when a block literal is started.
5907 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
5908 // Analyze block parameters.
5909 BlockSemaInfo *BSI = new BlockSemaInfo();
5911 // Add BSI to CurBlock.
5912 BSI->PrevBlockInfo = CurBlock;
5915 BSI->ReturnType = QualType();
5916 BSI->TheScope = BlockScope;
5917 BSI->hasBlockDeclRefExprs = false;
5918 BSI->hasPrototype = false;
5919 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5920 CurFunctionNeedsScopeChecking = false;
5922 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
5923 PushDeclContext(BlockScope, BSI->TheDecl);
5926 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
5927 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
5929 if (ParamInfo.getNumTypeObjects() == 0
5930 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5931 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5932 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5934 if (T->isArrayType()) {
5935 Diag(ParamInfo.getSourceRange().getBegin(),
5936 diag::err_block_returns_array);
5940 // The parameter list is optional, if there was none, assume ().
5941 if (!T->isFunctionType())
5942 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5944 CurBlock->hasPrototype = true;
5945 CurBlock->isVariadic = false;
5946 // Check for a valid sentinel attribute on this block.
5947 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5948 Diag(ParamInfo.getAttributes()->getLoc(),
5949 diag::warn_attribute_sentinel_not_variadic) << 1;
5950 // FIXME: remove the attribute.
5952 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
5954 // Do not allow returning a objc interface by-value.
5955 if (RetTy->isObjCInterfaceType()) {
5956 Diag(ParamInfo.getSourceRange().getBegin(),
5957 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5963 // Analyze arguments to block.
5964 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5965 "Not a function declarator!");
5966 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
5968 CurBlock->hasPrototype = FTI.hasPrototype;
5969 CurBlock->isVariadic = true;
5971 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5972 // no arguments, not a function that takes a single void argument.
5973 if (FTI.hasPrototype &&
5974 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5975 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5976 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
5977 // empty arg list, don't push any params.
5978 CurBlock->isVariadic = false;
5979 } else if (FTI.hasPrototype) {
5980 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
5981 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
5982 CurBlock->isVariadic = FTI.isVariadic;
5984 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
5985 CurBlock->Params.size());
5986 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
5987 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5988 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5989 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5990 // If this has an identifier, add it to the scope stack.
5991 if ((*AI)->getIdentifier())
5992 PushOnScopeChains(*AI, CurBlock->TheScope);
5994 // Check for a valid sentinel attribute on this block.
5995 if (!CurBlock->isVariadic &&
5996 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5997 Diag(ParamInfo.getAttributes()->getLoc(),
5998 diag::warn_attribute_sentinel_not_variadic) << 1;
5999 // FIXME: remove the attribute.
6002 // Analyze the return type.
6003 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6004 QualType RetTy = T->getAs<FunctionType>()->getResultType();
6006 // Do not allow returning a objc interface by-value.
6007 if (RetTy->isObjCInterfaceType()) {
6008 Diag(ParamInfo.getSourceRange().getBegin(),
6009 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6010 } else if (!RetTy->isDependentType())
6011 CurBlock->ReturnType = RetTy;
6014 /// ActOnBlockError - If there is an error parsing a block, this callback
6015 /// is invoked to pop the information about the block from the action impl.
6016 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6017 // Ensure that CurBlock is deleted.
6018 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
6020 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6022 // Pop off CurBlock, handle nested blocks.
6024 CurBlock = CurBlock->PrevBlockInfo;
6025 // FIXME: Delete the ParmVarDecl objects as well???
6028 /// ActOnBlockStmtExpr - This is called when the body of a block statement
6029 /// literal was successfully completed. ^(int x){...}
6030 Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6031 StmtArg body, Scope *CurScope) {
6032 // If blocks are disabled, emit an error.
6033 if (!LangOpts.Blocks)
6034 Diag(CaretLoc, diag::err_blocks_disable);
6036 // Ensure that CurBlock is deleted.
6037 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
6041 // Pop off CurBlock, handle nested blocks.
6042 CurBlock = CurBlock->PrevBlockInfo;
6044 QualType RetTy = Context.VoidTy;
6045 if (!BSI->ReturnType.isNull())
6046 RetTy = BSI->ReturnType;
6048 llvm::SmallVector<QualType, 8> ArgTypes;
6049 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6050 ArgTypes.push_back(BSI->Params[i]->getType());
6052 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
6054 if (!BSI->hasPrototype)
6055 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6058 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
6059 BSI->isVariadic, 0, false, false, 0, 0,
6062 // FIXME: Check that return/parameter types are complete/non-abstract
6063 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
6064 BlockTy = Context.getBlockPointerType(BlockTy);
6066 // If needed, diagnose invalid gotos and switches in the block.
6067 if (CurFunctionNeedsScopeChecking)
6068 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6069 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
6071 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
6072 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
6073 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6074 BSI->hasBlockDeclRefExprs));
6077 Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6078 ExprArg expr, TypeTy *type,
6079 SourceLocation RPLoc) {
6080 QualType T = GetTypeFromParser(type);
6081 Expr *E = static_cast<Expr*>(expr.get());
6084 InitBuiltinVaListType();
6086 // Get the va_list type
6087 QualType VaListType = Context.getBuiltinVaListType();
6088 if (VaListType->isArrayType()) {
6089 // Deal with implicit array decay; for example, on x86-64,
6090 // va_list is an array, but it's supposed to decay to
6091 // a pointer for va_arg.
6092 VaListType = Context.getArrayDecayedType(VaListType);
6093 // Make sure the input expression also decays appropriately.
6094 UsualUnaryConversions(E);
6096 // Otherwise, the va_list argument must be an l-value because
6097 // it is modified by va_arg.
6098 if (!E->isTypeDependent() &&
6099 CheckForModifiableLvalue(E, BuiltinLoc, *this))
6103 if (!E->isTypeDependent() &&
6104 !Context.hasSameType(VaListType, E->getType())) {
6105 return ExprError(Diag(E->getLocStart(),
6106 diag::err_first_argument_to_va_arg_not_of_type_va_list)
6107 << OrigExpr->getType() << E->getSourceRange());
6110 // FIXME: Check that type is complete/non-abstract
6111 // FIXME: Warn if a non-POD type is passed in.
6114 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6118 Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
6119 // The type of __null will be int or long, depending on the size of
6120 // pointers on the target.
6122 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6125 Ty = Context.LongTy;
6127 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
6130 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6132 QualType DstType, QualType SrcType,
6133 Expr *SrcExpr, const char *Flavor) {
6134 // Decode the result (notice that AST's are still created for extensions).
6135 bool isInvalid = false;
6138 default: assert(0 && "Unknown conversion type");
6139 case Compatible: return false;
6141 DiagKind = diag::ext_typecheck_convert_pointer_int;
6144 DiagKind = diag::ext_typecheck_convert_int_pointer;
6146 case IncompatiblePointer:
6147 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6149 case IncompatiblePointerSign:
6150 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6152 case FunctionVoidPointer:
6153 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6155 case CompatiblePointerDiscardsQualifiers:
6156 // If the qualifiers lost were because we were applying the
6157 // (deprecated) C++ conversion from a string literal to a char*
6158 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6159 // Ideally, this check would be performed in
6160 // CheckPointerTypesForAssignment. However, that would require a
6161 // bit of refactoring (so that the second argument is an
6162 // expression, rather than a type), which should be done as part
6163 // of a larger effort to fix CheckPointerTypesForAssignment for
6165 if (getLangOptions().CPlusPlus &&
6166 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6168 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6170 case IntToBlockPointer:
6171 DiagKind = diag::err_int_to_block_pointer;
6173 case IncompatibleBlockPointer:
6174 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
6176 case IncompatibleObjCQualifiedId:
6177 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
6178 // it can give a more specific diagnostic.
6179 DiagKind = diag::warn_incompatible_qualified_id;
6181 case IncompatibleVectors:
6182 DiagKind = diag::warn_incompatible_vectors;
6185 DiagKind = diag::err_typecheck_convert_incompatible;
6190 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
6191 << SrcExpr->getSourceRange();
6195 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
6196 llvm::APSInt ICEResult;
6197 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6199 *Result = ICEResult;
6203 Expr::EvalResult EvalResult;
6205 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
6206 EvalResult.HasSideEffects) {
6207 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6209 if (EvalResult.Diag) {
6210 // We only show the note if it's not the usual "invalid subexpression"
6211 // or if it's actually in a subexpression.
6212 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6213 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6214 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6220 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6221 E->getSourceRange();
6223 if (EvalResult.Diag &&
6224 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6225 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6228 *Result = EvalResult.Val.getInt();
6232 Sema::ExpressionEvaluationContext
6233 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
6234 // Introduce a new set of potentially referenced declarations to the stack.
6235 if (NewContext == PotentiallyPotentiallyEvaluated)
6236 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
6238 std::swap(ExprEvalContext, NewContext);
6243 Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6244 ExpressionEvaluationContext NewContext) {
6245 ExprEvalContext = NewContext;
6247 if (OldContext == PotentiallyPotentiallyEvaluated) {
6248 // Mark any remaining declarations in the current position of the stack
6249 // as "referenced". If they were not meant to be referenced, semantic
6250 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6251 PotentiallyReferencedDecls RemainingDecls;
6252 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6253 PotentiallyReferencedDeclStack.pop_back();
6255 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6256 IEnd = RemainingDecls.end();
6258 MarkDeclarationReferenced(I->first, I->second);
6262 /// \brief Note that the given declaration was referenced in the source code.
6264 /// This routine should be invoke whenever a given declaration is referenced
6265 /// in the source code, and where that reference occurred. If this declaration
6266 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6267 /// C99 6.9p3), then the declaration will be marked as used.
6269 /// \param Loc the location where the declaration was referenced.
6271 /// \param D the declaration that has been referenced by the source code.
6272 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6273 assert(D && "No declaration?");
6278 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6279 // template or not. The reason for this is that unevaluated expressions
6280 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6281 // -Wunused-parameters)
6282 if (isa<ParmVarDecl>(D) ||
6283 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
6286 // Do not mark anything as "used" within a dependent context; wait for
6287 // an instantiation.
6288 if (CurContext->isDependentContext())
6291 switch (ExprEvalContext) {
6293 // We are in an expression that is not potentially evaluated; do nothing.
6296 case PotentiallyEvaluated:
6297 // We are in a potentially-evaluated expression, so this declaration is
6298 // "used"; handle this below.
6301 case PotentiallyPotentiallyEvaluated:
6302 // We are in an expression that may be potentially evaluated; queue this
6303 // declaration reference until we know whether the expression is
6304 // potentially evaluated.
6305 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6309 // Note that this declaration has been used.
6310 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
6312 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6313 if (!Constructor->isUsed())
6314 DefineImplicitDefaultConstructor(Loc, Constructor);
6315 } else if (Constructor->isImplicit() &&
6316 Constructor->isCopyConstructor(Context, TypeQuals)) {
6317 if (!Constructor->isUsed())
6318 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6320 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6321 if (Destructor->isImplicit() && !Destructor->isUsed())
6322 DefineImplicitDestructor(Loc, Destructor);
6324 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6325 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6326 MethodDecl->getOverloadedOperator() == OO_Equal) {
6327 if (!MethodDecl->isUsed())
6328 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6331 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
6332 // Implicit instantiation of function templates and member functions of
6334 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
6335 bool AlreadyInstantiated = false;
6336 if (FunctionTemplateSpecializationInfo *SpecInfo
6337 = Function->getTemplateSpecializationInfo()) {
6338 if (SpecInfo->getPointOfInstantiation().isInvalid())
6339 SpecInfo->setPointOfInstantiation(Loc);
6340 else if (SpecInfo->getTemplateSpecializationKind()
6341 == TSK_ImplicitInstantiation)
6342 AlreadyInstantiated = true;
6343 } else if (MemberSpecializationInfo *MSInfo
6344 = Function->getMemberSpecializationInfo()) {
6345 if (MSInfo->getPointOfInstantiation().isInvalid())
6346 MSInfo->setPointOfInstantiation(Loc);
6347 else if (MSInfo->getTemplateSpecializationKind()
6348 == TSK_ImplicitInstantiation)
6349 AlreadyInstantiated = true;
6352 if (!AlreadyInstantiated)
6353 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6356 // FIXME: keep track of references to static functions
6357 Function->setUsed(true);
6361 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
6362 // Implicit instantiation of static data members of class templates.
6363 if (Var->isStaticDataMember() &&
6364 Var->getInstantiatedFromStaticDataMember()) {
6365 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6366 assert(MSInfo && "Missing member specialization information?");
6367 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6368 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6369 MSInfo->setPointOfInstantiation(Loc);
6370 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6374 // FIXME: keep track of references to static data?
6381 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6382 CallExpr *CE, FunctionDecl *FD) {
6383 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6386 PartialDiagnostic Note =
6387 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6388 << FD->getDeclName() : PDiag();
6389 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6391 if (RequireCompleteType(Loc, ReturnType,
6393 PDiag(diag::err_call_function_incomplete_return)
6394 << CE->getSourceRange() << FD->getDeclName() :
6395 PDiag(diag::err_call_incomplete_return)
6396 << CE->getSourceRange(),
6397 std::make_pair(NoteLoc, Note)))
6403 // Diagnose the common s/=/==/ typo. Note that adding parentheses
6404 // will prevent this condition from triggering, which is what we want.
6405 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6408 if (isa<BinaryOperator>(E)) {
6409 BinaryOperator *Op = cast<BinaryOperator>(E);
6410 if (Op->getOpcode() != BinaryOperator::Assign)
6413 Loc = Op->getOperatorLoc();
6414 } else if (isa<CXXOperatorCallExpr>(E)) {
6415 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6416 if (Op->getOperator() != OO_Equal)
6419 Loc = Op->getOperatorLoc();
6421 // Not an assignment.
6425 SourceLocation Open = E->getSourceRange().getBegin();
6426 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
6428 Diag(Loc, diag::warn_condition_is_assignment)
6429 << E->getSourceRange()
6430 << CodeModificationHint::CreateInsertion(Open, "(")
6431 << CodeModificationHint::CreateInsertion(Close, ")");
6434 bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6435 DiagnoseAssignmentAsCondition(E);
6437 if (!E->isTypeDependent()) {
6438 DefaultFunctionArrayConversion(E);
6440 QualType T = E->getType();
6442 if (getLangOptions().CPlusPlus) {
6443 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6445 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6446 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6447 << T << E->getSourceRange();